Skip to content

Commit

Permalink
Add BitList::resize
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelsproul committed Sep 3, 2024
1 parent c8a1294 commit 91b5130
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions ssz/src/bitfield.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,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 @@ -1394,4 +1412,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();
}
}

0 comments on commit 91b5130

Please sign in to comment.