makepad_vector/internal_iter/
internal_iterator.rs

1use crate::internal_iter::FromInternalIterator;
2
3/// A trait for internal iterators. An internal iterator differs from a normal iterator in that its
4/// iteration is controlled internally by the iterator itself, instead of externally by the calling
5/// code. This means that instead of returning a single item on each call to `next`, internal
6/// iterators call a closure for each item on a single call to `for_each`. This allows internal
7/// operators to be implemented recursively, something that is not possible with normal iterators.
8pub trait InternalIterator {
9    type Item;
10
11    /// Calls `f` with each item of `self`.
12    ///
13    /// If `f` returns `false`, iteration is aborted. If iteration was aborted, this function
14    /// returns `false`.
15    fn for_each<F>(self, f: &mut F) -> bool
16    where
17        F: FnMut(Self::Item) -> bool;
18
19    /// Transforms `self` into a collection.
20    fn collect<F>(self) -> F
21    where
22        Self: Sized,
23        F: FromInternalIterator<Self::Item>,
24    {
25        FromInternalIterator::from_internal_iter(self)
26    }
27
28    /// Returns an internal iterator that applies `f` to each item of `self`.
29    fn map<R, F>(self, f: F) -> Map<Self, F>
30    where
31        Self: Sized,
32        F: FnMut(Self::Item) -> R,
33    {
34        Map {
35            internal_iter: self,
36            f,
37        }
38    }
39}
40
41impl<I> InternalIterator for I
42where
43    I: Iterator,
44{
45    type Item = I::Item;
46
47    fn for_each<F>(self, f: &mut F) -> bool
48    where
49        F: FnMut(Self::Item) -> bool,
50    {
51        for item in self {
52            if !f(item) {
53                return false;
54            }
55        }
56        true
57    }
58}
59
60/// An internal iterator that applies `f` to each item of `self`.
61#[derive(Clone, Debug)]
62pub struct Map<I, F> {
63    internal_iter: I,
64    f: F,
65}
66
67impl<R, I, F> InternalIterator for Map<I, F>
68where
69    I: InternalIterator,
70    F: FnMut(I::Item) -> R,
71{
72    type Item = R;
73
74    fn for_each<G>(mut self, g: &mut G) -> bool
75    where
76        G: FnMut(Self::Item) -> bool,
77    {
78        self.internal_iter.for_each({
79            let f = &mut self.f;
80            &mut move |item| g((f)(item))
81        })
82    }
83}