bitfield: add set ratio

This commit is contained in:
2016-12-14 16:59:21 -05:00
parent 18d64ecebd
commit d336c00079

View File

@@ -49,6 +49,10 @@ impl BitField {
pub fn as_bytes(&self) -> &[u8] {
&self.bits
}
pub fn set_ratio(&self) -> f64 {
self.bits.iter().map(|b| b.count_ones()).sum::<u32>() as f64 / self.len as f64
}
}
impl fmt::Debug for BitField {
@@ -107,3 +111,10 @@ fn test_bitfield_unset() {
bf.unset(15);
assert_eq!(bf.bits[1], 255-128-1);
}
#[test]
fn test_bitfield_set_ratio() {
use std::f64;
let mut bf = BitField::new(vec![255, 255], 16);
assert!(f64::abs(bf.set_ratio() - 1.0) < f64::EPSILON);
}