Guillaume Chatelet | 3cc8f31 | 2020-10-12 08:55:20 +0000 | [diff] [blame] | 1 | // Copyright 2017 Google LLC |
Guillaume Chatelet | 439d371 | 2018-02-01 10:03:09 +0100 | [diff] [blame] | 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | #include "internal/bit_utils.h" |
| 16 | |
| 17 | #include "gtest/gtest.h" |
| 18 | |
| 19 | namespace cpu_features { |
| 20 | namespace { |
| 21 | |
| 22 | TEST(UtilsTest, IsBitSet) { |
| 23 | for (size_t bit_set = 0; bit_set < 32; ++bit_set) { |
| 24 | const uint32_t value = 1UL << bit_set; |
Leonard Mosescu | bdb36d9 | 2019-07-03 05:57:19 -0700 | [diff] [blame] | 25 | for (uint32_t i = 0; i < 32; ++i) { |
Guillaume Chatelet | 439d371 | 2018-02-01 10:03:09 +0100 | [diff] [blame] | 26 | EXPECT_EQ(IsBitSet(value, i), i == bit_set); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // testing 0, all bits should be 0. |
Leonard Mosescu | bdb36d9 | 2019-07-03 05:57:19 -0700 | [diff] [blame] | 31 | for (uint32_t i = 0; i < 32; ++i) { |
Guillaume Chatelet | 439d371 | 2018-02-01 10:03:09 +0100 | [diff] [blame] | 32 | EXPECT_FALSE(IsBitSet(0, i)); |
| 33 | } |
| 34 | |
| 35 | // testing ~0, all bits should be 1. |
Leonard Mosescu | bdb36d9 | 2019-07-03 05:57:19 -0700 | [diff] [blame] | 36 | for (uint32_t i = 0; i < 32; ++i) { |
Guillaume Chatelet | 439d371 | 2018-02-01 10:03:09 +0100 | [diff] [blame] | 37 | EXPECT_TRUE(IsBitSet(-1, i)); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | TEST(UtilsTest, ExtractBitRange) { |
| 42 | // Extracting all bits gives the same number. |
| 43 | EXPECT_EQ(ExtractBitRange(123, 31, 0), 123); |
| 44 | // Extracting 1 bit gives parity. |
| 45 | EXPECT_EQ(ExtractBitRange(123, 0, 0), 1); |
| 46 | EXPECT_EQ(ExtractBitRange(122, 0, 0), 0); |
| 47 | |
| 48 | EXPECT_EQ(ExtractBitRange(0xF0, 7, 4), 0xF); |
| 49 | EXPECT_EQ(ExtractBitRange(0x42 << 2, 10, 2), 0x42); |
| 50 | } |
| 51 | |
| 52 | } // namespace |
| 53 | } // namespace cpu_features |