itertools/
put_back_n_impl.rs1use alloc::vec::Vec;
2
3use crate::size_hint;
4
5#[derive(Debug, Clone)]
10#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
11pub struct PutBackN<I: Iterator> {
12 top: Vec<I::Item>,
13 iter: I,
14}
15
16pub fn put_back_n<I>(iterable: I) -> PutBackN<I::IntoIter>
21where
22 I: IntoIterator,
23{
24 PutBackN {
25 top: Vec::new(),
26 iter: iterable.into_iter(),
27 }
28}
29
30impl<I: Iterator> PutBackN<I> {
31 #[inline]
46 pub fn put_back(&mut self, x: I::Item) {
47 self.top.push(x);
48 }
49}
50
51impl<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}