Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resize BitList #24

Merged
merged 3 commits into from
Jul 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/bitfield.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,24 @@ impl<N: Unsigned + Clone> Bitfield<Variable<N>> {
pub fn is_subset(&self, other: &Self) -> bool {
self.difference(other).is_zero()
}

/// Returns a new BitList of length M, with the same bits set as `self`.
pub fn resize<M: Unsigned + Clone>(&self) -> Result<Bitfield<Variable<M>>, Error> {
if N::to_usize() > M::to_usize() {
return Err(Error::InvalidByteCount {
given: M::to_usize(),
expected: N::to_usize() + 1,
});
}

let mut resized = Bitfield::<Variable<M>>::with_capacity(M::to_usize())?;

for (i, bit) in self.iter().enumerate() {
resized.set(i, bit)?;
}

Ok(resized)
}
}

impl<N: Unsigned + Clone> Bitfield<Fixed<N>> {
Expand Down Expand Up @@ -1403,4 +1421,21 @@ mod bitlist {
fn size_of() {
assert_eq!(std::mem::size_of::<BitList1024>(), SMALLVEC_LEN + 24);
}

#[test]
fn resize() {
let mut bit_list = BitList1::with_capacity(1).unwrap();
bit_list.set(0, true).unwrap();
assert_eq!(bit_list.len(), 1);
assert_eq!(bit_list.num_set_bits(), 1);
assert_eq!(bit_list.highest_set_bit().unwrap(), 0);

let resized_bit_list = bit_list.resize::<typenum::U1024>().unwrap();
assert_eq!(resized_bit_list.len(), 1024);
assert_eq!(resized_bit_list.num_set_bits(), 1);
assert_eq!(resized_bit_list.highest_set_bit().unwrap(), 0);

// Can't extend a BitList to a smaller BitList
resized_bit_list.resize::<typenum::U16>().unwrap_err();
}
}
Loading