Skip to content

Commit

Permalink
Merge #514
Browse files Browse the repository at this point in the history
514: Add Itertools.contains r=jswrenn a=mmirate

This is an extremely trivial shorthand for the code-pattern suggested by the docs for [slice::contains](https://doc.rust-lang.org/std/primitive.slice.html#method.contains) in the case when one has a slice of owned data to be queried using borrowed data.

Co-authored-by: Milo Mirate <mmirate@gmx.com>
Co-authored-by: Milo Mirate <mmirate@users.noreply.github.com>
  • Loading branch information
3 people committed Jan 13, 2021
2 parents 573743a + 6a8a6c1 commit cc46647
Showing 1 changed file with 35 additions and 0 deletions.
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

0 comments on commit cc46647

Please sign in to comment.