std / Bit_Array
Available on macOS, Linux, Windows, Wasm
#import "Bit_Array";
A fixed-length sequence of bits packed into words.
seen := make_bit_array (100 );
defer deinit (*seen);
seen[42 ] = true ;
assert (seen[42 ] && !seen[43 ]);
Procedures#
Sets up array to hold count bits, all cleared, replacing whatever it was. Allocates the words with the array's allocator, taking context.allocator if it has none.
bits: Bit_Array;
init_bit_array (*bits, 16 );
assert (bits.count == 16 && !bits[3 ]);
deinit (*bits);Reset Copy ↗ Run ▸
A new Bit_Array of count cleared bits. The caller owns the storage and releases it with deinit.
Frees the words and leaves the array empty (count is zero). It can be set up again with init_bit_array.
Sets bit i; bits[i] reads it back.
Clears bit i. An index outside 0..count-1 fails an assert.
Flips bit i. An index outside 0..count-1 fails an assert.
Sets bit i when value is true and clears it otherwise; this is what bits[i] = value does.
Clears every bit, including the padding bits of the last word.
Sets every bit, including the padding bits of the last word, so slots holds all ones.
Flips every bit, including the padding bits of the last word.
(array: *
Bit_Array , body:
Code , flags: For_Flags)
Lets a Bit_Array be used in a for loop over all its bits, in order: it is the bit and it_index its position.
bits := make_bit_array (4 );
bits[2 ] = true ;
for bits if it assert (it_index == 2 );
deinit (*bits);Reset Copy ↗ Run ▸
A loop body for visiting just the set bits, used as for: only_set bits; it is true and it_index the position.
bits := make_bit_array (8 );
bits[1 ] = true ;
bits[6 ] = true ;
positions: [..] int ;
for : only_set bits array_add(*positions, it_index);
assert (positions.count == 2 && positions[1 ] == 6 );
array_free(positions);
deinit (*bits);Reset Copy ↗ Run ▸
Like only_set, but visits the cleared bits.
bits := make_bit_array (4 );
bits[0 ] = true ;
cleared := 0 ;
for : only_unset bits cleared += 1 ;
assert (cleared == 3 );
deinit (*bits);Reset Copy ↗ Run ▸
Types#
:: struct
A fixed-length sequence of bits packed into 64-bit words; count is the number of bits.
slots : [] s64
count : int
allocator : Allocator
bits := make_bit_array (10 );
set_bit (*bits, 2 );
bits[5 ] = true ;
toggle_bit (*bits, 2 );
assert (!bits[2 ] && bits[5 ]);
set := 0 ;
for bits if it set += 1 ; // `it` is the bit, `it_index` its position
assert (set == 1 );
deinit (*bits);Reset Copy ↗ Run ▸