1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
pub(crate) struct BitIter {
value: u64,
mask: u64,
}
impl BitIter {
pub(crate) const fn new(value: u64) -> Self {
BitIter {
value,
mask: 0x8000_0000_0000_0000,
}
}
}
impl Iterator for BitIter {
type Item = bool;
fn next(&mut self) -> Option<bool> {
let mask = self.mask;
if mask != 0 {
self.mask >>= 1;
Some(self.value & mask != 0)
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn zero() {
for b in BitIter::new(0) {
assert!(!b);
}
}
#[test]
pub fn max() {
for b in BitIter::new(u64::max_value()) {
assert!(b);
}
}
#[test]
pub fn alternating() {
let mut expected = true;
for b in BitIter::new(0xaaaa_aaaa_aaaa_aaaa) {
assert_eq!(expected, b);
expected = !expected;
}
}
}