Skip to content

Commit b8a77c4

Browse files
Philippe-Choletphimuemue
authored andcommitted
WithPosition::fold
1 parent 9b28180 commit b8a77c4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/with_position.rs

+27
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,33 @@ impl<I: Iterator> Iterator for WithPosition<I> {
8181
fn size_hint(&self) -> (usize, Option<usize>) {
8282
self.peekable.size_hint()
8383
}
84+
85+
fn fold<B, F>(mut self, mut init: B, mut f: F) -> B
86+
where
87+
F: FnMut(B, Self::Item) -> B,
88+
{
89+
if let Some(mut head) = self.peekable.next() {
90+
if !self.handled_first {
91+
// The current head is `First` or `Only`,
92+
// it depends if there is another item or not.
93+
match self.peekable.next() {
94+
Some(second) => {
95+
let first = std::mem::replace(&mut head, second);
96+
init = f(init, (Position::First, first));
97+
}
98+
None => return f(init, (Position::Only, head)),
99+
}
100+
}
101+
// Have seen the first item, and there's something left.
102+
init = self.peekable.fold(init, |acc, mut item| {
103+
std::mem::swap(&mut head, &mut item);
104+
f(acc, (Position::Middle, item))
105+
});
106+
// The "head" is now the last item.
107+
init = f(init, (Position::Last, head));
108+
}
109+
init
110+
}
84111
}
85112

86113
impl<I> ExactSizeIterator for WithPosition<I> where I: ExactSizeIterator {}

0 commit comments

Comments
 (0)