Skip to content

Commit cc46647

Browse files
bors[bot]mmirate
andauthored
Merge #514
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 <[email protected]> Co-authored-by: Milo Mirate <[email protected]>
2 parents 573743a + 6a8a6c1 commit cc46647

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/lib.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ use alloc::{
5959

6060
pub use either::Either;
6161

62+
use core::borrow::Borrow;
6263
#[cfg(feature = "use_std")]
6364
use std::collections::HashMap;
6465
use std::iter::{IntoIterator, once};
@@ -1608,6 +1609,40 @@ pub trait Itertools : Iterator {
16081609
None
16091610
}
16101611

1612+
/// Returns `true` if the given item is present in this iterator.
1613+
///
1614+
/// This method is short-circuiting. If the given item is present in this
1615+
/// iterator, this method will consume the iterator up-to-and-including
1616+
/// the item. If the given item is not present in this iterator, the
1617+
/// iterator will be exhausted.
1618+
///
1619+
/// ```
1620+
/// use itertools::Itertools;
1621+
///
1622+
/// #[derive(PartialEq, Debug)]
1623+
/// enum Enum { A, B, C, D, E, }
1624+
///
1625+
/// let mut iter = vec![Enum::A, Enum::B, Enum::C, Enum::D].into_iter();
1626+
///
1627+
/// // search `iter` for `B`
1628+
/// assert_eq!(iter.contains(&Enum::B), true);
1629+
/// // `B` was found, so the iterator now rests at the item after `B` (i.e, `C`).
1630+
/// assert_eq!(iter.next(), Some(Enum::C));
1631+
///
1632+
/// // search `iter` for `E`
1633+
/// assert_eq!(iter.contains(&Enum::E), false);
1634+
/// // `E` wasn't found, so `iter` is now exhausted
1635+
/// assert_eq!(iter.next(), None);
1636+
/// ```
1637+
fn contains<Q>(&mut self, query: &Q) -> bool
1638+
where
1639+
Self: Sized,
1640+
Self::Item: Borrow<Q>,
1641+
Q: PartialEq,
1642+
{
1643+
self.any(|x| x.borrow() == query)
1644+
}
1645+
16111646
/// Check whether all elements compare equal.
16121647
///
16131648
/// Empty iterators are considered to have equal elements:

0 commit comments

Comments
 (0)