blob: 3874e1309379e3db68d5ffe97c46a1cb70c5d99b [file] [log] [blame]
Guillaume Chatelet3cc8f312020-10-12 08:55:20 +00001// Copyright 2017 Google LLC
Guillaume Chatelet439d3712018-02-01 10:03:09 +01002//
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
19namespace cpu_features {
20namespace {
21
22TEST(UtilsTest, IsBitSet) {
23 for (size_t bit_set = 0; bit_set < 32; ++bit_set) {
24 const uint32_t value = 1UL << bit_set;
Leonard Mosescubdb36d92019-07-03 05:57:19 -070025 for (uint32_t i = 0; i < 32; ++i) {
Guillaume Chatelet439d3712018-02-01 10:03:09 +010026 EXPECT_EQ(IsBitSet(value, i), i == bit_set);
27 }
28 }
29
30 // testing 0, all bits should be 0.
Leonard Mosescubdb36d92019-07-03 05:57:19 -070031 for (uint32_t i = 0; i < 32; ++i) {
Guillaume Chatelet439d3712018-02-01 10:03:09 +010032 EXPECT_FALSE(IsBitSet(0, i));
33 }
34
35 // testing ~0, all bits should be 1.
Leonard Mosescubdb36d92019-07-03 05:57:19 -070036 for (uint32_t i = 0; i < 32; ++i) {
Guillaume Chatelet439d3712018-02-01 10:03:09 +010037 EXPECT_TRUE(IsBitSet(-1, i));
38 }
39}
40
41TEST(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