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
72
pub trait CloneEachIterator<'a, E>: Iterator<Item=&'a E> + Sized where E: 'a + Clone {
fn clone_each(self) -> CloneEach<Self> {
CloneEach {
iter: self,
}
}
}
impl<'a, It, E> CloneEachIterator<'a, E> for It where It: Iterator<Item=&'a E>, E: 'a + Clone {}
#[derive(Clone, Debug)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct CloneEach<It> {
iter: It,
}
impl<It> CloneEach<It> {
pub fn unwrap(self) -> It {
self.iter
}
}
impl<'a, It, E> Iterator for CloneEach<It> where It: Iterator<Item=&'a E>, E: 'a + Clone {
type Item = E;
fn next(&mut self) -> Option<E> {
match self.iter.next() {
None => None,
Some(e) => Some(e.clone())
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, E, It> DoubleEndedIterator for CloneEach<It> where It: DoubleEndedIterator<Item=&'a E>, E: 'a + Clone {
fn next_back(&mut self) -> Option<E> {
self.iter.next_back().map(|e| e.clone())
}
}
#[test]
fn test_clone_each() {
let it: Vec<i32> = vec![1, 2, 3];
let mut it = it.iter().clone_each();
assert_eq!(it.next(), Some(1));
assert_eq!(it.next(), Some(2));
assert_eq!(it.next(), Some(3));
assert_eq!(it.next(), None);
}