Skip to content

Commit

Permalink
FEAT: implement .all_unique()
Browse files Browse the repository at this point in the history
  • Loading branch information
samueltardieu authored and jswrenn committed Jan 18, 2021
1 parent 4d902e3 commit ddeb9f1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/lib.rs
Expand Up @@ -66,6 +66,8 @@ use std::iter::{IntoIterator, once};
use std::cmp::Ordering;
use std::fmt;
#[cfg(feature = "use_std")]
use std::collections::HashSet;
#[cfg(feature = "use_std")]
use std::hash::Hash;
#[cfg(feature = "use_alloc")]
use std::fmt::Write;
Expand Down Expand Up @@ -1671,6 +1673,30 @@ pub trait Itertools : Iterator {
}
}

/// Check whether all elements are unique (non equal).
///
/// Empty iterators are considered to have unique elements:
///
/// ```
/// use itertools::Itertools;
///
/// let data = vec![1, 2, 3, 4, 1, 5];
/// assert!(!data.iter().all_unique());
/// assert!(data[0..4].iter().all_unique());
/// assert!(data[1..6].iter().all_unique());
///
/// let data : Option<usize> = None;
/// assert!(data.into_iter().all_unique());
/// ```
#[cfg(feature = "use_std")]
fn all_unique(&mut self) -> bool
where Self: Sized,
Self::Item: Eq + Hash
{
let mut used = HashSet::new();
self.all(move |elt| used.insert(elt))
}

/// Consume the first `n` elements from the iterator eagerly,
/// and return the same iterator again.
///
Expand Down
7 changes: 7 additions & 0 deletions tests/test_std.rs
Expand Up @@ -189,6 +189,13 @@ fn all_equal() {
}
}

#[test]
fn all_unique() {
assert!("ABCDEFGH".chars().all_unique());
assert!(!"ABCDEFGA".chars().all_unique());
assert!(::std::iter::empty::<usize>().all_unique());
}

#[test]
fn test_put_back_n() {
let xs = [0, 1, 1, 1, 2, 1, 3, 3];
Expand Down

0 comments on commit ddeb9f1

Please sign in to comment.