From 3067c3585d36f0b7c87ac21edb047b340e31f219 Mon Sep 17 00:00:00 2001 From: Jan-Paul Bultmann <74891396+somethingelseentirely@users.noreply.github.com> Date: Wed, 23 Jul 2025 18:05:50 +0200 Subject: [PATCH] Add from_bit constructor to BitVectorBuilder --- CHANGELOG.md | 1 + src/bit_vector/mod.rs | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 54111dc..101dd5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - Replaced the old `BitVector` with the generic `BitVector` and renamed the mutable variant to `RawBitVector`. - Extended `BitVectorBuilder` with `push_bits` and `set_bit` APIs. +- Added `from_bit` constructor on `BitVectorBuilder` for repeating a single bit. - `DacsByte` now stores level data as zero-copy `View<[u8]>` values. - Added `get_bits` methods to `BitVectorData` and `BitVector`. - Added `scripts/devtest.sh` and `scripts/preflight.sh` for testing and diff --git a/src/bit_vector/mod.rs b/src/bit_vector/mod.rs index 82b3278..b105b71 100644 --- a/src/bit_vector/mod.rs +++ b/src/bit_vector/mod.rs @@ -138,6 +138,22 @@ impl BitVectorBuilder { Self::default() } + /// Creates a builder that stores `len` copies of `bit`. + pub fn from_bit(bit: bool, len: usize) -> Self { + if len == 0 { + return Self::default(); + } + let word = if bit { usize::MAX } else { 0 }; + let num_words = (len + WORD_LEN - 1) / WORD_LEN; + let mut words = vec![word; num_words]; + let shift = len % WORD_LEN; + if shift != 0 { + let mask = (1 << shift) - 1; + *words.last_mut().unwrap() &= mask; + } + Self { words, len } + } + /// Pushes a single bit. pub fn push_bit(&mut self, bit: bool) { let pos_in_word = self.len % WORD_LEN; @@ -590,6 +606,14 @@ mod tests { assert_eq!(bv.data.get_bits(61, 7).unwrap(), 0b0111110); } + #[test] + fn builder_from_bit() { + let builder = BitVectorBuilder::from_bit(true, 5); + let bv: BitVector = builder.freeze::(); + assert_eq!(bv.len(), 5); + assert_eq!(bv.num_ones(), 5); + } + #[test] fn iter_collects() { let data = BitVectorData::from_bits([true, false, true]);