advance_iter/
lib.rs

1//! This crate provides two structs, [`Advance`] and [`CountingAdvance`], to help with consuming iterators one step at
2//! a time. Refer to their respective documentation for more information.
3
4/// Wrapper around an iterator. Has to be advanced using the
5/// [`advance`] method, which will cache the iterator's next element
6/// in `self.current`.
7///
8/// See also [`CountingAdvance`], a similar adapter that keeps track of how
9/// many times it has been advanced.
10///
11/// [`advance`]: Advance::advance
12#[derive(Debug, Copy, Clone, Eq, PartialEq)]
13pub struct Advance<I: Iterator> {
14    current: Option<I::Item>,
15    iter: I,
16}
17
18impl<I: Iterator> Advance<I> {
19    /// Wraps the given iterator in an [`Advance`] adapter. This initiates
20    /// `self.current` with the iterator's first element (if any).
21    #[inline]
22    pub fn new(mut iter: I) -> Self {
23        Self {
24            current: iter.next(),
25            iter,
26        }
27    }
28
29    #[inline]
30    pub fn advance(&mut self) {
31        self.current = self.iter.next();
32    }
33
34    #[inline]
35    pub fn current(&self) -> Option<&I::Item> {
36        self.current.as_ref()
37    }
38
39    #[inline]
40    pub fn current_mut(&mut self) -> Option<&mut I::Item> {
41        self.current.as_mut()
42    }
43}
44
45/// Wrapper around an iterator. Has to be advanced using the
46/// [`advance`][adv_fn] method, which will cache the iterator's next element
47/// in `self.current` and increment `self.counter`.
48///
49/// See also [`Advance`], a similar adapter that does not keep track of how
50/// many times it has been advanced.
51///
52/// [adv_fn]: CountingAdvance::advance
53#[derive(Debug, Copy, Clone, Eq, PartialEq)]
54pub struct CountingAdvance<I: Iterator> {
55    counter: usize,
56    current: Option<I::Item>,
57    iter: I,
58}
59
60impl<I: Iterator> CountingAdvance<I> {
61    /// Wraps the given iterator in a [`CountingAdvance`] adapter. This
62    /// initiates `self.current` with the iterator's first element (if any)
63    /// and starts the counter at zero.
64    #[inline]
65    pub fn new(mut iter: I) -> Self {
66        Self {
67            counter: 0,
68            current: iter.next(),
69            iter,
70        }
71    }
72
73    #[inline]
74    pub fn advance(&mut self) {
75        self.counter += 1;
76        self.current = self.iter.next();
77    }
78
79    #[inline]
80    pub fn counter(&self) -> usize {
81        self.counter
82    }
83
84    #[inline]
85    pub fn current(&self) -> Option<&I::Item> {
86        self.current.as_ref()
87    }
88
89    #[inline]
90    pub fn current_mut(&mut self) -> Option<&mut I::Item> {
91        self.current.as_mut()
92    }
93}