binvec
binvec provides a fixed-size, stack-allocated bit vector implemented with const generics.
It packs boolean values densely into bytes so you can store large sets of flags without
the overhead of bool slices or heap allocations.
Highlights
- Packs
Lboolean values into(L + 7) / 8bytes with zero heap usage. - Const-generic type
Binvec<L, N>gives compile-time guarantees about bit length. - Ergonomic
binvec!macro computes the minimal byte length for you. - Constant-time indexing with
get/setand checked or unchecked access variants. - Methods for bulk operations such as
fill,count_ones,count_zeros, and predicates for all-one/zero checks. - Iterator support via
BinvecIterfor integration with the iterator ecosystem.
Installation
Add the crate to your Cargo.toml:
[]
= "0.1"
ℹ️ The crate currently uses only
coreAPIs internally, but it is exported as a normalstdcrate. No additional features or dependencies are required.
Quick Start
use *;
// Create a 12-bit binvec filled with zeros
let mut flags = binvec!;
// Flip a couple of bits
flags.set.unwrap;
flags.set.unwrap;
assert_eq!;
assert_eq!;
assert!;
The binvec! macro is the recommended constructor. It expands to a const instantiation
of Binvec<L, N> where N is (L + 7) >> 3, ensuring the backing byte array is the
minimal size required to hold the requested bit length.
API Overview
Binvec::<L, N>: main container type. Use the macro unless you need to specify both const parameters manually.get/set: checked accessors that returnOption<bool>orResult<(), IndexOutOfBounds>.get_unchecked/set_unchecked: unchecked versions for hot paths where you can guarantee the index is in range (calling these with an out-of-bounds index is UB).fill,count_ones,count_zeros,is_all_one,is_all_zero: helpers for bulk inspection.iter: yieldsboolvalues and integrates withforloops and iterator adapters.BinvecIter: explicit iterator type if you need to hold the iterator value.
The crate also exposes the error::IndexOutOfBounds error type so you can handle
checked writes ergonomically:
use *;
let mut bits = binvec!;
match bits.set
Safety & Performance Notes
- Checked access methods (
get,set) are safe and return an error instead of panicking. - Unchecked methods are
unsafebecause they can read or write past the backing array if misused; prefer the checked versions unless profiling shows you need the extra speed. - All public const functions can be evaluated at compile time, making it easy to work
with
Binvecinconstcontexts or static initialisers.