Skip to content

Commit c7a3f6b

Browse files
authored
Merge pull request #23 from MarinPostma/peekable-methods
Peekable methods
2 parents b176087 + 37a07f4 commit c7a3f6b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/lib.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2148,6 +2148,27 @@ where
21482148

21492149
Ok(self.next.as_ref())
21502150
}
2151+
2152+
/// Consume and return the next value of this iterator if a condition is true.
2153+
///
2154+
/// If func returns true for the next value of this iterator, consume and return it. Otherwise, return None.
2155+
#[inline]
2156+
pub fn next_if(&mut self, f: impl Fn(&I::Item) -> bool) -> Result<Option<I::Item>, I::Error> {
2157+
match self.peek()? {
2158+
Some(item) if f(item) => self.next(),
2159+
_ => Ok(None),
2160+
}
2161+
}
2162+
2163+
/// Consume and return the next item if it is equal to `expected`.
2164+
#[inline]
2165+
pub fn next_if_eq<T>(&mut self, expected: &T) -> Result<Option<I::Item>, I::Error>
2166+
where
2167+
T: ?Sized,
2168+
I::Item: PartialEq<T>,
2169+
{
2170+
self.next_if(|found| found == expected)
2171+
}
21512172
}
21522173

21532174
impl<I> FallibleIterator for Peekable<I>

0 commit comments

Comments
 (0)