Skip to content

Commit bf55b14

Browse files
committed
Impl From<Peekable> for Iterator
1 parent ca4e54f commit bf55b14

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

library/core/src/iter/adapters/peekable.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,29 @@ use crate::ops::{ControlFlow, Try};
77
///
88
/// This `struct` is created by the [`peekable`] method on [`Iterator`]. See its
99
/// documentation for more.
10+
///
11+
/// `Peakable` has a implementation: `impl<I: Interator> From<Peekable<I>> for I`, use `I::from()` can get back to [`Iterator`].
12+
/// ```rust
13+
/// struct Counter {
14+
/// v: usize,
15+
/// }
16+
///
17+
/// impl Iterator for Counter {
18+
/// type Item = usize;
19+
///
20+
/// fn next(&mut self) -> Option<Self::Item> {
21+
/// let v = self.v;
22+
/// self.v += 1;
23+
/// Some(v)
24+
/// }
25+
/// }
26+
///
27+
/// let counter = Counter { v: 0 };
28+
/// let mut peekable = counter.peekable();
29+
/// assert_eq!(peekable.peek(), Some(&0));
30+
/// let counter: Counter = Counter::from(peekable);
31+
/// assert_eq!(counter.next(), Some(0));
32+
/// ```
1033
///
1134
/// [`peekable`]: Iterator::peekable
1235
/// [`Iterator`]: trait.Iterator.html
@@ -26,6 +49,12 @@ impl<I: Iterator> Peekable<I> {
2649
}
2750
}
2851

52+
impl<I: Interator> From<Peekable<I>> for I {
53+
fn from(p: Peekable<I>) -> Self {
54+
p.iter
55+
}
56+
}
57+
2958
// Peekable must remember if a None has been seen in the `.peek()` method.
3059
// It ensures that `.peek(); .peek();` or `.peek(); .next();` only advances the
3160
// underlying iterator at most once. This does not by itself make the iterator

0 commit comments

Comments
 (0)