Skip to content

Commit

Permalink
WithPosition::fold
Browse files Browse the repository at this point in the history
  • Loading branch information
Philippe-Cholet committed Oct 2, 2023
1 parent 20611c8 commit a3edd8d
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/with_position.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,33 @@ impl<I: Iterator> Iterator for WithPosition<I> {
fn size_hint(&self) -> (usize, Option<usize>) {
self.peekable.size_hint()
}

fn fold<B, F>(mut self, mut init: B, mut f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
if !self.handled_first {
// Haven't seen the first item yet, and there might be one to give.
self.handled_first = true;
if let Some(first) = self.peekable.next() {
// Peek to see if this is also the last item,
// in which case tag it as `Only`.
match self.peekable.peek() {
Some(_) => init = f(init, (Position::First, first)),
None => return f(init, (Position::Only, first)),
}
}
}
if let Some(mut head) = self.peekable.next() {
// Have seen the first item, and there's something left.
(init, head) = self.peekable.fold((init, head), |(acc, old), new| {
(f(acc, (Position::Middle, old)), new)
});
// The "head" is now the last item.
init = f(init, (Position::Last, head));
}
init
}
}

impl<I> ExactSizeIterator for WithPosition<I> where I: ExactSizeIterator {}
Expand Down

0 comments on commit a3edd8d

Please sign in to comment.