sparse_bitfield/iter.rs
1use super::Bitfield;
2use std::iter;
3
4/// Iterate over a `Bitfield` instance.
5// TODO: the most efficient way to iterate this is to get a page at the time &
6// cache it. Then get a bit at the time & cache it. That should allow us to
7// return values much faster, rather than doing a heap lookup for every bit.
8//
9// The CPU's (L3) cache might kick in here to store a page at the time, but
10// there's no guarantees that it does. So it's up to us to eventually optimize
11// this.
12pub struct Iter<'a> {
13 pub(crate) inner: &'a mut Bitfield,
14 pub(crate) cursor: usize,
15}
16
17impl<'a> Iter<'a> {
18 #[inline]
19 pub(crate) fn new(inner: &'a mut Bitfield) -> Self {
20 Self { inner, cursor: 0 }
21 }
22}
23
24impl<'a> iter::Iterator for Iter<'a> {
25 type Item = bool;
26
27 fn next(&mut self) -> Option<Self::Item> {
28 let cursor = self.cursor;
29 self.cursor += 1;
30
31 // Each byte contains 8 bits, so we must iterate over each bit.
32 if cursor >= self.inner.len() {
33 None
34 } else {
35 Some(self.inner.get(cursor))
36 }
37 }
38}