38#include <gtest/gtest.h>
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
52#ifdef BITARRAY_TEST_READS_ALLOCATED_BYTES
55extern "C" size_t __sanitizer_get_current_allocated_bytes();
78SavedBitArray save_and_parse(
const BitArray &arr)
83 istringstream in(
out.str());
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)
91 parsed.bytes.push_back(
value);
96string bits_to_string(
const vector<unsigned int> &
bits)
100 for (
auto bit :
bits)
101 out.push_back(bit ?
'1' :
'0');
106string to_bit_string(U
value,
const size_t num_bits)
109 out.reserve(num_bits);
110 for (
size_t i = 0; i < num_bits; ++i)
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');
120string expected_set_num_bits(
const T value)
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);
127vector<unsigned int> random_bits(mt19937 &
rng,
const size_t n)
129 bernoulli_distribution dist(0.5);
130 vector<unsigned int>
bits;
132 for (
size_t i = 0; i < n; ++i)
133 bits.push_back(dist(
rng) ? 1u : 0u);
140 for (
size_t i = 0; i <
bits.size(); ++i)
146vector<unsigned int> or_bits(
const vector<unsigned int> &a,
147 const vector<unsigned int> &b)
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)
153 const unsigned int lhs = i < a.size() ? a[i] : 0u;
154 const unsigned int rhs = i < b.size() ? b[i] : 0u;
160vector<unsigned int> and_bits(
const vector<unsigned int> &a,
161 const vector<unsigned int> &b)
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];
170TEST(BitArrayBasics, construction_size_and_defaults)
173 EXPECT_EQ(empty.
size(), 0u);
174 EXPECT_THROW((
void) empty.
read_bit(0), std::out_of_range);
177 EXPECT_EQ(a.size(), 10u);
178 for (
size_t i = 0; i < a.size(); ++i)
179 EXPECT_EQ(a.read_bit(i), 0);
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'));
188TEST(ByteBasics, read_write_and_int_roundtrip)
190 static_assert(
sizeof(
Byte) == 1);
199 EXPECT_EQ(b.
get_int(), 0b00000101);
214TEST(BitArrayProxy, writes_extend_size_and_copy_from_sparse_proxy)
218 EXPECT_EQ(a.
size(), 1u);
222 EXPECT_EQ(a.
size(), 11u);
229 EXPECT_NO_THROW(b[0] = sparse[0]);
230 EXPECT_EQ(b.
size(), 1u);
234 EXPECT_THROW((
void) c[1], std::out_of_range);
237TEST(BitArraySizing, set_size_computes_byte_count_correctly)
243 const auto saved = save_and_parse(a);
244 EXPECT_EQ(saved.num_bytes, 1u);
245 EXPECT_EQ(saved.num_bits, 1u);
250 const auto saved = save_and_parse(a);
251 EXPECT_EQ(saved.num_bytes, 2u);
252 EXPECT_EQ(saved.num_bits, 16u);
257 const auto saved = save_and_parse(a);
258 EXPECT_EQ(saved.num_bytes, 3u);
259 EXPECT_EQ(saved.num_bits, 17u);
268TEST(BitArraySizing, set_size_refuses_a_size_that_it_cannot_hold)
270 constexpr size_t max = numeric_limits<size_t>::max();
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})
278 EXPECT_THROW(a.
set_size(sz), length_error);
279 EXPECT_THROW(a.
reserve(sz), length_error);
280 ASSERT_EQ(a.
size(), 3u);
284 EXPECT_EQ(a.
size(), 10u);
292TEST(BitArraySizing, bits_that_come_back_after_shrinking_are_zero)
294 for (
const size_t down : {0u, 1u, 7u, 8u, 9u, 15u})
301 EXPECT_EQ(a.
get_bit_str(),
string(down,
'1') +
string(16 - down,
'0'));
305TEST(BitArrayAccess, reserve_enables_fast_read_write)
309 EXPECT_EQ(a.
size(), 9u);
312 EXPECT_EQ(a.
read(8), 1);
316TEST(BitArrayAccess, reading_unallocated_bytes_returns_zero)
320 EXPECT_EQ(a.
size(), 40'001u);
327TEST(BitArrayStackOps, push_pop_and_empty)
330 EXPECT_THROW(a.
pop(), std::underflow_error);
335 EXPECT_EQ(a.
size(), 3u);
339 EXPECT_EQ(a.
size(), 2u);
341 EXPECT_THROW((
void) a.
read_bit(2), std::out_of_range);
344 EXPECT_EQ(a.
size(), 0u);
347TEST(BitArrayPersistence, save_load_roundtrip)
356 istringstream in(
out.str());
368TEST(BitArrayPersistence, load_rejects_a_header_whose_bits_wrap)
370 const size_t max = numeric_limits<size_t>::max();
376 EXPECT_THROW(a.
load(in), std::runtime_error) <<
bits;
386TEST(BitArrayPersistence, load_rejects_a_header_with_too_many_bytes)
395 ADD_FAILURE() <<
"load() accepted the header";
397 catch (
const std::runtime_error & e)
399 EXPECT_NE(
string(e.what()).find(
"too many bytes"), string::npos)
407TEST(BitArrayPersistence, load_of_a_truncated_payload_throws)
411 istringstream in(
"3 17\n1 2\n");
412 EXPECT_THROW(a.
load(in), std::runtime_error);
416TEST(BitArrayPersistence, load_from_array_of_chars_roundtrip)
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));
432TEST(BitArrayShifts, fixed_and_dynamic_shifts)
453 EXPECT_EQ(too_much.
size(), 1u);
457TEST(BitArrayShifts, circular_shifts)
475TEST(BitArrayBitwiseOps, or_and_with_different_sizes)
490TEST(BitArrayBitwiseOps, or_does_not_leak_rhs_unused_bits_after_shrink)
494 for (
size_t i = 9; i < 16; ++i)
502 for (
size_t i = 9; i < 16; ++i)
506TEST(BitArrayBitwiseOps, or_masks_rhs_unused_bits_from_load)
509 const unsigned char bytes[] = {0x00, 0xFF};
518 for (
size_t i = 9; i < 16; ++i)
522TEST(BitArraySizing, shrink_then_write_bit_growth_keeps_new_bits_zeroed)
527 for (
size_t i = 9; i < 16; ++i)
535 EXPECT_EQ(a.
size(), 16u);
537 for (
size_t i = 9; i < 15; ++i)
541TEST(BitArrayFunctional, iterator_and_traverse)
547 ASSERT_TRUE(it.has_curr());
548 EXPECT_EQ(it.get_curr(), 1u);
550 EXPECT_EQ(it.get_curr(), 0u);
552 EXPECT_EQ(it.get_curr(), 1u);
554 EXPECT_FALSE(it.has_curr());
555 EXPECT_EQ(it.get_curr_ne(), 0u);
560 bool operator()(
int bit)
572 EXPECT_EQ(op.visited, 4);
575TEST(BitArrayIterator, unbound_iterator_corner_cases)
580 EXPECT_THROW((
void) it.
get_curr(), std::overflow_error);
581 EXPECT_NO_THROW(it.
end());
582 EXPECT_THROW(it.
next(), std::overflow_error);
583 EXPECT_THROW(it.
prev(), std::underflow_error);
586TEST(BitArrayIterator, empty_array_iterator_corner_cases)
592 EXPECT_THROW((
void) it.
get_curr(), std::overflow_error);
593 EXPECT_THROW(it.
next(), std::overflow_error);
597 EXPECT_THROW(it.
prev(), std::underflow_error);
598 EXPECT_NO_THROW(it.
end());
601TEST(BitArrayNumbers, set_num_bit_strings_and_numeric_roundtrip)
606 EXPECT_EQ(a.
size(), 8u);
607 EXPECT_EQ(a.
get_bit_str(), expected_set_num_bits<std::uint8_t>(0));
612 EXPECT_EQ(a.
get_bit_str(), expected_set_num_bits<std::uint8_t>(0xA5));
617 EXPECT_EQ(a.
get_bit_str(), expected_set_num_bits<std::int8_t>(-1));
622 EXPECT_EQ(a.
get_bit_str(), expected_set_num_bits<std::int8_t>(-2));
627 EXPECT_EQ(a.
size(), 16u);
628 EXPECT_EQ(a.
get_bit_str(), expected_set_num_bits<std::int16_t>(-2));
630 EXPECT_EQ(a.
get_num(), 65534l);
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());
638TEST(BitArrayNumbers, get_unum_ignores_bits_beyond_unsigned_long_width)
640 constexpr size_t ul_bits =
sizeof(
unsigned long) * 8;
641 constexpr size_t extra = 5;
649TEST(BitArrayRandomized, matches_reference_or_and_counts)
653 for (
int iter = 0; iter < 50; ++iter)
655 const size_t n1 =
rng() % 200;
656 const size_t n2 =
rng() % 200;
658 const auto bits1 = random_bits(
rng, n1);
659 const auto bits2 = random_bits(
rng, n2);
661 const BitArray a = from_bits(bits1);
662 const BitArray b = from_bits(bits2);
664 const auto expected_or = or_bits(bits1, bits2);
665 const auto expected_and = and_bits(bits1, bits2);
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));
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);
682TEST(BitArrayCopyMove, copy_constructor_and_assignment)
708TEST(BitArrayCopyMove, move_constructor_and_assignment)
717 EXPECT_EQ(a.
size(), 0u);
724 EXPECT_EQ(b.
size(), 0u);
731TEST(BitArrayCopyMove, move_constructor_leaves_a_source_that_takes_bits_again)
733 static_assert(std::is_nothrow_move_constructible_v<BitArray>);
735 for (
const size_t n : {0u, 1u, 8u, 9u, 100u, 40000u})
738 for (
size_t i = 0; i < n; ++i)
742#ifdef BITARRAY_TEST_READS_ALLOCATED_BYTES
743 const size_t allocated = __sanitizer_get_current_allocated_bytes();
746#ifdef BITARRAY_TEST_READS_ALLOCATED_BYTES
747 EXPECT_EQ(__sanitizer_get_current_allocated_bytes(), allocated) <<
"the move allocated";
749 EXPECT_EQ(b.
size(), n);
751 EXPECT_EQ(a.
size(), 0u);
753 EXPECT_THROW(a.
read_bit(0), std::out_of_range);
765 EXPECT_EQ(a.
size(), 64u);
772 EXPECT_EQ(d.get_bit_str(), original);
773 EXPECT_EQ(e.size(), 0u);
794TEST(BitArrayFunctions, bits_list)
800 EXPECT_EQ(list.size(), 5u);
802 auto it = list.get_it();
810TEST(BitArrayFunctions, fast_read_write)
830TEST(BitArrayFunctions, FastAccessAssertsAnIndexBelowTheSizeInDebugBuilds)
835 EXPECT_DEATH(a.
fast_write(8, 1),
"i < current_size");
836 EXPECT_DEATH((
void) a.
fast_read(8),
"i < current_size");
838 EXPECT_EQ(a.
read(8), 0);
842TEST(BitArrayFunctions, save_in_array_of_chars)
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);
856TEST(BitArrayFunctions, equality_operator)
871 EXPECT_FALSE(a == c);
872 EXPECT_FALSE(a == d);
875TEST(BitArrayIterator, prev_and_bidirectional)
897 EXPECT_THROW(it.
prev(), std::underflow_error);
900TEST(BitArrayIterator, end_and_get_pos)
930constexpr size_t Reserve_Sizes[] = {0, 1, 7, 8, 9, 63, 64, 65, 2047, 2048,
931 2049, 8191, 8192, 8193, 32768, 32769,
934constexpr unsigned pattern(
const size_t i)
noexcept {
return i % 3 == 0; }
938template <
class Value>
941 for (
size_t i = 0; i < b.
size(); ++i)
943 const int expected = i < kept ? static_cast<int>(
value(i)) : 0;
948 for (
size_t i = 0; i < b.
size(); ++i)
950 for (
size_t i = 0; i < b.
size(); ++i)
952 ASSERT_EQ(b.
read_bit(i), 1) <<
"bit " << i;
955 for (
size_t i = 0; i < b.
size(); ++i)
956 ASSERT_EQ(b.
fast_read(i), 0) <<
"bit " << i;
959TEST(BitArrayReserve, FastAccessAfterReserveOnAFreshArray)
961 for (
const size_t n : Reserve_Sizes)
962 for (const size_t
r : Reserve_Sizes)
964 SCOPED_TRACE(::testing::Message() <<
"n = " << n <<
", r = " <<
r);
967 ASSERT_EQ(b.
size(),
r);
968 check_fast_access(b, 0, pattern);
969 if (::testing::Test::HasFatalFailure())
974TEST(BitArrayReserve, ReserveKeepsTheBitsOfAWrittenArray)
976 for (
const size_t n : Reserve_Sizes)
977 for (const size_t
r : Reserve_Sizes)
979 SCOPED_TRACE(::testing::Message() <<
"n = " << n <<
", r = " <<
r);
981 for (
size_t i = 0; i < n; ++i)
984 ASSERT_EQ(b.
size(),
r);
985 check_fast_access(b, std::min(n,
r), pattern);
986 if (::testing::Test::HasFatalFailure())
992TEST(BitArrayReserve, BitsLeftOutByASmallerSizeDoNotComeBack)
994 for (
const size_t n : Reserve_Sizes)
995 for (const size_t
r : Reserve_Sizes)
999 SCOPED_TRACE(::testing::Message() <<
"n = " << n <<
", r = " <<
r);
1003 ASSERT_EQ(b.
size(), n);
1004 check_fast_access(b,
r, [] (
size_t) {
return 1u; });
1005 if (::testing::Test::HasFatalFailure())
1011TEST(BitArrayReserve, FillsTheHolesOfASparseArray)
1013 for (
const size_t n : Reserve_Sizes)
1017 SCOPED_TRACE(::testing::Message() <<
"n = " << n);
1021 check_fast_access(b, n, [n] (
size_t i) {
return i == n - 1; });
1022 if (::testing::Test::HasFatalFailure())
1027TEST(BitArrayReserve, FastAccessAfterReserveWhateverTheHistory)
1029 constexpr size_t n = 100000;
1030 const auto zero = [] (size_t) {
return 0u; };
1033 SCOPED_TRACE(history);
1035 ASSERT_EQ(b.
size(), n);
1036 check_fast_access(b, 0, zero);
1041 check(copied,
"copy of a fresh array");
1045 check(assigned,
"assigned from a fresh array");
1049 check(moved,
"moved to");
1050 check(source,
"moved from");
1054 check(emptied,
"emptied");
1056 std::stringstream stream;
1059 loaded.load(stream);
1060 check(loaded,
"loaded from an empty array");
Space-efficient bit array implementation.
size_t size_t int32_t value
size_t size_t int32_t * out
unsigned int get_curr_ne() const noexcept
unsigned int get_curr() const
bool has_curr() const noexcept
long get_pos() const noexcept
void reset_last() noexcept
Contiguous array of bits.
bool traverse(Operation &operation) const
void fast_write(const size_t i, const unsigned int value)
Write bit i without checking i.
int read_bit(const size_t i) const
Read bit i.
std::string get_bit_str() const
void circular_left_shift(const size_t n=1)
Shifts the bits n positions to the left circularly.
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.
long get_num() const noexcept
void set_bit_str(const std::string &str)
int fast_read(const size_t i) const noexcept
Read bit i without any check.
void write(const size_t i, const unsigned int value)
Writes bit i with value without memory check.
auto get_it() const noexcept
void left_shift(const size_t n=1)
Shifts the bits n positions to the left.
void circular_right_shift(const size_t n=1)
Shifts the bits n positions to the right circularly.
void pop()
Removes the last bit of the array.
void write_bit(const size_t i, const unsigned int value)
Write bit i with the value.
void reserve(const size_t dim)
Reserve memory in advance for the bit array dim dimension.
void dyn_left_shift(const size_t n=1)
Shifts bits n positions to the left dynamically.
void right_shift(const size_t n=1)
Shifts the bits n positions to the right.
void load(std::istream &input)
Loads an array of bits saved with save().
DynList< char > bits_list() const
Converts it to a list.
void empty() noexcept
Delete all inserted bits.
int count_ones() const noexcept
void save_in_array_of_chars(const std::string &name, std::ostream &output) const
Saves a static string declaration to a text file.
int read(const size_t i) const
Quick read of bit i.
void push(const unsigned int value)
Inserts the value at the end of the array.
constexpr size_t size() const noexcept
Returns the dimension of the bit array.
void swap(BitArray &array) noexcept
void dyn_right_shift(const size_t n=1)
Shifts bits n positions to the right dynamically.
void save(std::ostream &output) const
Saves the bit sequence in a text file.
int count_zeros() const noexcept
unsigned long get_unum() const noexcept
void set_size(const size_t sz)
Resets the dimension of the array.
void write_bit(const unsigned int i, const unsigned int val) noexcept
int get_int() const noexcept
int count_ones() const noexcept
void set_int(int i) noexcept
unsigned int read_bit(const unsigned int i) const noexcept
int count_zeros() const noexcept
Minimal std::expected-style result type for C++20.
__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)
__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)
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.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
@ 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
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.