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