-
Notifications
You must be signed in to change notification settings - Fork 308
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Warren Wise <[email protected]>
- Loading branch information
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
/// An iterator adaptor that combines each element except the first with a clone of the previous. | ||
/// | ||
/// See [`.with_prev()`](crate::Itertools::with_prev) for more information. | ||
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"] | ||
pub struct WithPrev<I> | ||
where | ||
I: Iterator, | ||
{ | ||
iter: I, | ||
prev: Option<I::Item>, | ||
} | ||
|
||
impl<I> Clone for WithPrev<I> | ||
where | ||
I: Clone + Iterator, | ||
I::Item: Clone, | ||
{ | ||
clone_fields!(iter, prev); | ||
} | ||
|
||
/// Create a new `WithPrev` iterator. | ||
pub fn with_prev<I>(iter: I) -> WithPrev<I> | ||
where | ||
I: Iterator, | ||
{ | ||
WithPrev { iter, prev: None } | ||
} | ||
|
||
impl<I> Iterator for WithPrev<I> | ||
where | ||
I: Iterator, | ||
I::Item: Clone, | ||
{ | ||
type Item = (Option<I::Item>, I::Item); | ||
|
||
fn next(&mut self) -> Option<Self::Item> { | ||
let next = self.iter.next()?; | ||
let prev = std::mem::replace(&mut self.prev, Some(next.clone())); | ||
Some((prev, next)) | ||
} | ||
} |