Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
bitarray.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
38#include <gtest/gtest.h>
39
40#include <bitArray.H>
41
42// Under ASan, the bytes that the program has allocated can be read: a test
43// checks with them that a move allocates nothing. DynArray takes its
44// directory from malloc(), which the operator new of a test cannot count
45#if defined(__SANITIZE_ADDRESS__)
46# define BITARRAY_TEST_READS_ALLOCATED_BYTES 1
47#elif defined(__has_feature)
48# if __has_feature(address_sanitizer)
49# define BITARRAY_TEST_READS_ALLOCATED_BYTES 1
50# endif
51#endif
52#ifdef BITARRAY_TEST_READS_ALLOCATED_BYTES
53# include <cstddef>
54// Of the runtime of ASan. GCC does not ship <sanitizer/allocator_interface.h>
55extern "C" size_t __sanitizer_get_current_allocated_bytes();
56#endif
57
58#include <cstdint>
59#include <limits>
60#include <random>
61#include <sstream>
62#include <string>
63#include <type_traits>
64#include <vector>
65
66using namespace Aleph;
67using namespace std;
68
69namespace {
70
71struct SavedBitArray
72{
73 size_t num_bytes = 0;
74 size_t num_bits = 0;
75 vector<int> bytes;
76};
77
78SavedBitArray save_and_parse(const BitArray &arr)
79{
80 ostringstream out;
81 arr.save(out);
82
83 istringstream in(out.str());
84 SavedBitArray parsed;
85 in >> parsed.num_bytes >> parsed.num_bits;
86 parsed.bytes.reserve(parsed.num_bytes);
87 for (size_t i = 0; i < parsed.num_bytes; ++i)
88 {
89 int value = 0;
90 in >> value;
91 parsed.bytes.push_back(value);
92 }
93 return parsed;
94}
95
96string bits_to_string(const vector<unsigned int> &bits)
97{
98 string out;
99 out.reserve(bits.size());
100 for (auto bit : bits)
101 out.push_back(bit ? '1' : '0');
102 return out;
103}
104
105template <typename U>
106string to_bit_string(U value, const size_t num_bits)
107{
108 string out;
109 out.reserve(num_bits);
110 for (size_t i = 0; i < num_bits; ++i)
111 {
112 const size_t shift = num_bits - i - 1;
113 const bool bit = ((value >> shift) & U(1)) != 0;
114 out.push_back(bit ? '1' : '0');
115 }
116 return out;
117}
118
119template <typename T>
120string expected_set_num_bits(const T value)
121{
122 using U = std::make_unsigned_t<T>;
123 const U u = static_cast<U>(value);
124 return to_bit_string(u, sizeof(T) * 8);
125}
126
127vector<unsigned int> random_bits(mt19937 &rng, const size_t n)
128{
129 bernoulli_distribution dist(0.5);
130 vector<unsigned int> bits;
131 bits.reserve(n);
132 for (size_t i = 0; i < n; ++i)
133 bits.push_back(dist(rng) ? 1u : 0u);
134 return bits;
135}
136
137BitArray from_bits(const vector<unsigned int> &bits)
138{
139 BitArray arr(bits.size());
140 for (size_t i = 0; i < bits.size(); ++i)
141 if (bits[i])
142 arr.write_bit(i, 1);
143 return arr;
144}
145
146vector<unsigned int> or_bits(const vector<unsigned int> &a,
147 const vector<unsigned int> &b)
148{
149 const size_t n = max(a.size(), b.size());
150 vector<unsigned int> out(n, 0);
151 for (size_t i = 0; i < n; ++i)
152 {
153 const unsigned int lhs = i < a.size() ? a[i] : 0u;
154 const unsigned int rhs = i < b.size() ? b[i] : 0u;
155 out[i] = lhs | rhs;
156 }
157 return out;
158}
159
160vector<unsigned int> and_bits(const vector<unsigned int> &a,
161 const vector<unsigned int> &b)
162{
163 const size_t n = min(a.size(), b.size());
164 vector<unsigned int> out(n, 0);
165 for (size_t i = 0; i < n; ++i)
166 out[i] = a[i] & b[i];
167 return out;
168}
169
170TEST(BitArrayBasics, construction_size_and_defaults)
171{
172 BitArray empty;
173 EXPECT_EQ(empty.size(), 0u);
174 EXPECT_THROW((void) empty.read_bit(0), std::out_of_range);
175
176 BitArray a(10);
177 EXPECT_EQ(a.size(), 10u);
178 for (size_t i = 0; i < a.size(); ++i)
179 EXPECT_EQ(a.read_bit(i), 0);
180
181 BitArray ones(10, 1);
182 EXPECT_EQ(ones.size(), 10u);
183 EXPECT_EQ(ones.count_ones(), 10);
184 EXPECT_EQ(ones.count_zeros(), 0);
185 EXPECT_EQ(ones.get_bit_str(), string(10, '1'));
186}
187
188TEST(ByteBasics, read_write_and_int_roundtrip)
189{
190 static_assert(sizeof(Byte) == 1);
191
192 Byte b;
193 EXPECT_EQ(b.get_int(), 0);
194 EXPECT_EQ(b.count_ones(), 0);
195 EXPECT_EQ(b.count_zeros(), 8);
196
197 b.write_bit(0, 1);
198 b.write_bit(2, 1);
199 EXPECT_EQ(b.get_int(), 0b00000101);
200 EXPECT_EQ(b.read_bit(0), 1u);
201 EXPECT_EQ(b.read_bit(1), 0u);
202 EXPECT_EQ(b.read_bit(2), 1u);
203
204 b.set_int(0xA5); // 1010'0101
205 EXPECT_EQ(b.get_int(), 0xA5);
206 EXPECT_EQ(b.read_bit(0), 1u);
207 EXPECT_EQ(b.read_bit(2), 1u);
208 EXPECT_EQ(b.read_bit(5), 1u);
209 EXPECT_EQ(b.read_bit(7), 1u);
210 EXPECT_EQ(b.count_ones(), 4);
211 EXPECT_EQ(b.count_zeros(), 4);
212}
213
214TEST(BitArrayProxy, writes_extend_size_and_copy_from_sparse_proxy)
215{
216 BitArray a;
217 a[0] = 1;
218 EXPECT_EQ(a.size(), 1u);
219 EXPECT_EQ(a.read_bit(0), 1);
220
221 a[10] = 1;
222 EXPECT_EQ(a.size(), 11u);
223 EXPECT_EQ(a.read_bit(0), 1);
224 EXPECT_EQ(a.read_bit(9), 0);
225 EXPECT_EQ(a.read_bit(10), 1);
226
227 BitArray sparse(40'000); // sized, but blocks not allocated
228 BitArray b;
229 EXPECT_NO_THROW(b[0] = sparse[0]);
230 EXPECT_EQ(b.size(), 1u);
231 EXPECT_EQ(b.read_bit(0), 0);
232
233 const BitArray c(1);
234 EXPECT_THROW((void) c[1], std::out_of_range);
235}
236
237TEST(BitArraySizing, set_size_computes_byte_count_correctly)
238{
239 BitArray a;
240
241 a.set_size(1);
242 {
243 const auto saved = save_and_parse(a);
244 EXPECT_EQ(saved.num_bytes, 1u);
245 EXPECT_EQ(saved.num_bits, 1u);
246 }
247
248 a.set_size(16);
249 {
250 const auto saved = save_and_parse(a);
251 EXPECT_EQ(saved.num_bytes, 2u);
252 EXPECT_EQ(saved.num_bits, 16u);
253 }
254
255 a.set_size(17);
256 {
257 const auto saved = save_and_parse(a);
258 EXPECT_EQ(saved.num_bytes, 3u);
259 EXPECT_EQ(saved.num_bits, 17u);
260 }
261}
262
263// set_size() computed its bytes as (size + 7) / 8, which wraps for the last
264// seven sizes of size_t: the array freed its bytes and took the size, so
265// that an array that held 101 read 000. A size whose bytes do not fit in a
266// DynArray is refused now, before anything is allocated, and the array
267// keeps its bits
268TEST(BitArraySizing, set_size_refuses_a_size_that_it_cannot_hold)
269{
270 constexpr size_t max = numeric_limits<size_t>::max();
271 const size_t max_bytes = DynArray<Byte>::Max_Dim_Allowed;
272 for (const size_t sz : {max, max - 1, max - 6, max - 7, max - 8, size_t(1) << 62,
273 size_t(1) << 61, max_bytes * 8 + 1, max_bytes * 8 + 8})
274 {
275 SCOPED_TRACE(sz);
276 BitArray a;
277 a.set_bit_str("101");
278 EXPECT_THROW(a.set_size(sz), length_error);
279 EXPECT_THROW(a.reserve(sz), length_error);
280 ASSERT_EQ(a.size(), 3u); // before the bits of an array that took the size
281 EXPECT_EQ(a.get_bit_str(), "101");
282
283 a.set_size(10); // and it goes on
284 EXPECT_EQ(a.size(), 10u);
285 EXPECT_EQ(a.get_bit_str(), "1010000000");
286 }
287}
288
289// set_size() keeps the bytes of its size and no more: after shrinking to a
290// multiple of 8 bits, the bits that come back when the array grows again
291// are 0, not those that the byte after them held
292TEST(BitArraySizing, bits_that_come_back_after_shrinking_are_zero)
293{
294 for (const size_t down : {0u, 1u, 7u, 8u, 9u, 15u})
295 {
296 SCOPED_TRACE(down);
297 BitArray a;
298 a.set_bit_str("1111111111111111");
299 a.set_size(down);
300 a.set_size(16);
301 EXPECT_EQ(a.get_bit_str(), string(down, '1') + string(16 - down, '0'));
302 }
303}
304
305TEST(BitArrayAccess, reserve_enables_fast_read_write)
306{
307 BitArray a;
308 a.reserve(9);
309 EXPECT_EQ(a.size(), 9u);
310
311 a.write(8, 1);
312 EXPECT_EQ(a.read(8), 1);
313 EXPECT_EQ(a.read_bit(8), 1);
314}
315
316TEST(BitArrayAccess, reading_unallocated_bytes_returns_zero)
317{
318 BitArray a;
319 a.write_bit(40'000, 1);
320 EXPECT_EQ(a.size(), 40'001u);
321 EXPECT_EQ(a.read_bit(0), 0);
322 EXPECT_EQ(a.read_bit(1), 0);
323 EXPECT_EQ(a.read_bit(39'999), 0);
324 EXPECT_EQ(a.read_bit(40'000), 1);
325}
326
327TEST(BitArrayStackOps, push_pop_and_empty)
328{
329 BitArray a;
330 EXPECT_THROW(a.pop(), std::underflow_error);
331
332 a.push(1);
333 a.push(0);
334 a.push(1);
335 EXPECT_EQ(a.size(), 3u);
336 EXPECT_EQ(a.get_bit_str(), "101");
337
338 a.pop();
339 EXPECT_EQ(a.size(), 2u);
340 EXPECT_EQ(a.get_bit_str(), "10");
341 EXPECT_THROW((void) a.read_bit(2), std::out_of_range);
342
343 a.empty();
344 EXPECT_EQ(a.size(), 0u);
345}
346
347TEST(BitArrayPersistence, save_load_roundtrip)
348{
349 BitArray a;
350 a.set_bit_str("10110011");
351 a.write_bit(40'000, 1); // force sparse blocks
352
353 ostringstream out;
354 a.save(out);
355
356 istringstream in(out.str());
357 BitArray b;
358 b.load(in);
359
360 EXPECT_TRUE(a == b);
361 EXPECT_EQ(b.size(), a.size());
362 EXPECT_EQ(b.read_bit(40'000), 1);
363}
364
365// The coherence of the header summed num_bits + 7, which wraps: a header
366// of 0 bytes and 2^64 - 1 bits passed, and the array claimed that many bits
367// with no byte, so that save() walked 2^61 bytes
368TEST(BitArrayPersistence, load_rejects_a_header_whose_bits_wrap)
369{
370 const size_t max = numeric_limits<size_t>::max();
371 for (const size_t bits : {max, max - 6})
372 {
373 BitArray a;
374 a.set_bit_str("101");
375 istringstream in("0 " + to_string(bits) + "\n");
376 EXPECT_THROW(a.load(in), std::runtime_error) << bits;
377 ASSERT_EQ(a.size(), 3u) << bits; // else get_bit_str() does not end
378 EXPECT_EQ(a.get_bit_str(), "101") << bits;
379 }
380}
381
382// A header is checked before anything is reserved: the bytes it claims
383// cannot be more than a DynArray holds. It made room for all of them, on
384// the word of the header, before the first byte was read: 128 MB for a
385// header of 2^44 bytes, 8 GB for one of 2^50
386TEST(BitArrayPersistence, load_rejects_a_header_with_too_many_bytes)
387{
388 const unsigned long long bytes = DynArray<Byte>::Max_Dim_Allowed + 1;
389 BitArray a;
390 a.set_bit_str("101");
391 istringstream in(to_string(bytes) + " " + to_string(8 * bytes) + "\n");
392 try
393 {
394 a.load(in);
395 ADD_FAILURE() << "load() accepted the header";
396 }
397 catch (const std::runtime_error & e)
398 {
399 EXPECT_NE(string(e.what()).find("too many bytes"), string::npos)
400 << e.what();
401 }
402 EXPECT_EQ(a.get_bit_str(), "101");
403}
404
405// A header that claims more bytes than the input has fails when the input
406// ends, and leaves the array as it was
407TEST(BitArrayPersistence, load_of_a_truncated_payload_throws)
408{
409 BitArray a;
410 a.set_bit_str("101");
411 istringstream in("3 17\n1 2\n");
412 EXPECT_THROW(a.load(in), std::runtime_error);
413 EXPECT_EQ(a.get_bit_str(), "101");
414}
415
416TEST(BitArrayPersistence, load_from_array_of_chars_roundtrip)
417{
418 BitArray a;
419 a.set_bit_str("10110011");
420
421 const auto saved = save_and_parse(a);
422 vector<unsigned char> bytes;
423 bytes.reserve(saved.num_bytes);
424 for (int value : saved.bytes)
425 bytes.push_back(static_cast<unsigned char>(value));
426
427 BitArray b;
428 b.load_from_array_of_chars(bytes.data(), saved.num_bits);
429 EXPECT_TRUE(a == b);
430}
431
432TEST(BitArrayShifts, fixed_and_dynamic_shifts)
433{
434 BitArray a;
435 a.set_bit_str("10110011");
436
437 BitArray left = a;
438 left.left_shift(2);
439 EXPECT_EQ(left.get_bit_str(), "11001100");
440
441 BitArray right = a;
442 right.right_shift(2);
443 EXPECT_EQ(right.get_bit_str(), "00101100");
444
445 BitArray dyn = a;
446 dyn.dyn_left_shift(2);
447 EXPECT_EQ(dyn.get_bit_str(), "1011001100");
448 dyn.dyn_right_shift(2);
449 EXPECT_EQ(dyn.get_bit_str(), a.get_bit_str());
450
451 BitArray too_much = a;
452 too_much.dyn_right_shift(1'000);
453 EXPECT_EQ(too_much.size(), 1u);
454 EXPECT_EQ(too_much.get_bit_str(), "0");
455}
456
457TEST(BitArrayShifts, circular_shifts)
458{
459 BitArray a;
460 a.set_bit_str("10110011");
461
462 BitArray left = a;
463 left.circular_left_shift(10); // 10 % 8 == 2
464 EXPECT_EQ(left.get_bit_str(), "11001110");
465
466 BitArray right = a;
467 right.circular_right_shift(10); // 10 % 8 == 2
468 EXPECT_EQ(right.get_bit_str(), "11101100");
469
470 BitArray empty;
471 EXPECT_NO_THROW(empty.circular_left_shift(3));
472 EXPECT_NO_THROW(empty.circular_right_shift(3));
473}
474
475TEST(BitArrayBitwiseOps, or_and_with_different_sizes)
476{
477 BitArray a;
478 a.set_bit_str("10101");
479
480 BitArray b;
481 b.set_bit_str("00110011");
482
483 BitArray c = a | b;
484 EXPECT_EQ(c.get_bit_str(), "10111011");
485
486 BitArray d = a & b;
487 EXPECT_EQ(d.get_bit_str(), "00100");
488}
489
490TEST(BitArrayBitwiseOps, or_does_not_leak_rhs_unused_bits_after_shrink)
491{
492 BitArray rhs;
493 rhs.set_size(16);
494 for (size_t i = 9; i < 16; ++i)
495 rhs.write_bit(i, 1);
496 rhs.set_size(9); // last byte still exists, but bits 9..15 are out of range
497
498 BitArray lhs;
499 lhs.set_size(16);
500 lhs |= rhs;
501
502 for (size_t i = 9; i < 16; ++i)
503 EXPECT_EQ(lhs.read_bit(i), 0);
504}
505
506TEST(BitArrayBitwiseOps, or_masks_rhs_unused_bits_from_load)
507{
508 // num_bits is not multiple of 8; extra bits in last byte must not leak.
509 const unsigned char bytes[] = {0x00, 0xFF};
510 BitArray rhs;
511 rhs.load_from_array_of_chars(bytes, 9);
512
513 BitArray lhs;
514 lhs.set_size(16);
515 lhs |= rhs;
516
517 EXPECT_EQ(lhs.read_bit(8), 1);
518 for (size_t i = 9; i < 16; ++i)
519 EXPECT_EQ(lhs.read_bit(i), 0);
520}
521
522TEST(BitArraySizing, shrink_then_write_bit_growth_keeps_new_bits_zeroed)
523{
524 BitArray a;
525 a.set_size(16);
526 a.write_bit(8, 1);
527 for (size_t i = 9; i < 16; ++i)
528 a.write_bit(i, 1);
529
530 a.set_size(9);
531 EXPECT_EQ(a.read_bit(8), 1);
532
533 // Extend without set_size(), so intermediate bits must already be cleared.
534 a.write_bit(15, 0);
535 EXPECT_EQ(a.size(), 16u);
536 EXPECT_EQ(a.read_bit(8), 1);
537 for (size_t i = 9; i < 15; ++i)
538 EXPECT_EQ(a.read_bit(i), 0);
539}
540
541TEST(BitArrayFunctional, iterator_and_traverse)
542{
543 BitArray a;
544 a.set_bit_str("101");
545
546 auto it = a.get_it();
547 ASSERT_TRUE(it.has_curr());
548 EXPECT_EQ(it.get_curr(), 1u);
549 it.next();
550 EXPECT_EQ(it.get_curr(), 0u);
551 it.next();
552 EXPECT_EQ(it.get_curr(), 1u);
553 it.next();
554 EXPECT_FALSE(it.has_curr());
555 EXPECT_EQ(it.get_curr_ne(), 0u);
556
557 struct StopOnOne
558 {
559 int visited = 0;
560 bool operator()(int bit)
561 {
562 ++visited;
563 return bit == 0;
564 }
565 };
566
567 BitArray b;
568 b.set_bit_str("000100");
569 StopOnOne op;
570 const bool completed = b.traverse(op);
571 EXPECT_FALSE(completed);
572 EXPECT_EQ(op.visited, 4);
573}
574
575TEST(BitArrayIterator, unbound_iterator_corner_cases)
576{
578 EXPECT_FALSE(it.has_curr());
579 EXPECT_EQ(it.get_curr_ne(), 0u);
580 EXPECT_THROW((void) it.get_curr(), std::overflow_error);
581 EXPECT_NO_THROW(it.end()); // should be a no-op and not crash
582 EXPECT_THROW(it.next(), std::overflow_error);
583 EXPECT_THROW(it.prev(), std::underflow_error);
584}
585
586TEST(BitArrayIterator, empty_array_iterator_corner_cases)
587{
588 BitArray empty;
589 auto it = empty.get_it();
590 EXPECT_FALSE(it.has_curr());
591 EXPECT_EQ(it.get_curr_ne(), 0u);
592 EXPECT_THROW((void) it.get_curr(), std::overflow_error);
593 EXPECT_THROW(it.next(), std::overflow_error);
594
595 it.reset_last();
596 EXPECT_FALSE(it.has_curr());
597 EXPECT_THROW(it.prev(), std::underflow_error);
598 EXPECT_NO_THROW(it.end());
599}
600
601TEST(BitArrayNumbers, set_num_bit_strings_and_numeric_roundtrip)
602{
603 BitArray a;
604
605 a.set_num<std::uint8_t>(0);
606 EXPECT_EQ(a.size(), 8u);
607 EXPECT_EQ(a.get_bit_str(), expected_set_num_bits<std::uint8_t>(0));
608 EXPECT_EQ(a.get_unum(), 0ul);
609 EXPECT_EQ(a.get_num(), 0l);
610
611 a.set_num<std::uint8_t>(0xA5);
612 EXPECT_EQ(a.get_bit_str(), expected_set_num_bits<std::uint8_t>(0xA5));
613 EXPECT_EQ(a.get_unum(), 0xA5ul);
614 EXPECT_EQ(a.get_num(), 0xA5l);
615
616 a.set_num<std::int8_t>(-1);
617 EXPECT_EQ(a.get_bit_str(), expected_set_num_bits<std::int8_t>(-1));
618 EXPECT_EQ(a.get_unum(), 255ul);
619 EXPECT_EQ(a.get_num(), 255l);
620
621 a.set_num<std::int8_t>(-2);
622 EXPECT_EQ(a.get_bit_str(), expected_set_num_bits<std::int8_t>(-2));
623 EXPECT_EQ(a.get_unum(), 254ul);
624 EXPECT_EQ(a.get_num(), 254l);
625
626 a.set_num<std::int16_t>(-2);
627 EXPECT_EQ(a.size(), 16u);
628 EXPECT_EQ(a.get_bit_str(), expected_set_num_bits<std::int16_t>(-2));
629 EXPECT_EQ(a.get_unum(), 65534ul);
630 EXPECT_EQ(a.get_num(), 65534l);
631
632 a.set_num<long>(-1);
633 EXPECT_EQ(a.size(), sizeof(long) * 8);
634 EXPECT_EQ(a.get_bit_str(), expected_set_num_bits<long>(-1));
635 EXPECT_EQ(a.get_unum(), std::numeric_limits<unsigned long>::max());
636}
637
638TEST(BitArrayNumbers, get_unum_ignores_bits_beyond_unsigned_long_width)
639{
640 constexpr size_t ul_bits = sizeof(unsigned long) * 8;
641 constexpr size_t extra = 5;
642
643 BitArray a(ul_bits + extra);
644 a.write_bit(0, 1); // outside get_unum() window
645 a.write_bit(a.size() - 1, 1); // LSB within get_unum() window
646 EXPECT_EQ(a.get_unum(), 1ul);
647}
648
649TEST(BitArrayRandomized, matches_reference_or_and_counts)
650{
651 mt19937 rng(12345);
652
653 for (int iter = 0; iter < 50; ++iter)
654 {
655 const size_t n1 = rng() % 200;
656 const size_t n2 = rng() % 200;
657
658 const auto bits1 = random_bits(rng, n1);
659 const auto bits2 = random_bits(rng, n2);
660
661 const BitArray a = from_bits(bits1);
662 const BitArray b = from_bits(bits2);
663
664 const auto expected_or = or_bits(bits1, bits2);
665 const auto expected_and = and_bits(bits1, bits2);
666
667 const BitArray got_or = a | b;
668 const BitArray got_and = a & b;
669
670 EXPECT_EQ(got_or.get_bit_str(), bits_to_string(expected_or));
671 EXPECT_EQ(got_and.get_bit_str(), bits_to_string(expected_and));
672
673 const int ones = got_or.count_ones();
674 int expected_ones = 0;
675 for (auto bit : expected_or)
676 expected_ones += static_cast<int>(bit);
677 EXPECT_EQ(ones, expected_ones);
678 EXPECT_EQ(got_or.count_zeros(), static_cast<int>(got_or.size()) - ones);
679 }
680}
681
682TEST(BitArrayCopyMove, copy_constructor_and_assignment)
683{
684 BitArray a;
685 a.set_bit_str("10110011");
686
687 // Copy constructor
688 BitArray b(a);
689 EXPECT_EQ(b.get_bit_str(), a.get_bit_str());
690 EXPECT_TRUE(b == a);
691
692 // Modify b, a should not change
693 b.write_bit(0, 0);
694 EXPECT_NE(b.get_bit_str(), a.get_bit_str());
695 EXPECT_EQ(a.read_bit(0), 1);
696
697 // Copy assignment
698 BitArray c;
699 c = a;
700 EXPECT_EQ(c.get_bit_str(), a.get_bit_str());
701 EXPECT_TRUE(c == a);
702
703 // Self assignment
704 c = c;
705 EXPECT_EQ(c.get_bit_str(), a.get_bit_str());
706}
707
708TEST(BitArrayCopyMove, move_constructor_and_assignment)
709{
710 BitArray a;
711 a.set_bit_str("10110011");
712 const string original = a.get_bit_str();
713
714 // Move constructor
715 BitArray b(std::move(a));
716 EXPECT_EQ(b.get_bit_str(), original);
717 EXPECT_EQ(a.size(), 0u); // a should be empty after move
718
719 // Move assignment
720 BitArray c;
721 c.set_bit_str("111");
722 c = std::move(b);
723 EXPECT_EQ(c.get_bit_str(), original);
724 EXPECT_EQ(b.size(), 0u); // b should be empty after move
725}
726
727// The move constructor built an empty array first, whose directory is an
728// allocation, inside a constructor that is noexcept: without memory for it,
729// the program ended. It takes the bytes of its source, which is left
730// without them and takes bits again.
731TEST(BitArrayCopyMove, move_constructor_leaves_a_source_that_takes_bits_again)
732{
733 static_assert(std::is_nothrow_move_constructible_v<BitArray>);
734
735 for (const size_t n : {0u, 1u, 8u, 9u, 100u, 40000u})
736 {
737 BitArray a;
738 for (size_t i = 0; i < n; ++i)
739 a.push(i % 3 == 0);
740 const string original = a.get_bit_str();
741
742#ifdef BITARRAY_TEST_READS_ALLOCATED_BYTES
743 const size_t allocated = __sanitizer_get_current_allocated_bytes();
744#endif
745 BitArray b(std::move(a));
746#ifdef BITARRAY_TEST_READS_ALLOCATED_BYTES
747 EXPECT_EQ(__sanitizer_get_current_allocated_bytes(), allocated) << "the move allocated";
748#endif
749 EXPECT_EQ(b.size(), n);
750 EXPECT_EQ(b.get_bit_str(), original);
751 EXPECT_EQ(a.size(), 0u);
752 EXPECT_EQ(a.get_bit_str(), "");
753 EXPECT_THROW(a.read_bit(0), std::out_of_range);
754
755 // the source is an empty array, which grows, is copied and is moved
756 a.push(1);
757 a.push(0);
758 a.push(1);
759 EXPECT_EQ(a.get_bit_str(), "101");
760 const BitArray c(a);
761 EXPECT_EQ(c.get_bit_str(), "101");
762 a.pop();
763 EXPECT_EQ(a.get_bit_str(), "10");
764 a.reserve(64); // which sets its size
765 EXPECT_EQ(a.size(), 64u);
766 EXPECT_EQ(a.read_bit(0), 1);
767 EXPECT_EQ(a.read_bit(63), 0);
768 EXPECT_EQ(b.get_bit_str(), original); // and what it gave is untouched
769
770 BitArray d(std::move(b));
771 BitArray e(std::move(b)); // from a source already moved from
772 EXPECT_EQ(d.get_bit_str(), original);
773 EXPECT_EQ(e.size(), 0u);
774 }
775}
776
777TEST(BitArrayCopyMove, swap)
778{
779 BitArray a;
780 a.set_bit_str("10110011");
781
782 BitArray b;
783 b.set_bit_str("0101");
784
785 const string a_str = a.get_bit_str();
786 const string b_str = b.get_bit_str();
787
788 a.swap(b);
789
790 EXPECT_EQ(a.get_bit_str(), b_str);
791 EXPECT_EQ(b.get_bit_str(), a_str);
792}
793
794TEST(BitArrayFunctions, bits_list)
795{
796 BitArray a;
797 a.set_bit_str("10110");
798
799 auto list = a.bits_list();
800 EXPECT_EQ(list.size(), 5u);
801
802 auto it = list.get_it();
803 EXPECT_EQ(it.get_curr(), 1); it.next();
804 EXPECT_EQ(it.get_curr(), 0); it.next();
805 EXPECT_EQ(it.get_curr(), 1); it.next();
806 EXPECT_EQ(it.get_curr(), 1); it.next();
807 EXPECT_EQ(it.get_curr(), 0);
808}
809
810TEST(BitArrayFunctions, fast_read_write)
811{
812 BitArray a;
813 a.reserve(16);
814
815 // fast_write doesn't expand, so we need to reserve first
816 a.fast_write(0, 1);
817 a.fast_write(7, 1);
818 a.fast_write(15, 1);
819
820 EXPECT_EQ(a.fast_read(0), 1);
821 EXPECT_EQ(a.fast_read(1), 0);
822 EXPECT_EQ(a.fast_read(7), 1);
823 EXPECT_EQ(a.fast_read(15), 1);
824}
825
826// The fast access asserts an index below size() in debug builds: a bit
827// written past size(), in a byte that exists, would come back when the size
828// grows
829#ifndef NDEBUG
830TEST(BitArrayFunctions, FastAccessAssertsAnIndexBelowTheSizeInDebugBuilds)
831{
832 BitArray a;
833 a.reserve(16);
834 a.set_size(8);
835 EXPECT_DEATH(a.fast_write(8, 1), "i < current_size");
836 EXPECT_DEATH((void) a.fast_read(8), "i < current_size");
837 a.set_size(16);
838 EXPECT_EQ(a.read(8), 0);
839}
840#endif
841
842TEST(BitArrayFunctions, save_in_array_of_chars)
843{
844 BitArray a;
845 a.set_bit_str("10110011");
846
847 ostringstream out;
848 a.save_in_array_of_chars("test_arr", out);
849 const string output = out.str();
850
851 EXPECT_NE(output.find("test_arr"), string::npos);
852 EXPECT_NE(output.find("8 bits"), string::npos);
853 EXPECT_NE(output.find("const unsigned char"), string::npos);
854}
855
856TEST(BitArrayFunctions, equality_operator)
857{
858 BitArray a;
859 a.set_bit_str("10110011");
860
861 BitArray b;
862 b.set_bit_str("10110011");
863
864 BitArray c;
865 c.set_bit_str("10110010");
866
867 BitArray d;
868 d.set_bit_str("1011001");
869
870 EXPECT_TRUE(a == b);
871 EXPECT_FALSE(a == c); // Different last bit
872 EXPECT_FALSE(a == d); // Different size
873}
874
875TEST(BitArrayIterator, prev_and_bidirectional)
876{
877 BitArray a;
878 a.set_bit_str("101");
879
880 auto it = a.get_it();
881 it.reset_last();
882 EXPECT_TRUE(it.has_curr());
883 EXPECT_EQ(it.get_curr(), 1u); // Last bit
884
885 it.prev();
886 EXPECT_EQ(it.get_curr(), 0u); // Middle bit
887
888 it.prev();
889 EXPECT_EQ(it.get_curr(), 1u); // First bit
890
891 // At position 0, prev moves to -1 (before first, like rend())
892 it.prev();
893 EXPECT_EQ(it.get_pos(), -1);
894 EXPECT_FALSE(it.has_curr());
895
896 // Now at position -1, prev should throw
897 EXPECT_THROW(it.prev(), std::underflow_error);
898}
899
900TEST(BitArrayIterator, end_and_get_pos)
901{
902 BitArray a;
903 a.set_bit_str("101");
904
905 auto it = a.get_it();
906 EXPECT_EQ(it.get_pos(), 0);
907
908 it.next();
909 EXPECT_EQ(it.get_pos(), 1);
910
911 it.end();
912 EXPECT_EQ(it.get_pos(), 3);
913 EXPECT_FALSE(it.has_curr());
914
915 it.reset();
916 EXPECT_EQ(it.get_pos(), 0);
917 EXPECT_TRUE(it.has_curr());
918}
919
920} // namespace
921
922// ---------------------------------------------------------------------------
923// reserve() and set_size() allocate every byte of the array, so that
924// fast_read(), fast_write(), read() and write() may follow them
925// ---------------------------------------------------------------------------
926
927namespace {
928
929// Sizes in bits around the limits of a byte and of the blocks of DynArray
930constexpr size_t Reserve_Sizes[] = {0, 1, 7, 8, 9, 63, 64, 65, 2047, 2048,
931 2049, 8191, 8192, 8193, 32768, 32769,
932 100000};
933
934constexpr unsigned pattern(const size_t i) noexcept { return i % 3 == 0; }
935
936// Every bit below size() is reached without checks: the first `kept` ones
937// hold pattern(), or 0, and the others are 0
938template <class Value>
939void check_fast_access(BitArray & b, const size_t kept, Value && value)
940{
941 for (size_t i = 0; i < b.size(); ++i)
942 {
943 const int expected = i < kept ? static_cast<int>(value(i)) : 0;
944 ASSERT_EQ(b.fast_read(i), expected) << "bit " << i;
945 ASSERT_EQ(b.read(i), expected) << "bit " << i;
946 }
947
948 for (size_t i = 0; i < b.size(); ++i)
949 b.fast_write(i, 1);
950 for (size_t i = 0; i < b.size(); ++i)
951 {
952 ASSERT_EQ(b.read_bit(i), 1) << "bit " << i;
953 b.write(i, 0);
954 }
955 for (size_t i = 0; i < b.size(); ++i)
956 ASSERT_EQ(b.fast_read(i), 0) << "bit " << i;
957}
958
959TEST(BitArrayReserve, FastAccessAfterReserveOnAFreshArray)
960{
961 for (const size_t n : Reserve_Sizes)
962 for (const size_t r : Reserve_Sizes)
963 {
964 SCOPED_TRACE(::testing::Message() << "n = " << n << ", r = " << r);
965 BitArray b(n);
966 b.reserve(r);
967 ASSERT_EQ(b.size(), r);
968 check_fast_access(b, 0, pattern);
969 if (::testing::Test::HasFatalFailure())
970 return;
971 }
972}
973
974TEST(BitArrayReserve, ReserveKeepsTheBitsOfAWrittenArray)
975{
976 for (const size_t n : Reserve_Sizes)
977 for (const size_t r : Reserve_Sizes)
978 {
979 SCOPED_TRACE(::testing::Message() << "n = " << n << ", r = " << r);
980 BitArray b;
981 for (size_t i = 0; i < n; ++i)
982 b.push(pattern(i));
983 b.reserve(r);
984 ASSERT_EQ(b.size(), r);
985 check_fast_access(b, std::min(n, r), pattern);
986 if (::testing::Test::HasFatalFailure())
987 return;
988 }
989}
990
991// The bits that leave the array do not come back when it grows again
992TEST(BitArrayReserve, BitsLeftOutByASmallerSizeDoNotComeBack)
993{
994 for (const size_t n : Reserve_Sizes)
995 for (const size_t r : Reserve_Sizes)
996 {
997 if (r >= n)
998 continue;
999 SCOPED_TRACE(::testing::Message() << "n = " << n << ", r = " << r);
1000 BitArray b(n, 1);
1001 b.reserve(r);
1002 b.reserve(n);
1003 ASSERT_EQ(b.size(), n);
1004 check_fast_access(b, r, [] (size_t) { return 1u; });
1005 if (::testing::Test::HasFatalFailure())
1006 return;
1007 }
1008}
1009
1010// Only the last bit is written, so the blocks before it do not exist
1011TEST(BitArrayReserve, FillsTheHolesOfASparseArray)
1012{
1013 for (const size_t n : Reserve_Sizes)
1014 {
1015 if (n == 0)
1016 continue;
1017 SCOPED_TRACE(::testing::Message() << "n = " << n);
1018 BitArray b(n);
1019 b.write_bit(n - 1, 1);
1020 b.reserve(n);
1021 check_fast_access(b, n, [n] (size_t i) { return i == n - 1; });
1022 if (::testing::Test::HasFatalFailure())
1023 return;
1024 }
1025}
1026
1027TEST(BitArrayReserve, FastAccessAfterReserveWhateverTheHistory)
1028{
1029 constexpr size_t n = 100000;
1030 const auto zero = [] (size_t) { return 0u; };
1031 const auto check = [&] (BitArray & b, const char * history)
1032 {
1033 SCOPED_TRACE(history);
1034 b.set_size(n);
1035 ASSERT_EQ(b.size(), n);
1036 check_fast_access(b, 0, zero);
1037 };
1038
1039 BitArray fresh(n);
1040 BitArray copied(fresh);
1041 check(copied, "copy of a fresh array");
1042
1043 BitArray assigned;
1044 assigned = fresh;
1045 check(assigned, "assigned from a fresh array");
1046
1047 BitArray source(n);
1048 BitArray moved(std::move(source));
1049 check(moved, "moved to");
1050 check(source, "moved from");
1051
1052 BitArray emptied(n, 1);
1053 emptied.empty();
1054 check(emptied, "emptied");
1055
1056 std::stringstream stream;
1057 BitArray().save(stream);
1058 BitArray loaded(n);
1059 loaded.load(stream);
1060 check(loaded, "loaded from an empty array");
1061}
1062
1063} // namespace
Space-efficient bit array implementation.
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
unsigned int get_curr_ne() const noexcept
Definition bitArray.H:1124
unsigned int get_curr() const
Definition bitArray.H:1129
void reset() noexcept
Definition bitArray.H:1177
bool has_curr() const noexcept
Definition bitArray.H:1118
long get_pos() const noexcept
Definition bitArray.H:1136
void end() noexcept
Definition bitArray.H:1165
void reset_last() noexcept
Definition bitArray.H:1157
Contiguous array of bits.
Definition bitArray.H:201
bool traverse(Operation &operation) const
Definition bitArray.H:1183
void fast_write(const size_t i, const unsigned int value)
Write bit i without checking i.
Definition bitArray.H:498
int read_bit(const size_t i) const
Read bit i.
Definition bitArray.H:409
std::string get_bit_str() const
Definition bitArray.H:981
void circular_left_shift(const size_t n=1)
Shifts the bits n positions to the left circularly.
Definition bitArray.H:863
void load_from_array_of_chars(const unsigned char str[], const size_t num_bits)
Reads an array of bits saved in a character array.
Definition bitArray.H:762
long get_num() const noexcept
Definition bitArray.H:961
void set_bit_str(const std::string &str)
Definition bitArray.H:966
int fast_read(const size_t i) const noexcept
Read bit i without any check.
Definition bitArray.H:482
void write(const size_t i, const unsigned int value)
Writes bit i with value without memory check.
Definition bitArray.H:462
auto get_it() const noexcept
Definition bitArray.H:1180
void left_shift(const size_t n=1)
Shifts the bits n positions to the left.
Definition bitArray.H:786
void circular_right_shift(const size_t n=1)
Shifts the bits n positions to the right circularly.
Definition bitArray.H:892
void pop()
Removes the last bit of the array.
Definition bitArray.H:512
void write_bit(const size_t i, const unsigned int value)
Write bit i with the value.
Definition bitArray.H:424
void reserve(const size_t dim)
Reserve memory in advance for the bit array dim dimension.
Definition bitArray.H:344
void dyn_left_shift(const size_t n=1)
Shifts bits n positions to the left dynamically.
Definition bitArray.H:822
void right_shift(const size_t n=1)
Shifts the bits n positions to the right.
Definition bitArray.H:804
void load(std::istream &input)
Loads an array of bits saved with save().
Definition bitArray.H:661
DynList< char > bits_list() const
Converts it to a list.
Definition bitArray.H:570
void empty() noexcept
Delete all inserted bits.
Definition bitArray.H:521
int count_ones() const noexcept
Definition bitArray.H:1212
void save_in_array_of_chars(const std::string &name, std::ostream &output) const
Saves a static string declaration to a text file.
Definition bitArray.H:718
int read(const size_t i) const
Quick read of bit i.
Definition bitArray.H:445
void set_num(T n)
Definition bitArray.H:915
void push(const unsigned int value)
Inserts the value at the end of the array.
Definition bitArray.H:506
constexpr size_t size() const noexcept
Returns the dimension of the bit array.
Definition bitArray.H:350
void swap(BitArray &array) noexcept
Definition bitArray.H:541
void dyn_right_shift(const size_t n=1)
Shifts bits n positions to the right dynamically.
Definition bitArray.H:835
void save(std::ostream &output) const
Saves the bit sequence in a text file.
Definition bitArray.H:612
int count_zeros() const noexcept
Definition bitArray.H:1217
unsigned long get_unum() const noexcept
Definition bitArray.H:949
void set_size(const size_t sz)
Resets the dimension of the array.
Definition bitArray.H:362
void write_bit(const unsigned int i, const unsigned int val) noexcept
Definition bitArray.H:126
int get_int() const noexcept
Definition bitArray.H:148
int count_ones() const noexcept
Definition bitArray.H:170
void set_int(int i) noexcept
Definition bitArray.H:153
unsigned int read_bit(const unsigned int i) const noexcept
Definition bitArray.H:120
int count_zeros() const noexcept
Definition bitArray.H:175
Minimal std::expected-style result type for C++20.
#define TEST(name)
static mt19937 rng
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
void shift(T &first, const Way< T > &way, T &x)
Move an item along its way.
Main namespace for Aleph-w library functions.
bool completed() const noexcept
Return true if all underlying iterators are finished.
Definition ah-zip.H:183
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
@ Value
Regular runtime payload stored as Interpreter_Value.
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
STL namespace.
bool check(GT &g)
Gsl_Compatible_Rng r
DynList< int > l
ofstream output
Definition writeHeap.C:215