Add method to calculate the underlying number of bytes

Required for part of attestation validation logic
This commit is contained in:
Alex Stokes 2018-11-20 10:12:49 -08:00
parent 72cf7ad1bd
commit 031b7bf225
2 changed files with 23 additions and 1 deletions

View File

@ -75,6 +75,11 @@ impl BooleanBitfield {
self.0.len() self.0.len()
} }
/// Returns the number of bytes required to represent this bitfield.
pub fn num_bytes(&self) -> usize {
self.to_bytes().len()
}
/// Returns the number of `1` bits in the bitfield /// Returns the number of `1` bits in the bitfield
pub fn num_set_bits(&self) -> usize { pub fn num_set_bits(&self) -> usize {
self.0.iter().filter(|&bit| bit).count() self.0.iter().filter(|&bit| bit).count()
@ -203,6 +208,7 @@ mod tests {
let out_of_bounds_index = field.len(); let out_of_bounds_index = field.len();
assert!(field.set(out_of_bounds_index, true).is_none()); assert!(field.set(out_of_bounds_index, true).is_none());
assert!(field.len() == out_of_bounds_index + 1);
assert!(field.get(out_of_bounds_index).unwrap()); assert!(field.get(out_of_bounds_index).unwrap());
for i in 0..100 { for i in 0..100 {
@ -213,4 +219,16 @@ mod tests {
} }
} }
} }
#[test]
fn test_num_bytes() {
let field = BooleanBitfield::from_bytes(INPUT);
assert_eq!(field.num_bytes(), 2);
let field = BooleanBitfield::from_elem(2, true);
assert_eq!(field.num_bytes(), 1);
let field = BooleanBitfield::from_elem(13, true);
assert_eq!(field.num_bytes(), 2);
}
} }

View File

@ -199,6 +199,10 @@ where
} }
} }
fn bytes_for_bits(bits: usize) -> usize {
(bits.saturating_sub(1) / 8) + 1
}
impl From<ParentHashesError> for AttestationValidationError { impl From<ParentHashesError> for AttestationValidationError {
fn from(e: ParentHashesError) -> Self { fn from(e: ParentHashesError) -> Self {
match e { match e {
@ -243,4 +247,4 @@ impl From<SignatureVerificationError> for AttestationValidationError {
=> AttestationValidationError::OutOfBoundsBitfieldIndex, => AttestationValidationError::OutOfBoundsBitfieldIndex,
} }
} }
} }