26 class BitVectorTest :
public testing::Test {
28 void SetUp()
override {
29 std::locale::global(std::locale(
""));
43 int factor_limit = static_cast<int>(sqrt(1.0 +
kPrimeLimit));
44 for (
int f = 3; f <= factor_limit; f += 2) {
57 if (map[i]) ++total_primes;
59 EXPECT_EQ(168, total_primes);
60 EXPECT_TRUE(map[997]);
61 EXPECT_FALSE(map[998]);
62 EXPECT_FALSE(map[999]);
65 void TestAll(
const BitVector& map,
bool value) {
66 for (
int i = 0; i < map.
size(); ++i) {
67 EXPECT_EQ(value, map[i]);
74 void SetBitPattern(
int start_byte,
int end_byte,
int spacing,
BitVector* bv) {
75 bv->
Init((end_byte - start_byte) * 8 * spacing);
76 for (
int byte_value = start_byte; byte_value < end_byte; ++byte_value) {
77 for (
int bit = 0; bit < 8; ++bit) {
78 if (byte_value & (1 << bit))
79 bv->
SetBit((byte_value - start_byte) * 8 * spacing + bit);
86 void ExpectCorrectBits(
const BitVector& bv) {
88 int prev_bit_index = -1;
89 int num_bits_tested = 0;
90 while ((bit_index = bv.
NextSetBit(bit_index)) >= 0) {
91 EXPECT_LT(bit_index, bv.
size());
93 for (
int i = prev_bit_index + 1; i < bit_index; ++i) {
94 EXPECT_EQ(0, bv[i]) <<
"i = " << i <<
" prev = " << prev_bit_index;
97 EXPECT_EQ(1, bv[bit_index]) <<
"Bit index = " << bit_index;
99 prev_bit_index = bit_index;
102 for (
int i = prev_bit_index + 1; i < bv.
size(); ++i) {
110 TEST_F(BitVectorTest, Primes) {
122 std::string filename = OutputNameToPath(
"primesbitvector");
123 FILE* fp = fopen(filename.c_str(),
"wb");
124 CHECK(fp !=
nullptr);
127 fp = fopen(filename.c_str(),
"rb");
128 CHECK(fp !=
nullptr);
132 TestPrimes(read_map);
136 TEST_F(BitVectorTest, SetAll) {
149 TEST_F(BitVectorTest, TestNextSetBit) {
151 for (
int spacing = 1; spacing <= 5; ++spacing) {
152 SetBitPattern(0, 256, spacing, &bv);
153 ExpectCorrectBits(bv);
159 TEST_F(BitVectorTest, TestNumSetBits) {
161 for (
int byte = 0;
byte < 256; ++byte) {
162 SetBitPattern(
byte,
byte + 1, 1, &bv);
163 ExpectCorrectBits(bv);