Skip to content

Instantly share code, notes, and snippets.

@HackerFoo
Created October 15, 2022 19:06
Show Gist options
  • Save HackerFoo/c83bfbc5aefeb97bbff1db12d297b179 to your computer and use it in GitHub Desktop.
Save HackerFoo/c83bfbc5aefeb97bbff1db12d297b179 to your computer and use it in GitHub Desktop.
pub struct After<A, I>
where
I: Iterator<Item = A>,
A: Clone,
{
iter: I,
first: Option<A>,
item: Option<A>,
}
impl<A, I> Iterator for After<A, I>
where
I: Iterator<Item = A>,
A: Copy,
{
type Item = (A, A);
fn next(&mut self) -> Option<Self::Item> {
if let Some(x) = replace(&mut self.item, self.iter.next()) {
if let Some(y) = self.item {
Some((x, y))
} else {
replace(&mut self.first, None).map(|y| (x, y))
}
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
pub fn after<A, I>(mut iter: I) -> After<A, I>
where
I: Iterator<Item = A>,
A: Copy,
{
let first = iter.next();
After {
iter,
first,
item: first,
}
}
#[cfg(test)]
#[test]
fn after_test() {
let v: Vec<(u32, u32)> = after(0..5).collect();
assert_eq!(v, vec![(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment