| Crates.io | binvec |
| lib.rs | binvec |
| version | 0.1.1 |
| created_at | 2025-09-08 09:05:08.66452+00 |
| updated_at | 2025-10-24 05:43:28.766326+00 |
| description | It is a binary vector type developed in Rust to use memory efficiently. It is characterized by using the minimum memory space to store an array of bool values. |
| homepage | |
| repository | |
| max_upload_size | |
| id | 1829025 |
| size | 20,285 |
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.
L boolean values into (L + 7) / 8 bytes with zero heap usage.Binvec<L, N> gives compile-time guarantees about bit length.binvec! macro computes the minimal byte length for you.get/set and checked or unchecked access variants.fill, count_ones, count_zeros, and predicates for all-one/zero checks.BinvecIter for integration with the iterator ecosystem.Add the crate to your Cargo.toml:
[dependencies]
binvec = "0.1"
ℹ️ The crate currently uses only
coreAPIs internally, but it is exported as a normalstdcrate. No additional features or dependencies are required.
use binvec::*;
// Create a 12-bit binvec filled with zeros
let mut flags = binvec!(12, false);
// Flip a couple of bits
flags.set(3, true).unwrap();
flags.set(7, true).unwrap();
assert_eq!(flags.get(3), Some(true));
assert_eq!(flags.count_ones(), 2);
assert!(!flags.is_all_zero());
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.
Binvec::<L, N>: main container type. Use the macro unless you need to specify both
const parameters manually.get / set: checked accessors that return Option<bool> or Result<(), 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: yields bool values and integrates with for loops 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 binvec::*;
let mut bits = binvec!(8, false);
match bits.set(32, true) {
Ok(()) => { /* success */ }
Err(e) => eprintln!("write failed: {e}"),
}
get, set) are safe and return an error instead of panicking.unsafe because they can read or write past the backing array
if misused; prefer the checked versions unless profiling shows you need the extra speed.Binvec in const contexts or static initialisers.