Skip to content

Commit 9e0f1ae

Browse files
committed
remove peek_map, add examples
1 parent bf88550 commit 9e0f1ae

File tree

1 file changed

+55
-6
lines changed

1 file changed

+55
-6
lines changed

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

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,65 @@
22
/// Iterators which inherently support peeking without needing to be wrapped by a `Peekable`.
33
pub trait PeekableIterator: Iterator {
44
/// Executes the closure with a reference to the `next()` value without advancing the iterator.
5+
///
6+
/// # Examples
7+
///
8+
/// Basic usage:
9+
/// ```
10+
/// #![feature(peekable_iterator)]
11+
/// use std::iter::PeekableIterator;
12+
///
13+
/// let mut vals = [0, 1, 2].into_iter();
14+
///
15+
/// assert_eq!(vals.peek_with(|x| x.copied()), Some(0));
16+
/// // element is not consumed
17+
/// assert_eq!(vals.next(), Some(0));
18+
///
19+
/// // examine the pending element
20+
/// assert_eq!(vals.peek_with(|x| x), Some(&1));
21+
/// assert_eq!(vals.next(), Some(1));
22+
///
23+
/// // determine if the iterator has an element without advancing
24+
/// assert_eq!(vals.peek_with(|x| x.is_some()), false);
25+
/// assert_eq!(vals.next(), Some(2));
26+
///
27+
/// // exhausted iterator
28+
/// assert_eq!(vals.next(), None);
29+
/// assert_eq!(vals.peek_with(|x| x), None);
30+
/// ```
531
fn peek_with<T>(&mut self, func: impl for<'a> FnOnce(Option<&'a Self::Item>) -> T) -> T;
632

7-
/// Executes the closure on the `next()` element without advancing the iterator, or returns `None` if the iterator is exhausted.
8-
fn peek_map<T>(&mut self, func: impl for<'a> FnOnce(&'a Self::Item) -> T) -> Option<T> {
9-
self.peek_with(|x| x.map(|y| func(y)))
10-
}
11-
1233
/// Returns the `next()` element if the given predicate holds true.
34+
///
35+
/// # Examples
36+
///
37+
/// Basic usage:
38+
/// ```
39+
/// #![feature(peekable_iterator)]
40+
/// use std::iter::PeekableIterator;
41+
/// fn parse_number(s: &str) -> u32 {
42+
/// let mut c = s.chars();
43+
///
44+
/// let base = if c.next_if_eq(&"0").is_some() {
45+
/// match c.next_if(|c| "oxb".contains(c)) {
46+
/// Some("x") => 16,
47+
/// Some("b") => 2,
48+
/// _ => 8
49+
/// }
50+
/// } else {
51+
/// 10
52+
/// }
53+
///
54+
/// u32::from_str_radix(c.as_str(), base).unwrap()
55+
/// }
56+
///
57+
/// assert_eq!(parse_number("055"), 45);
58+
/// assert_eq!(parse_number("0o42"), 34);
59+
/// assert_eq!(parse_number("0x11"), 17);
60+
/// ```
61+
///
1362
fn next_if(&mut self, func: impl FnOnce(&Self::Item) -> bool) -> Option<Self::Item> {
14-
match self.peek_map(func) {
63+
match self.peek_with(|x| x.map(|y| func(y))) {
1564
Some(true) => self.next(),
1665
_ => None,
1766
}

0 commit comments

Comments
 (0)