iterators_collection/core/
mod.rs

1//! Some useful features shared by more than one other module or impossible to class in one of these
2
3/// A resettable iterator. It means that calling a `reset` method will set the iterator to the first position
4pub trait ResettableIterator: Iterator {
5    /// Resets the iterator to its initial state when called
6    fn reset(&mut self);
7
8    /// Creates a new iterator from the current one and reset it
9    fn reset_clone(&self) -> Self
10    where
11        Self: Clone,
12    {
13        let mut new = self.clone();
14        new.reset();
15        new
16    }
17
18    /// Creates a ResettableMap from the current iterator
19    fn resettable_map<F, R>(self, callback: F) -> self::ResettableMap<Self, F>
20    where
21        F: FnMut(Self::Item) -> R,
22        Self: Sized,
23    {
24        ResettableMap {
25            iterator: self,
26            callback,
27        }
28    }
29}
30
31/// A resettable version of `std::iter::Map`. A simple trait implementation is not suitable because it requires to get access to private elements of `std::iter::Map` like the iterator stored
32/// 
33/// You can use it like you would use `std::iter::Map` but it implements the `ResettableIterator` trait too
34pub struct ResettableMap<I, F> {
35    iterator: I,
36    callback: F,
37}
38
39impl<I, F, R> Iterator for ResettableMap<I, F>
40where
41    I: Iterator,
42    F: FnMut(I::Item) -> R,
43{
44    type Item = R;
45
46    fn next(&mut self) -> Option<R> {
47        let item = self.iterator.next()?;
48        let result = (self.callback)(item);
49
50        Some(result)
51    }
52}
53
54impl<I, F, R> self::ResettableIterator for ResettableMap<I, F>
55where
56    I: self::ResettableIterator,
57    F: FnMut(I::Item) -> R,
58{
59    fn reset(&mut self) {
60        self.iterator.reset();
61    }
62}
63
64impl<I, F, R> crate::child::ChildIterator for ResettableMap<I, F>
65where
66    I: Iterator,
67    F: FnMut(I::Item) -> R,
68{
69    type Parent = I;
70
71    fn release_parent(self) -> I {
72        self.iterator
73    }
74
75    fn get_parent_mut(&mut self) -> &mut I {
76        &mut self.iterator
77    }
78
79    fn get_parent(&self) -> &I {
80        &self.iterator
81    }
82}