internal_iterator/
adaptors.rs

1use core::ops::ControlFlow;
2
3use crate::{InternalIterator, IntoInternalIterator};
4
5
6/// An iterator that links two iterators together, in a chain.
7#[derive(Clone)]
8pub struct Chain<A, B> {
9    pub(crate) first: A,
10    pub(crate) second: B,
11}
12
13impl<A, B> InternalIterator for Chain<A, B>
14where
15    A: InternalIterator,
16    B: InternalIterator<Item = A::Item>,
17{
18    type Item = A::Item;
19
20    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
21    where
22        C: FnMut(Self::Item) -> ControlFlow<R>
23    {
24        let Self { first, second } = self;
25        match first.try_for_each(&mut consumer) {
26            ControlFlow::Continue(()) => second.try_for_each(consumer),
27            br => br,
28        }
29    }
30
31    fn last(self) -> Option<Self::Item> {
32        match (self.first.last(), self.second.last()) {
33            (_, Some(x)) | (Some(x), None) => Some(x),
34            (None, None) => None,
35        }
36    }
37}
38
39
40/// An iterator that clones the elements of an underlying iterator.
41#[derive(Clone)]
42pub struct Cloned<I> {
43    pub(crate) iter: I,
44}
45
46impl<'a, I, T: 'a> InternalIterator for Cloned<I>
47where
48    I: InternalIterator<Item = &'a T>,
49    T: Clone,
50{
51    type Item = T;
52
53    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
54    where
55        C: FnMut(Self::Item) -> ControlFlow<R>
56    {
57        self.iter.try_for_each(|item| consumer(item.clone()))
58    }
59}
60
61
62/// An iterator that copies the elements of an underlying iterator.
63#[derive(Clone)]
64pub struct Copied<I> {
65    pub(crate) iter: I,
66}
67
68impl<'a, I, T: 'a> InternalIterator for Copied<I>
69where
70    I: InternalIterator<Item = &'a T>,
71    T: Copy,
72{
73    type Item = T;
74
75    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
76    where
77        C: FnMut(Self::Item) -> ControlFlow<R>
78    {
79        self.iter.try_for_each(|&item| consumer(item))
80    }
81
82    fn count(self) -> usize {
83        self.iter.count()
84    }
85
86    fn last(self) -> Option<Self::Item> {
87        self.iter.last().copied()
88    }
89
90    fn nth(self, n: usize) -> Option<Self::Item> {
91        self.iter.nth(n).copied()
92    }
93}
94
95
96/// An iterator that yields the current count and the element during iteration.
97#[derive(Clone)]
98pub struct Enumerate<I> {
99    pub(crate) iter: I,
100}
101
102impl<I> InternalIterator for Enumerate<I>
103where
104    I: InternalIterator,
105{
106    type Item = (usize, I::Item);
107
108    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
109    where
110        C: FnMut(Self::Item) -> ControlFlow<R>
111    {
112        let mut idx = 0;
113        self.iter.try_for_each(|item| {
114            let next = idx + 1;
115            let idx = core::mem::replace(&mut idx, next);
116            consumer((idx, item))
117        })
118    }
119
120    fn count(self) -> usize {
121        self.iter.count()
122    }
123
124    fn nth(self, n: usize) -> Option<Self::Item> {
125        let value = self.iter.nth(n)?;
126        Some((n, value))
127    }
128}
129
130
131/// An iterator that filters the elements of `iter` with `predicate`.
132#[derive(Clone)]
133pub struct Filter<I, F> {
134    pub(crate) iter: I,
135    pub(crate) predicate: F,
136}
137
138impl<I, F> InternalIterator for Filter<I, F>
139where
140    I: InternalIterator,
141    F: FnMut(&I::Item) -> bool,
142{
143    type Item = I::Item;
144
145    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
146    where
147        C: FnMut(Self::Item) -> ControlFlow<R>
148    {
149        let Self { iter, mut predicate } = self;
150        iter.try_for_each(|item| {
151            if predicate(&item) {
152                consumer(item)
153            } else {
154                ControlFlow::Continue(())
155            }
156        })
157    }
158}
159
160
161/// An iterator that uses `f` to both filter and map elements from `iter`.
162#[derive(Clone)]
163pub struct FilterMap<I, F> {
164    pub(crate) iter: I,
165    pub(crate) f: F,
166}
167
168impl<I, F, T> InternalIterator for FilterMap<I, F>
169where
170    I: InternalIterator,
171    F: FnMut(I::Item) -> Option<T>,
172{
173    type Item = T;
174
175    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
176    where
177        C: FnMut(Self::Item) -> ControlFlow<R>
178    {
179        let Self { iter, mut f } = self;
180        iter.try_for_each(|item| match f(item) {
181            Some(mapped) => consumer(mapped),
182            None => ControlFlow::Continue(()),
183        })
184    }
185}
186
187
188/// An iterator that maps each element to an iterator, and yields the elements
189/// of the produced iterators.
190#[derive(Clone)]
191pub struct FlatMap<I, F> {
192    pub(crate) iter: I,
193    pub(crate) f: F,
194}
195
196impl<I, F, T, U> InternalIterator for FlatMap<I, F>
197where
198    I: InternalIterator,
199    F: FnMut(I::Item) -> U,
200    U: IntoInternalIterator<Item = T>,
201{
202    type Item = T;
203
204    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
205    where
206        C: FnMut(Self::Item) -> ControlFlow<R>
207    {
208        let Self { iter, mut f } = self;
209        iter.try_for_each(|item| f(item).into_internal_iter().try_for_each(&mut consumer))
210    }
211}
212
213
214/// An iterator that calls a function with a reference to each element before
215/// yielding it.
216#[derive(Clone)]
217pub struct Inspect<I, F> {
218    pub(crate) iter: I,
219    pub(crate) f: F,
220}
221
222impl<I, F> InternalIterator for Inspect<I, F>
223where
224    I: InternalIterator,
225    F: FnMut(&I::Item),
226{
227    type Item = I::Item;
228
229    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
230    where
231        C: FnMut(Self::Item) -> ControlFlow<R>
232    {
233        let Self { iter, mut f } = self;
234        iter.try_for_each(|item| {
235            f(&item);
236            consumer(item)
237        })
238    }
239}
240
241
242/// An iterator that maps the values of `iter` with `f`.
243#[derive(Clone)]
244pub struct Map<I, F> {
245    pub(crate) iter: I,
246    pub(crate) f: F,
247}
248
249impl<I, F, T> InternalIterator for Map<I, F>
250where
251    I: InternalIterator,
252    F: FnMut(I::Item) -> T,
253{
254    type Item = T;
255
256    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
257    where
258        C: FnMut(Self::Item) -> ControlFlow<R>
259    {
260        let Self { iter, mut f } = self;
261        iter.try_for_each(|item| consumer(f(item)))
262    }
263}
264
265
266/// An iterator that skips over `n` elements of `iter`.
267#[derive(Clone)]
268pub struct Skip<I> {
269    pub(crate) iter: I,
270    pub(crate) n: usize,
271}
272
273impl<I> InternalIterator for Skip<I>
274where
275    I: InternalIterator,
276{
277    type Item = I::Item;
278
279    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
280    where
281        C: FnMut(Self::Item) -> ControlFlow<R>
282    {
283        let Self { iter, mut n } = self;
284        iter.try_for_each(|item| {
285            if n == 0 {
286                consumer(item)
287            } else {
288                n -= 1;
289                ControlFlow::Continue(())
290            }
291        })
292    }
293}
294
295
296/// An iterator that only iterates over the first `n` iterations of `iter`.
297#[derive(Clone)]
298pub struct Take<I> {
299    pub(crate) iter: I,
300    pub(crate) n: usize,
301}
302
303impl<I> InternalIterator for Take<I>
304where
305    I: InternalIterator,
306{
307    type Item = I::Item;
308
309    fn try_for_each<R, C>(self, mut consumer: C) -> ControlFlow<R>
310    where
311        C: FnMut(Self::Item) -> ControlFlow<R>
312    {
313        let Self { iter, mut n } = self;
314        if n == 0 {
315            return ControlFlow::Continue(());
316        }
317        let result = iter.try_for_each(|item| {
318            n -= 1;
319            match consumer(item) {
320                _ if n == 0 => ControlFlow::Break(ControlFlow::Continue(())),
321                ControlFlow::Continue(()) => ControlFlow::Continue(()),
322                ControlFlow::Break(value) => ControlFlow::Break(ControlFlow::Break(value)),
323            }
324        });
325        match result {
326            ControlFlow::Continue(()) => ControlFlow::Continue(()),
327            ControlFlow::Break(x) => x,
328        }
329    }
330}
331
332
333/// A wrapper type to convert [`std::iter::Iterator`] to [`InternalIterator`].
334#[derive(Clone)]
335pub struct Internal<I> {
336    pub(crate) iterator: I,
337}
338
339impl<I> InternalIterator for Internal<I>
340where
341    I: Iterator
342{
343    type Item = I::Item;
344
345    fn try_for_each<T, F>(mut self, consumer: F) -> ControlFlow<T>
346    where
347        F: FnMut(Self::Item) -> ControlFlow<T>
348    {
349        self.iterator.try_for_each(consumer)
350    }
351
352    fn count(self) -> usize {
353        self.iterator.count()
354    }
355
356    fn last(self) -> Option<Self::Item> {
357        self.iterator.last()
358    }
359
360    fn nth(mut self, n: usize) -> Option<Self::Item> {
361        self.iterator.nth(n)
362    }
363}