Skip to content

Commit 0e5dc21

Browse files
committed
Merge upstream
2 parents c5bf4a1 + 89f3a0d commit 0e5dc21

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/lib.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2844,6 +2844,30 @@ pub trait Itertools : Iterator {
28442844
{
28452845
multipeek_impl::multipeek(self)
28462846
}
2847+
2848+
/// Collect the items in this iterator and return a `HashMap` which
2849+
/// contains each item that appears in the iterator and the number
2850+
/// of times it appears.
2851+
///
2852+
/// # Examples
2853+
/// ```
2854+
/// # use itertools::Itertools;
2855+
/// let counts = [1, 1, 1, 3, 3, 5].into_iter().counts();
2856+
/// assert_eq!(counts[&1], 3);
2857+
/// assert_eq!(counts[&3], 2);
2858+
/// assert_eq!(counts[&5], 1);
2859+
/// assert_eq!(counts.get(&0), None);
2860+
/// ```
2861+
#[cfg(feature = "use_std")]
2862+
fn counts(self) -> HashMap<Self::Item, usize>
2863+
where
2864+
Self: Sized,
2865+
Self::Item: Eq + Hash,
2866+
{
2867+
let mut counts = HashMap::new();
2868+
self.for_each(|item| *counts.entry(item).or_default() += 1);
2869+
counts
2870+
}
28472871
}
28482872

28492873
impl<T: ?Sized> Itertools for T where T: Iterator { }

tests/quick.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1545,3 +1545,24 @@ quickcheck! {
15451545
assert_eq!(lookup[&0], MinMaxResult::MinMax(0, 10));
15461546
}
15471547
}
1548+
1549+
quickcheck! {
1550+
#[test]
1551+
fn counts(nums: Vec<isize>) -> TestResult {
1552+
let counts = nums.iter().counts();
1553+
for (&item, &count) in counts.iter() {
1554+
if count <= 0 {
1555+
return TestResult::failed();
1556+
}
1557+
if count != nums.iter().filter(|&x| x == item).count() {
1558+
return TestResult::failed();
1559+
}
1560+
}
1561+
for item in nums.iter() {
1562+
if !counts.contains_key(item) {
1563+
return TestResult::failed();
1564+
}
1565+
}
1566+
TestResult::passed()
1567+
}
1568+
}

0 commit comments

Comments
 (0)