Skip to content

Commit 7145949

Browse files
author
philipp
committed
Add all_equal
1 parent cdd0c1e commit 7145949

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/lib.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -997,6 +997,33 @@ pub trait Itertools : Iterator {
997997
None
998998
}
999999

1000+
/// Check whether all elements compare equal.
1001+
///
1002+
/// Empty iterators are considered to have equal elements:
1003+
///
1004+
/// ```
1005+
/// use itertools::Itertools;
1006+
///
1007+
/// let data = vec![1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5];
1008+
/// assert!(!data.iter().all_equal());
1009+
/// assert!(data[0..3].iter().all_equal());
1010+
/// assert!(data[3..5].iter().all_equal());
1011+
/// assert!(data[5..8].iter().all_equal());
1012+
///
1013+
/// let data : Option<usize> = None;
1014+
/// assert!(data.into_iter().all_equal());
1015+
/// ```
1016+
fn all_equal(&mut self) -> bool
1017+
where Self: Sized,
1018+
Self::Item: PartialEq,
1019+
{
1020+
if let Some(first) = self.next() {
1021+
self.all(|x| x==first)
1022+
} else {
1023+
true
1024+
}
1025+
}
1026+
10001027
/// Consume the first `n` elements from the iterator eagerly,
10011028
/// and return the same iterator again.
10021029
///

tests/tests.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,15 @@ fn dedup() {
185185
assert_eq!(&xs_d, &ys);
186186
}
187187

188+
#[test]
189+
fn all_equal() {
190+
assert!(!"AABBCCC".chars().all_equal());
191+
assert!("AAAAAAA".chars().all_equal());
192+
for (_key, mut sub) in &"AABBCCC".chars().group_by(|&x| x) {
193+
assert!(sub.all_equal());
194+
}
195+
}
196+
188197
#[test]
189198
fn unique_by() {
190199
let xs = ["aaa", "bbbbb", "aa", "ccc", "bbbb", "aaaaa", "cccc"];

0 commit comments

Comments
 (0)