-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbit_test.cc
99 lines (91 loc) · 2.34 KB
/
bit_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Bit tests
#include "bit.h"
#include "print.h"
#include "tests.h"
#include <random>
namespace mandelbrot {
namespace {
using std::mt19937;
using std::mt19937_64;
using std::remove_reference_t;
TEST(countl_zero) {
const auto test = [](const auto zero) {
typedef decltype(zero) I;
const int bits = 8 * sizeof(zero);
ASSERT_EQ(countl_zero(I(0)), bits);
for (int i = 0; i < bits; i++)
for (int j = 0; j <= i; j++)
ASSERT_EQ(countl_zero(I(1) << i | I(1) << j), bits - 1 - i);
};
test(uint32_t(0));
test(uint64_t(0));
}
TEST(countr_zero) {
const auto test = [](const auto zero) {
typedef decltype(zero) I;
const int bits = 8 * sizeof(zero);
ASSERT_EQ(countr_zero(I(0)), bits);
for (int i = 0; i < bits; i++)
for (int j = 0; j <= i; j++)
ASSERT_EQ(countr_zero(I(1) << i | I(1) << j), j);
};
test(uint32_t(0));
test(uint64_t(0));
}
TEST(bit_ceil) {
const auto test = [](const auto zero) {
typedef decltype(zero) I;
const int bits = 8 * sizeof(zero);
ASSERT_EQ(bit_ceil(I(0)), I(1));
for (int i = 0; i < bits; i++) {
ASSERT_EQ(bit_ceil(I(1) << i), I(1) << i)
<< tfm::format("i %d, 1<<i %d, bit_ceil %d", i, I(1) << i, bit_ceil(I(1) << i));
if (i + 1 < bits) {
for (int j = 0; j < i; j++)
ASSERT_EQ(bit_ceil(I(1) << i | I(1) << j), I(1) << (i+1));
}
}
};
test(uint32_t(0));
test(uint64_t(0));
}
TEST(byteswap) {
mt19937_64 mt(7);
const auto test = [&mt](auto zero) {
typedef decltype(zero) I;
const auto slow = [](I n) {
const int bytes = sizeof(I);
I s = 0;
for (int i = 0; i < bytes; i++)
s |= ((n >> 8*i) & 0xff) << 8*(bytes-1-i);
return s;
};
for (int i = 0; i < 1024; i++) {
const I n = mt();
ASSERT_EQ(byteswap(n), slow(n));
}
};
test(uint32_t(0));
test(uint64_t(0));
}
TEST(bitreverse) {
mt19937_64 mt(7);
const auto test = [&mt](auto zero) {
typedef decltype(zero) I;
const auto slow = [](I n) {
const int bits = 8*sizeof(I);
I s = 0;
for (int i = 0; i < bits; i++)
s |= ((n >> i) & 1) << (bits-1-i);
return s;
};
for (int i = 0; i < 1024; i++) {
const I n = mt();
ASSERT_EQ(bitreverse(n), slow(n));
}
};
test(uint32_t(0));
test(uint64_t(0));
}
} // namespace
} // namespace mandelbrot