Skip to content

Commit ddeb9f1

Browse files
samueltardieujswrenn
authored andcommitted
FEAT: implement .all_unique()
1 parent 4d902e3 commit ddeb9f1

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/lib.rs

+26
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ use std::iter::{IntoIterator, once};
6666
use std::cmp::Ordering;
6767
use std::fmt;
6868
#[cfg(feature = "use_std")]
69+
use std::collections::HashSet;
70+
#[cfg(feature = "use_std")]
6971
use std::hash::Hash;
7072
#[cfg(feature = "use_alloc")]
7173
use std::fmt::Write;
@@ -1671,6 +1673,30 @@ pub trait Itertools : Iterator {
16711673
}
16721674
}
16731675

1676+
/// Check whether all elements are unique (non equal).
1677+
///
1678+
/// Empty iterators are considered to have unique elements:
1679+
///
1680+
/// ```
1681+
/// use itertools::Itertools;
1682+
///
1683+
/// let data = vec![1, 2, 3, 4, 1, 5];
1684+
/// assert!(!data.iter().all_unique());
1685+
/// assert!(data[0..4].iter().all_unique());
1686+
/// assert!(data[1..6].iter().all_unique());
1687+
///
1688+
/// let data : Option<usize> = None;
1689+
/// assert!(data.into_iter().all_unique());
1690+
/// ```
1691+
#[cfg(feature = "use_std")]
1692+
fn all_unique(&mut self) -> bool
1693+
where Self: Sized,
1694+
Self::Item: Eq + Hash
1695+
{
1696+
let mut used = HashSet::new();
1697+
self.all(move |elt| used.insert(elt))
1698+
}
1699+
16741700
/// Consume the first `n` elements from the iterator eagerly,
16751701
/// and return the same iterator again.
16761702
///

tests/test_std.rs

+7
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,13 @@ fn all_equal() {
189189
}
190190
}
191191

192+
#[test]
193+
fn all_unique() {
194+
assert!("ABCDEFGH".chars().all_unique());
195+
assert!(!"ABCDEFGA".chars().all_unique());
196+
assert!(::std::iter::empty::<usize>().all_unique());
197+
}
198+
192199
#[test]
193200
fn test_put_back_n() {
194201
let xs = [0, 1, 1, 1, 2, 1, 3, 3];

0 commit comments

Comments
 (0)