1 | use alloc::vec::Vec; |
2 | |
3 | use crate::size_hint; |
4 | |
5 | /// An iterator adaptor that allows putting multiple |
6 | /// items in front of the iterator. |
7 | /// |
8 | /// Iterator element type is `I::Item`. |
9 | #[derive (Debug, Clone)] |
10 | #[must_use = "iterator adaptors are lazy and do nothing unless consumed" ] |
11 | pub struct PutBackN<I: Iterator> { |
12 | top: Vec<I::Item>, |
13 | iter: I, |
14 | } |
15 | |
16 | /// Create an iterator where you can put back multiple values to the front |
17 | /// of the iteration. |
18 | /// |
19 | /// Iterator element type is `I::Item`. |
20 | pub fn put_back_n<I>(iterable: I) -> PutBackN<I::IntoIter> |
21 | where |
22 | I: IntoIterator, |
23 | { |
24 | PutBackN { |
25 | top: Vec::new(), |
26 | iter: iterable.into_iter(), |
27 | } |
28 | } |
29 | |
30 | impl<I: Iterator> PutBackN<I> { |
31 | /// Puts x in front of the iterator. |
32 | /// The values are yielded in order of the most recently put back |
33 | /// values first. |
34 | /// |
35 | /// ```rust |
36 | /// use itertools::put_back_n; |
37 | /// |
38 | /// let mut it = put_back_n(1..5); |
39 | /// it.next(); |
40 | /// it.put_back(1); |
41 | /// it.put_back(0); |
42 | /// |
43 | /// assert!(itertools::equal(it, 0..5)); |
44 | /// ``` |
45 | #[inline ] |
46 | pub fn put_back(&mut self, x: I::Item) { |
47 | self.top.push(x); |
48 | } |
49 | } |
50 | |
51 | impl<I: Iterator> Iterator for PutBackN<I> { |
52 | type Item = I::Item; |
53 | #[inline ] |
54 | fn next(&mut self) -> Option<Self::Item> { |
55 | self.top.pop().or_else(|| self.iter.next()) |
56 | } |
57 | |
58 | #[inline ] |
59 | fn size_hint(&self) -> (usize, Option<usize>) { |
60 | size_hint::add_scalar(self.iter.size_hint(), self.top.len()) |
61 | } |
62 | |
63 | fn fold<B, F>(self, mut init: B, mut f: F) -> B |
64 | where |
65 | F: FnMut(B, Self::Item) -> B, |
66 | { |
67 | init = self.top.into_iter().rfold(init, &mut f); |
68 | self.iter.fold(init, f) |
69 | } |
70 | } |
71 | |