Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions library/core/src/iter/adapters/peekable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,29 @@ use crate::ops::{ControlFlow, Try};
///
/// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
/// documentation for more.
///
/// `Peakable` has an implementation: `impl<I: Interator> From<Peekable<I>> for I`, use `I::from()` can get back to [`Iterator`].
/// ```rust
/// struct Counter {
/// v: usize,
/// }
///
/// impl Iterator for Counter {
/// type Item = usize;
///
/// fn next(&mut self) -> Option<Self::Item> {
/// let v = self.v;
/// self.v += 1;
/// Some(v)
/// }
/// }
///
/// let counter = Counter { v: 0 };
/// let mut peekable = counter.peekable();
/// assert_eq!(peekable.peek(), Some(&0));
/// let counter = Counter::from(peekable);
/// assert_eq!(counter.next(), Some(0));
/// ```
///
/// [`peekable`]: Iterator::peekable
/// [`Iterator`]: trait.Iterator.html
Expand All @@ -26,6 +49,12 @@ impl<I: Iterator> Peekable<I> {
}
}

impl<I: Iterator> From<Peekable<I>> for I {
fn from(p: Peekable<I>) -> Self {
p.iter
}
}

// Peekable must remember if a None has been seen in the `.peek()` method.
// It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
// underlying iterator at most once. This does not by itself make the iterator
Expand Down
Loading