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 4 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
32 changes: 32 additions & 0 deletions src/lib.rs
Expand Up @@ -1608,6 +1608,38 @@ 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, the this method will consume the iterator up-to-and-including
mmirate marked this conversation as resolved.
Show resolved Hide resolved
/// the item. If the given item is not present in this iterator, the
/// iterator will be exhausted.
///
/// ```
/// #[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