From 952e8dbfb343d0d30fe14b8d5db1c4657f08da7f Mon Sep 17 00:00:00 2001 From: Marin Postma Date: Fri, 14 May 2021 13:15:07 +0200 Subject: [PATCH 1/2] add next_if to Peekable --- src/lib.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index d95de94..ea34692 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2198,6 +2198,18 @@ 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: F) -> Result, I::Error> + where F: Fn(&I::Item) -> bool { + match self.peek()? { + Some(item) if f(item) => self.next(), + _ => Ok(None), + } + } } impl FallibleIterator for Peekable From 37a07f40df8e63f79c755cd49b6f72593dc0bf55 Mon Sep 17 00:00:00 2001 From: Marin Postma Date: Fri, 14 May 2021 13:20:49 +0200 Subject: [PATCH 2/2] add next_if_eq method to Peekable --- src/lib.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index ea34692..fac6b8c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2203,13 +2203,22 @@ where /// /// 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: F) -> Result, I::Error> - where F: Fn(&I::Item) -> bool { + pub fn next_if(&mut self, f: impl Fn(&I::Item) -> bool) -> Result, 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(&mut self, expected: &T) -> Result, I::Error> + where + T: ?Sized, + I::Item: PartialEq, + { + self.next_if(|found| found == expected) + } } impl FallibleIterator for Peekable