-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathput_back_n.rs
71 lines (63 loc) · 1.6 KB
/
put_back_n.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::iter::Peekable;
#[derive(Debug, Clone)]
pub struct PutBackN<I: Iterator> {
top: Vec<I::Item>,
iter: Peekable<I>,
}
pub fn put_back_n<I>(iterable: I) -> PutBackN<I::IntoIter>
where I: IntoIterator
{
PutBackN {
top: Vec::new(),
iter: iterable.into_iter().peekable(),
}
}
impl<I: Iterator> PutBackN<I> {
#[inline]
pub(crate)
fn put_back(&mut self, item: I::Item) {
self.top.push(item);
}
#[inline]
pub fn take_buf(&mut self) -> Vec<I::Item> {
std::mem::replace(&mut self.top, vec![])
}
#[inline]
pub(crate)
fn peek(&mut self) -> Option<&I::Item> {
if self.top.is_empty() {
/* This is a kludge for Ctrl-D not being
* handled properly if self.iter().peek() isn't called
* first. */
match self.iter.peek() {
Some(_) => {
self.iter.next().and_then(move |item| {
self.top.push(item);
self.top.last()
})
}
None => {
None
}
}
} else {
self.top.last()
}
}
#[inline]
pub(crate)
fn put_back_all<DEI: DoubleEndedIterator<Item = I::Item>>(&mut self, iter: DEI) {
self.top.extend(iter.rev());
}
}
impl<I: Iterator> Iterator for PutBackN<I> {
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
if self.top.is_empty() {
self.iter.next()
} else {
self.top.pop()
}
}
}