1 // Copyright (c) 2009 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // This file contains the unit tests for the bit utilities. 6 7 #include "base/bits.h" 8 9 #include <stddef.h> 10 11 #include <limits> 12 13 #include "testing/gtest/include/gtest/gtest.h" 14 15 namespace base { 16 namespace bits { 17 18 TEST(BitsTest, Log2Floor) { 19 EXPECT_EQ(-1, Log2Floor(0)); 20 EXPECT_EQ(0, Log2Floor(1)); 21 EXPECT_EQ(1, Log2Floor(2)); 22 EXPECT_EQ(1, Log2Floor(3)); 23 EXPECT_EQ(2, Log2Floor(4)); 24 for (int i = 3; i < 31; ++i) { 25 unsigned int value = 1U << i; 26 EXPECT_EQ(i, Log2Floor(value)); 27 EXPECT_EQ(i, Log2Floor(value + 1)); 28 EXPECT_EQ(i, Log2Floor(value + 2)); 29 EXPECT_EQ(i - 1, Log2Floor(value - 1)); 30 EXPECT_EQ(i - 1, Log2Floor(value - 2)); 31 } 32 EXPECT_EQ(31, Log2Floor(0xffffffffU)); 33 } 34 35 TEST(BitsTest, Log2Ceiling) { 36 EXPECT_EQ(-1, Log2Ceiling(0)); 37 EXPECT_EQ(0, Log2Ceiling(1)); 38 EXPECT_EQ(1, Log2Ceiling(2)); 39 EXPECT_EQ(2, Log2Ceiling(3)); 40 EXPECT_EQ(2, Log2Ceiling(4)); 41 for (int i = 3; i < 31; ++i) { 42 unsigned int value = 1U << i; 43 EXPECT_EQ(i, Log2Ceiling(value)); 44 EXPECT_EQ(i + 1, Log2Ceiling(value + 1)); 45 EXPECT_EQ(i + 1, Log2Ceiling(value + 2)); 46 EXPECT_EQ(i, Log2Ceiling(value - 1)); 47 EXPECT_EQ(i, Log2Ceiling(value - 2)); 48 } 49 EXPECT_EQ(32, Log2Ceiling(0xffffffffU)); 50 } 51 52 TEST(BitsTest, Align) { 53 const size_t kSizeTMax = std::numeric_limits<size_t>::max(); 54 EXPECT_EQ(0ul, Align(0, 4)); 55 EXPECT_EQ(4ul, Align(1, 4)); 56 EXPECT_EQ(4096ul, Align(1, 4096)); 57 EXPECT_EQ(4096ul, Align(4096, 4096)); 58 EXPECT_EQ(4096ul, Align(4095, 4096)); 59 EXPECT_EQ(8192ul, Align(4097, 4096)); 60 EXPECT_EQ(kSizeTMax - 31, Align(kSizeTMax - 62, 32)); 61 EXPECT_EQ(kSizeTMax / 2 + 1, Align(1, kSizeTMax / 2 + 1)); 62 } 63 64 } // namespace bits 65 } // namespace base 66