Skip to main content

abin/binary/
into_iter.rs

1use crate::AnyBin;
2
3/// Consuming iterator for a binary.
4#[derive(Debug)]
5pub struct IntoIter<T> {
6    pos: usize,
7    inner: T,
8    len: usize,
9}
10
11impl<T: AnyBin> IntoIter<T> {
12    /// Creates an iterator over the bytes contained by the binary, starting at given
13    /// position (`pos`). The position is usually `0` (if you want to read the binary from
14    /// the start).
15    pub(crate) fn new(inner: T, pos: usize) -> Self {
16        let len = inner.len();
17        Self { inner, pos, len }
18    }
19
20    /// Consumes this `IntoIter`, returning the underlying value.
21    pub fn into_inner(self) -> T {
22        self.inner
23    }
24}
25
26impl<T: AnyBin> Iterator for IntoIter<T> {
27    type Item = u8;
28
29    #[inline]
30    fn next(&mut self) -> Option<u8> {
31        let current_pos = self.pos;
32        if current_pos < self.len {
33            self.pos += 1;
34            Some(self.inner.as_slice()[current_pos])
35        } else {
36            // out of bounds
37            None
38        }
39    }
40
41    #[inline]
42    fn size_hint(&self) -> (usize, Option<usize>) {
43        let rem = if self.pos < self.len {
44            self.len - self.pos
45        } else {
46            0
47        };
48        (rem, Some(rem))
49    }
50}
51
52impl<T: AnyBin> ExactSizeIterator for IntoIter<T> {}