|
2 | 2 | /// Iterators which inherently support peeking without needing to be wrapped by a `Peekable`. |
3 | 3 | pub trait PeekableIterator: Iterator { |
4 | 4 | /// 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 | + /// ``` |
5 | 31 | fn peek_with<T>(&mut self, func: impl for<'a> FnOnce(Option<&'a Self::Item>) -> T) -> T; |
6 | 32 |
|
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 | | - |
12 | 33 | /// 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 | + /// |
13 | 62 | 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))) { |
15 | 64 | Some(true) => self.next(), |
16 | 65 | _ => None, |
17 | 66 | } |
|
0 commit comments