embedrs_bytes/buf/
iter.rs

1use Buf;
2
3/// Iterator over the bytes contained by the buffer.
4///
5/// This struct is created by the [`iter`] method on [`Buf`].
6///
7/// # Examples
8///
9/// Basic usage:
10///
11/// ```
12/// use embedrs_bytes::{Buf, IntoBuf, Bytes};
13///
14/// let buf = Bytes::from(&b"abc"[..]).into_buf();
15/// let mut iter = buf.iter();
16///
17/// assert_eq!(iter.next(), Some(b'a'));
18/// assert_eq!(iter.next(), Some(b'b'));
19/// assert_eq!(iter.next(), Some(b'c'));
20/// assert_eq!(iter.next(), None);
21/// ```
22///
23/// [`iter`]: trait.Buf.html#method.iter
24/// [`Buf`]: trait.Buf.html
25#[derive(Debug)]
26pub struct Iter<T> {
27    inner: T,
28}
29
30impl<T> Iter<T> {
31    /// Consumes this `Iter`, returning the underlying value.
32    ///
33    /// # Examples
34    ///
35    /// ```rust
36    /// use embedrs_bytes::{Buf, IntoBuf, Bytes};
37    ///
38    /// let buf = Bytes::from(&b"abc"[..]).into_buf();
39    /// let mut iter = buf.iter();
40    ///
41    /// assert_eq!(iter.next(), Some(b'a'));
42    ///
43    /// let buf = iter.into_inner();
44    /// assert_eq!(2, buf.remaining());
45    /// ```
46    pub fn into_inner(self) -> T {
47        self.inner
48    }
49
50    /// Gets a reference to the underlying `Buf`.
51    ///
52    /// It is inadvisable to directly read from the underlying `Buf`.
53    ///
54    /// # Examples
55    ///
56    /// ```rust
57    /// use embedrs_bytes::{Buf, IntoBuf, Bytes};
58    ///
59    /// let buf = Bytes::from(&b"abc"[..]).into_buf();
60    /// let mut iter = buf.iter();
61    ///
62    /// assert_eq!(iter.next(), Some(b'a'));
63    ///
64    /// assert_eq!(2, iter.get_ref().remaining());
65    /// ```
66    pub fn get_ref(&self) -> &T {
67        &self.inner
68    }
69
70    /// Gets a mutable reference to the underlying `Buf`.
71    ///
72    /// It is inadvisable to directly read from the underlying `Buf`.
73    ///
74    /// # Examples
75    ///
76    /// ```rust
77    /// use embedrs_bytes::{Buf, IntoBuf, BytesMut};
78    ///
79    /// let buf = BytesMut::from(&b"abc"[..]).into_buf();
80    /// let mut iter = buf.iter();
81    ///
82    /// assert_eq!(iter.next(), Some(b'a'));
83    ///
84    /// iter.get_mut().set_position(0);
85    ///
86    /// assert_eq!(iter.next(), Some(b'a'));
87    /// ```
88    pub fn get_mut(&mut self) -> &mut T {
89        &mut self.inner
90    }
91}
92
93pub fn new<T>(inner: T) -> Iter<T> {
94    Iter { inner: inner }
95}
96
97impl<T: Buf> Iterator for Iter<T> {
98    type Item = u8;
99
100    fn next(&mut self) -> Option<u8> {
101        if !self.inner.has_remaining() {
102            return None;
103        }
104
105        let b = self.inner.bytes()[0];
106        self.inner.advance(1);
107        Some(b)
108    }
109
110    fn size_hint(&self) -> (usize, Option<usize>) {
111        let rem = self.inner.remaining();
112        (rem, Some(rem))
113    }
114}
115
116impl<T: Buf> ExactSizeIterator for Iter<T> { }