core/iter/adapters/
scan.rs

1use crate::fmt;
2use crate::iter::InPlaceIterable;
3use crate::iter::adapters::SourceIter;
4use crate::num::NonZero;
5use crate::ops::{ControlFlow, Try};
6
7/// An iterator to maintain state while iterating another iterator.
8///
9/// This `struct` is created by the [`scan`] method on [`Iterator`]. See its
10/// documentation for more.
11///
12/// [`scan`]: Iterator::scan
13/// [`Iterator`]: trait.Iterator.html
14#[must_use = "iterators are lazy and do nothing unless consumed"]
15#[stable(feature = "rust1", since = "1.0.0")]
16#[derive(Clone)]
17pub struct Scan<I, St, F> {
18    iter: I,
19    f: F,
20    state: St,
21}
22
23impl<I, St, F> Scan<I, St, F> {
24    pub(in crate::iter) fn new(iter: I, state: St, f: F) -> Scan<I, St, F> {
25        Scan { iter, state, f }
26    }
27}
28
29#[stable(feature = "core_impl_debug", since = "1.9.0")]
30impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.debug_struct("Scan").field("iter", &self.iter).field("state", &self.state).finish()
33    }
34}
35
36#[stable(feature = "rust1", since = "1.0.0")]
37impl<B, I, St, F> Iterator for Scan<I, St, F>
38where
39    I: Iterator,
40    F: FnMut(&mut St, I::Item) -> Option<B>,
41{
42    type Item = B;
43
44    #[inline]
45    fn next(&mut self) -> Option<B> {
46        let a = self.iter.next()?;
47        (self.f)(&mut self.state, a)
48    }
49
50    #[inline]
51    fn size_hint(&self) -> (usize, Option<usize>) {
52        let (_, upper) = self.iter.size_hint();
53        (0, upper) // can't know a lower bound, due to the scan function
54    }
55
56    #[inline]
57    fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
58    where
59        Self: Sized,
60        Fold: FnMut(Acc, Self::Item) -> R,
61        R: Try<Output = Acc>,
62    {
63        fn scan<'a, T, St, B, Acc, R: Try<Output = Acc>>(
64            state: &'a mut St,
65            f: &'a mut impl FnMut(&mut St, T) -> Option<B>,
66            mut fold: impl FnMut(Acc, B) -> R + 'a,
67        ) -> impl FnMut(Acc, T) -> ControlFlow<R, Acc> + 'a {
68            move |acc, x| match f(state, x) {
69                None => ControlFlow::Break(try { acc }),
70                Some(x) => ControlFlow::from_try(fold(acc, x)),
71            }
72        }
73
74        let state = &mut self.state;
75        let f = &mut self.f;
76        self.iter.try_fold(init, scan(state, f, fold)).into_try()
77    }
78
79    impl_fold_via_try_fold! { fold -> try_fold }
80}
81
82#[unstable(issue = "none", feature = "inplace_iteration")]
83unsafe impl<St, F, I> SourceIter for Scan<I, St, F>
84where
85    I: SourceIter,
86{
87    type Source = I::Source;
88
89    #[inline]
90    unsafe fn as_inner(&mut self) -> &mut I::Source {
91        // SAFETY: unsafe function forwarding to unsafe function with the same requirements
92        unsafe { SourceIter::as_inner(&mut self.iter) }
93    }
94}
95
96#[unstable(issue = "none", feature = "inplace_iteration")]
97unsafe impl<St, F, I: InPlaceIterable> InPlaceIterable for Scan<I, St, F> {
98    const EXPAND_BY: Option<NonZero<usize>> = I::EXPAND_BY;
99    const MERGE_BY: Option<NonZero<usize>> = I::MERGE_BY;
100}