Skip to content

Commit

Permalink
Merge pull request #23 from MarinPostma/peekable-methods
Browse files Browse the repository at this point in the history
Peekable methods
  • Loading branch information
dpc authored May 13, 2022
2 parents b176087 + 37a07f4 commit c7a3f6b
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2148,6 +2148,27 @@ where

Ok(self.next.as_ref())
}

/// Consume and return the next value of this iterator if a condition is true.
///
/// If func returns true for the next value of this iterator, consume and return it. Otherwise, return None.
#[inline]
pub fn next_if(&mut self, f: impl Fn(&I::Item) -> bool) -> Result<Option<I::Item>, I::Error> {
match self.peek()? {
Some(item) if f(item) => self.next(),
_ => Ok(None),
}
}

/// Consume and return the next item if it is equal to `expected`.
#[inline]
pub fn next_if_eq<T>(&mut self, expected: &T) -> Result<Option<I::Item>, I::Error>
where
T: ?Sized,
I::Item: PartialEq<T>,
{
self.next_if(|found| found == expected)
}
}

impl<I> FallibleIterator for Peekable<I>
Expand Down

0 comments on commit c7a3f6b

Please sign in to comment.