async_std_utp/
bit_iterator.rs

1// How many bits in a `u8`
2const U8BITS: usize = 8;
3
4/// Lazy iterator over bits of a vector of bytes, starting with the LSB
5/// (least-significat bit) of the first element of the vector.
6pub struct BitIterator<'a> {
7    object: &'a [u8],
8    next_index: usize,
9    end_index: usize,
10}
11
12impl<'a> BitIterator<'a> {
13    /// Creates an iterator from a vector of bytes. Each byte becomes eight bits, with the least
14    /// significant bits coming first.
15    pub fn from_bytes(obj: &'a [u8]) -> BitIterator<'_> {
16        BitIterator {
17            object: obj,
18            next_index: 0,
19            end_index: obj.len() * U8BITS,
20        }
21    }
22
23    /// Returns the number of ones in the binary representation of the underlying object.
24    pub fn count_ones(&self) -> u32 {
25        self.object.iter().fold(0, |acc, bv| acc + bv.count_ones())
26    }
27}
28
29impl<'a> Iterator for BitIterator<'a> {
30    type Item = bool;
31
32    fn next(&mut self) -> Option<bool> {
33        if self.next_index != self.end_index {
34            let (byte_index, bit_index) = (self.next_index / U8BITS, self.next_index % U8BITS);
35            let bit = self.object[byte_index] >> bit_index & 0x1;
36            self.next_index += 1;
37            Some(bit == 0x1)
38        } else {
39            None
40        }
41    }
42
43    fn size_hint(&self) -> (usize, Option<usize>) {
44        (self.end_index, Some(self.end_index))
45    }
46}
47
48impl<'a> ExactSizeIterator for BitIterator<'a> {}
49
50#[test]
51fn test_iterator() {
52    let bytes = vec![0xCA, 0xFE];
53    let expected_bits = vec![0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1];
54
55    for (i, bit) in BitIterator::from_bytes(&bytes).enumerate() {
56        println!("{} == {}", bit, expected_bits[i] == 1);
57        assert_eq!(bit, expected_bits[i] == 1);
58    }
59}