|
| 1 | +#[unstable(feature = "peekable_iterator", issue = "132973")] |
| 2 | +/// Iterators which inherently support `peek()` without needing to be wrapped by a `Peekable`. |
| 3 | +pub trait PeekableIterator: Iterator { |
| 4 | + /// returns a reference to the `next()` value without advancing the iterator. |
| 5 | + /// Just like `next()`, if there is a value, it returns a reference to it in Some() |
| 6 | + /// if the iteration is finished, a `None` is returned |
| 7 | + /// |
| 8 | + /// # Examples |
| 9 | + /// Basic usage: |
| 10 | + /// ``` |
| 11 | + /// let xs = [1, 2, 3]; |
| 12 | + /// let mut iter = xs.iter(); |
| 13 | + /// |
| 14 | + /// // peek() allows us to check the future value |
| 15 | + /// assert_eq!(iter.peek(), Some(&&1)); |
| 16 | + /// assert_eq!(iter.next(), Some(&1)); |
| 17 | + /// |
| 18 | + /// // peek() doesn't move the iterator forward |
| 19 | + /// assert_eq!(iter.peek(), Some(&&2)); |
| 20 | + /// assert_eq!(iter.peek(), Some(&&2)); |
| 21 | + /// |
| 22 | + /// ``` |
| 23 | + fn peek(&mut self) -> Option<&Self::Item>; |
| 24 | + |
| 25 | + /// returns the `next()` element if a predicate holds true |
| 26 | + fn next_if(&mut self, func: impl FnOnce(&Self::Item) -> bool) -> Option<Self::Item> { |
| 27 | + let Some(item) = self.peek() else { |
| 28 | + return None; |
| 29 | + }; |
| 30 | + |
| 31 | + if func(item) { self.next() } else { None } |
| 32 | + } |
| 33 | + |
| 34 | + /// move forward and return the `next()` item if it is equal to the expected value |
| 35 | + fn next_if_eq<T>(&mut self, expected: &T) -> Option<Self::Item> |
| 36 | + where |
| 37 | + Self::Item: PartialEq<T>, |
| 38 | + T: ?Sized, |
| 39 | + { |
| 40 | + self.next_if(|x| x == expected) |
| 41 | + } |
| 42 | +} |
0 commit comments