pub struct OneBitsIter(u64);
impl OneBitsIter {
pub const fn new(bits: u64) -> Self {
Self(bits)
}
}
impl Iterator for OneBitsIter {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
return None;
}
let mask = self.0 - 1;
let item = self.0 & !mask;
self.0 &= mask;
Some(item)
}
}
#[test]
fn empty() {
assert_eq!(OneBitsIter(0).next(), None);
}
#[test]
fn all() {
let mut obi = OneBitsIter(!0);
for bit in 0..64 {
assert_eq!(obi.next(), Some(1 << bit));
}
assert_eq!(obi.next(), None);
}
#[test]
fn first() {
let mut obi = OneBitsIter(1);
assert_eq!(obi.next(), Some(1));
assert_eq!(obi.next(), None);
}
#[test]
fn last() {
let mut obi = OneBitsIter(1 << 63);
assert_eq!(obi.next(), Some(1 << 63));
assert_eq!(obi.next(), None);
}
#[test]
fn in_order() {
let mut obi = OneBitsIter(0b11011000001);
assert_eq!(obi.next(), Some(1));
assert_eq!(obi.next(), Some(64));
assert_eq!(obi.next(), Some(128));
assert_eq!(obi.next(), Some(512));
assert_eq!(obi.next(), Some(1024));
assert_eq!(obi.next(), None);
}