@@ -1619,6 +1619,69 @@ impl<I: Iterator> Peekable<I> {
1619
1619
let iter = & mut self . iter ;
1620
1620
self . peeked . get_or_insert_with ( || iter. next ( ) ) . as_ref ( )
1621
1621
}
1622
+
1623
+ /// Consume the next value of this iterator if a condition is true.
1624
+ ///
1625
+ /// If `func` returns `true` for the next value of this iterator, consume and return it.
1626
+ /// Otherwise, return `None`.
1627
+ ///
1628
+ /// # Examples
1629
+ /// Consume a number if it's equal to 0.
1630
+ /// ```
1631
+ /// #![feature(peekable_next_if)]
1632
+ /// let mut iter = (0..5).peekable();
1633
+ /// // The first item of the iterator is 0; consume it.
1634
+ /// assert_eq!(iter.next_if(|&x| x == 0), Some(0));
1635
+ /// // The next item returned is now 1, so `consume` will return `false`.
1636
+ /// assert_eq!(iter.next_if(|&x| x == 0), None);
1637
+ /// // `next_if` saves the value of the next item if it was not equal to `expected`.
1638
+ /// assert_eq!(iter.next(), Some(1));
1639
+ /// ```
1640
+ ///
1641
+ /// Consume any number less than 10.
1642
+ /// ```
1643
+ /// #![feature(peekable_next_if)]
1644
+ /// let mut iter = (1..20).peekable();
1645
+ /// // Consume all numbers less than 10
1646
+ /// while iter.next_if(|&x| x < 10).is_some() {}
1647
+ /// // The next value returned will be 10
1648
+ /// assert_eq!(iter.next(), Some(10));
1649
+ /// ```
1650
+ #[ unstable( feature = "peekable_next_if" , issue = "72480" ) ]
1651
+ pub fn next_if ( & mut self , func : impl FnOnce ( & I :: Item ) -> bool ) -> Option < I :: Item > {
1652
+ match self . next ( ) {
1653
+ Some ( matched) if func ( & matched) => Some ( matched) ,
1654
+ other => {
1655
+ // Since we called `self.next()`, we consumed `self.peeked`.
1656
+ assert ! ( self . peeked. is_none( ) ) ;
1657
+ self . peeked = Some ( other) ;
1658
+ None
1659
+ }
1660
+ }
1661
+ }
1662
+
1663
+ /// Consume the next item if it is equal to `expected`.
1664
+ ///
1665
+ /// # Example
1666
+ /// Consume a number if it's equal to 0.
1667
+ /// ```
1668
+ /// #![feature(peekable_next_if)]
1669
+ /// let mut iter = (0..5).peekable();
1670
+ /// // The first item of the iterator is 0; consume it.
1671
+ /// assert_eq!(iter.next_if_eq(&0), Some(0));
1672
+ /// // The next item returned is now 1, so `consume` will return `false`.
1673
+ /// assert_eq!(iter.next_if_eq(&0), None);
1674
+ /// // `next_if_eq` saves the value of the next item if it was not equal to `expected`.
1675
+ /// assert_eq!(iter.next(), Some(1));
1676
+ /// ```
1677
+ #[ unstable( feature = "peekable_next_if" , issue = "72480" ) ]
1678
+ pub fn next_if_eq < R > ( & mut self , expected : & R ) -> Option < I :: Item >
1679
+ where
1680
+ R : ?Sized ,
1681
+ I :: Item : PartialEq < R > ,
1682
+ {
1683
+ self . next_if ( |next| next == expected)
1684
+ }
1622
1685
}
1623
1686
1624
1687
/// An iterator that rejects elements while `predicate` returns `true`.
0 commit comments