Modules

Bit_Array

moduleSource
macOSLinuxWindowswasm

#import "Bit_Array";

A fixed-length sequence of bits packed into words.

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.

(count: int) -> Bit_Array

A new Bit_Array of count cleared bits. The caller owns the storage and releases it with deinit.

bits := make_bit_array(200);
assert(bits.count == 200 && !bits[199]);
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.

(array: *Bit_Array, i: int)

Flips bit i. An index outside 0..count-1 fails an assert.

(array: *Bit_Array, i: int, value: bool)

Sets bit i when value is true and clears it otherwise; this is what bits[i] = value does.

(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.

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.

Types#

Bit_Arraystruct
:: struct

A fixed-length sequence of bits packed into 64-bit words; count is the number of bits.

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