blob: 1dad0f453199dac37a2c45da57765f72a2a15f82 [file] [log] [blame]
apatrick@google.com0265b732009-11-19 08:08:39 +09001// 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"
primiano47c69062015-07-25 05:13:32 +09008
9#include <limits>
10
apatrick@google.com0265b732009-11-19 08:08:39 +090011#include "testing/gtest/include/gtest/gtest.h"
12
13namespace base {
14namespace bits {
15
16TEST(BitsTest, Log2Floor) {
17 EXPECT_EQ(-1, Log2Floor(0));
18 EXPECT_EQ(0, Log2Floor(1));
19 EXPECT_EQ(1, Log2Floor(2));
20 EXPECT_EQ(1, Log2Floor(3));
21 EXPECT_EQ(2, Log2Floor(4));
22 for (int i = 3; i < 31; ++i) {
23 unsigned int value = 1U << i;
24 EXPECT_EQ(i, Log2Floor(value));
25 EXPECT_EQ(i, Log2Floor(value + 1));
26 EXPECT_EQ(i, Log2Floor(value + 2));
27 EXPECT_EQ(i - 1, Log2Floor(value - 1));
28 EXPECT_EQ(i - 1, Log2Floor(value - 2));
29 }
30 EXPECT_EQ(31, Log2Floor(0xffffffffU));
31}
32
33TEST(BitsTest, Log2Ceiling) {
34 EXPECT_EQ(-1, Log2Ceiling(0));
35 EXPECT_EQ(0, Log2Ceiling(1));
36 EXPECT_EQ(1, Log2Ceiling(2));
37 EXPECT_EQ(2, Log2Ceiling(3));
38 EXPECT_EQ(2, Log2Ceiling(4));
39 for (int i = 3; i < 31; ++i) {
40 unsigned int value = 1U << i;
41 EXPECT_EQ(i, Log2Ceiling(value));
42 EXPECT_EQ(i + 1, Log2Ceiling(value + 1));
43 EXPECT_EQ(i + 1, Log2Ceiling(value + 2));
44 EXPECT_EQ(i, Log2Ceiling(value - 1));
45 EXPECT_EQ(i, Log2Ceiling(value - 2));
46 }
47 EXPECT_EQ(32, Log2Ceiling(0xffffffffU));
48}
49
primiano47c69062015-07-25 05:13:32 +090050TEST(BitsTest, Align) {
51 const size_t kSizeTMax = std::numeric_limits<size_t>::max();
52 EXPECT_EQ(0ul, Align(0, 4));
53 EXPECT_EQ(4ul, Align(1, 4));
54 EXPECT_EQ(4096ul, Align(1, 4096));
55 EXPECT_EQ(4096ul, Align(4096, 4096));
56 EXPECT_EQ(4096ul, Align(4095, 4096));
57 EXPECT_EQ(8192ul, Align(4097, 4096));
58 EXPECT_EQ(kSizeTMax - 31, Align(kSizeTMax - 62, 32));
59 EXPECT_EQ(kSizeTMax / 2 + 1, Align(1, kSizeTMax / 2 + 1));
60}
61
apatrick@google.com0265b732009-11-19 08:08:39 +090062} // namespace bits
63} // namespace base