Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FEAT: implement .all_unique() #241

Merged
merged 1 commit into from Jan 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/lib.rs
Expand Up @@ -35,6 +35,8 @@ use std::iter::{IntoIterator};
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_std")]
use std::fmt::Write;
Expand Down Expand Up @@ -1227,6 +1229,30 @@ pub trait Itertools : Iterator {
self.dedup().nth(1).is_none()
}

/// 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 @@ -108,6 +108,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