/// A BooleanBitfield represents a set of booleans compactly stored as a vector of bits.
/// The BooleanBitfield is given a fixed size during construction. Reads outside of the current size return an out-of-bounds error. Writes outside of the current size expand the size of the set.
#[derive(Debug, Clone)]
pubstructBooleanBitfield(BitVec);
/// Error represents some reason a request against a bitfield was not satisfied
#[derive(Debug, PartialEq)]
pubenumError{
/// OutOfBounds refers to indexing into a bitfield where no bits exist; returns the illegal index and the current size of the bitfield, respectively
OutOfBounds(usize,usize),
}
implBooleanBitfield{
/// Create a new bitfield.
pubfnnew()-> Self{
Default::default()
}
pubfnwith_capacity(initial_len: usize)-> Self{
Self::from_elem(initial_len,false)
}
/// Create a new bitfield with the given length `initial_len` and all values set to `bit`.
/// Returns the index of the highest set bit. Some(n) if some bit is set, None otherwise.
pubfnhighest_set_bit(&self)-> Option<usize>{
self.0.iter().rposition(|bit|bit)
}
/// Returns the number of bits in this bitfield.
pubfnlen(&self)-> usize{
self.0.len()
}
/// Returns true if `self.len() == 0`
pubfnis_empty(&self)-> bool{
self.len()==0
}
/// Returns the number of bytes required to represent this bitfield.
pubfnnum_bytes(&self)-> usize{
self.to_bytes().len()
}
/// Returns the number of `1` bits in the bitfield
pubfnnum_set_bits(&self)-> usize{
self.0.iter().filter(|&bit|bit).count()
}
/// Returns a vector of bytes representing the bitfield
/// Note that this returns the bit layout of the underlying implementation in the `bit-vec` crate.
pubfnto_bytes(&self)-> Vec<u8>{
self.0.to_bytes()
}
}
impldefault::DefaultforBooleanBitfield{
/// default provides the "empty" bitfield
/// Note: the empty bitfield is set to the `0` byte.
fndefault()-> Self{
Self::from_elem(8,false)
}
}
implcmp::PartialEqforBooleanBitfield{
/// Determines equality by comparing the `ssz` encoding of the two candidates.
/// This method ensures that the presence of high-order (empty) bits in the highest byte do not exclude equality when they are in fact representing the same information.
fneq(&self,other: &Self)-> bool{
ssz::ssz_encode(self)==ssz::ssz_encode(other)
}
}
/// Create a new bitfield that is a union of two other bitfields.
///
/// For example `union(0101, 1000) == 1101`
implstd::ops::BitAndforBooleanBitfield{
typeOutput=Self;
fnbitand(self,other: Self)-> Self{
let(biggest,smallest)=ifself.len()>other.len(){
(&self,&other)
}else{
(&other,&self)
};
letmutnew=biggest.clone();
foriin0..smallest.len(){
ifletOk(true)=smallest.get(i){
new.set(i,true);
}
}
new
}
}
implssz::EncodableforBooleanBitfield{
// ssz_append encodes Self according to the `ssz` spec.