Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Itertools.contains #514

Merged
merged 9 commits into from Jan 13, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/lib.rs
Expand Up @@ -59,6 +59,7 @@ use alloc::{

pub use either::Either;

use core::borrow::Borrow;
#[cfg(feature = "use_std")]
use std::collections::HashMap;
use std::iter::{IntoIterator, once};
Expand Down Expand Up @@ -1608,6 +1609,40 @@ pub trait Itertools : Iterator {
None
}

/// Returns `true` if the given item is present in this iterator.
///
/// This method is short-circuiting. If the given item is present in this
/// iterator, this method will consume the iterator up-to-and-including
/// the item. If the given item is not present in this iterator, the
/// iterator will be exhausted.
///
/// ```
/// use itertools::Itertools;
///
/// #[derive(PartialEq, Debug)]
/// enum Enum { A, B, C, D, E, }
///
/// let mut iter = vec![Enum::A, Enum::B, Enum::C, Enum::D].into_iter();
///
/// // search `iter` for `B`
/// assert_eq!(iter.contains(&Enum::B), true);
/// // `B` was found, so the iterator now rests at the item after `B` (i.e, `C`).
/// assert_eq!(iter.next(), Some(Enum::C));
///
/// // search `iter` for `E`
/// assert_eq!(iter.contains(&Enum::E), false);
/// // `E` wasn't found, so `iter` is now exhausted
/// assert_eq!(iter.next(), None);
/// ```
fn contains<Q>(&mut self, query: &Q) -> bool
where
Self: Sized,
Self::Item: Borrow<Q>,
Q: PartialEq,
{
self.any(|x| x.borrow() == query)
}

/// Check whether all elements compare equal.
///
/// Empty iterators are considered to have equal elements:
Expand Down