Modules

Bit_Array

moduleSource

Available on macOS, Linux, Windows, Wasm

#import "Bit_Array";

A fixed-length sequence of bits packed into words.

Example↗
seen := make_bit_array(100);
defer deinit(*seen);
seen[42] = true;
assert(seen[42] && !seen[43]);

Procedures#

(array: *Bit_Array, count: int)

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);
↗
(array: *Bit_Array)

Frees the words and leaves the array empty (count is zero). It can be set up again with init_bit_array.

bits := make_bit_array(8);
deinit(*bits);
assert(bits.count == 0);
↗
(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);
↗

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);
↗

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);
↗

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);
↗