Skip to content

Commit f7345cf

Browse files
committed
Add counts_[by_]with_hasher()
1 parent ef62da0 commit f7345cf

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/lib.rs

+27-2
Original file line numberDiff line numberDiff line change
@@ -4688,7 +4688,19 @@ pub trait Itertools: Iterator {
46884688
Self: Sized,
46894689
Self::Item: Eq + Hash,
46904690
{
4691-
let mut counts = HashMap::new();
4691+
self.counts_with_hasher(RandomState::new())
4692+
}
4693+
4694+
/// Collect the items in this iterator and return a `HashMap` the same way
4695+
/// [.counts()](crate::Itertools::counts) does, but use the specified hash builder for hashing.
4696+
#[cfg(feature = "use_std")]
4697+
fn counts_with_hasher<S>(self, hash_builder: S) -> HashMap<Self::Item, usize, S>
4698+
where
4699+
Self: Sized,
4700+
Self::Item: Eq + Hash,
4701+
S: BuildHasher,
4702+
{
4703+
let mut counts = HashMap::with_hasher(hash_builder);
46924704
self.for_each(|item| *counts.entry(item).or_default() += 1);
46934705
counts
46944706
}
@@ -4733,7 +4745,20 @@ pub trait Itertools: Iterator {
47334745
K: Eq + Hash,
47344746
F: FnMut(Self::Item) -> K,
47354747
{
4736-
self.map(f).counts()
4748+
self.counts_by_with_hasher(f, RandomState::new())
4749+
}
4750+
4751+
/// Collect the items in this iterator and return a `HashMap` the same way
4752+
/// [.counts_by()](crate::Itertools::counts_by) does, but use the specified hash builder for hashing.
4753+
#[cfg(feature = "use_std")]
4754+
fn counts_by_with_hasher<K, F, S>(self, f: F, hash_builder: S) -> HashMap<K, usize, S>
4755+
where
4756+
Self: Sized,
4757+
K: Eq + Hash,
4758+
F: FnMut(Self::Item) -> K,
4759+
S: BuildHasher,
4760+
{
4761+
self.map(f).counts_with_hasher(hash_builder)
47374762
}
47384763

47394764
/// Converts an iterator of tuples into a tuple of containers.

0 commit comments

Comments
 (0)