Skip to content

Commit d118414

Browse files
committed
Add Itertools.contains
1 parent 573743a commit d118414

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/lib.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1608,6 +1608,53 @@ pub trait Itertools : Iterator {
16081608
None
16091609
}
16101610

1611+
/// Check whether the iterator contains an item.
1612+
///
1613+
/// If the iterator contains the item prior to its end,
1614+
/// this method will short-circuit and only partially
1615+
/// exhaust the iterator.
1616+
///
1617+
/// ```
1618+
/// use itertools::Itertools;
1619+
///
1620+
/// let data = vec![
1621+
/// "foo".to_owned(),
1622+
/// "bar".to_owned(),
1623+
/// "baz".to_owned(),
1624+
/// ];
1625+
/// // this could get expensive:
1626+
/// assert!(data.contains(&"foo".to_owned()));
1627+
/// // this, less so:
1628+
/// assert!(data.iter().contains("foo"));
1629+
///
1630+
/// // now the not-as-motivating tests involving Copy data:
1631+
///
1632+
/// let data = vec![4usize, 5, 1, 3, 0, 2];
1633+
/// assert!(data.iter().contains(&4));
1634+
/// assert!(!data.iter().contains(&6));
1635+
/// for x in (0..50) {
1636+
/// assert_eq!(data.contains(&x), data.iter().contains(&x));
1637+
/// }
1638+
///
1639+
/// let mut it = data.iter();
1640+
/// assert!(!it.contains(&6));
1641+
/// assert_eq!(it.next(), None);
1642+
///
1643+
/// let mut it = data.iter();
1644+
/// assert!(it.contains(&3));
1645+
/// assert_eq!(it.next(), Some(&0));
1646+
///
1647+
/// let data : Option<usize> = None;
1648+
/// assert!(!data.into_iter().contains(0));
1649+
/// ```
1650+
fn contains<Q>(&mut self, query: Q) -> bool
1651+
where
1652+
Self: Sized,
1653+
Self::Item: PartialEq<Q>,
1654+
{
1655+
self.any(|x| x == query)
1656+
}
1657+
16111658
/// Check whether all elements compare equal.
16121659
///
16131660
/// Empty iterators are considered to have equal elements:

0 commit comments

Comments
 (0)