diff --git a/src/net/bitfield.rs b/src/net/bitfield.rs index f0c8623..bead130 100644 --- a/src/net/bitfield.rs +++ b/src/net/bitfield.rs @@ -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::() 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); +}