Implementations
sourceimpl<T, N> Counter<T, N>where
T: Hash + Eq,
impl<T, N> Counter<T, N>where
T: Hash + Eq,
sourceimpl<T, N> Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero + One,
impl<T, N> Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero + One,
sourcepub fn init<I>(iterable: I) -> Counter<T, N>where
I: IntoIterator<Item = T>,
pub fn init<I>(iterable: I) -> Counter<T, N>where
I: IntoIterator<Item = T>,
Create a new Counter
initialized with the given iterable.
sourcepub fn update<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
pub fn update<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
Add the counts of the elements from the given iterable to this counter.
sourceimpl<T, N> Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
impl<T, N> Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
sourcepub fn subtract<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
pub fn subtract<I>(&mut self, iterable: I)where
I: IntoIterator<Item = T>,
Remove the counts of the elements from the given iterable to this counter.
Non-positive counts are automatically removed.
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter.subtract("abba".chars());
let expect = [('c', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
sourceimpl<T, N> Counter<T, N>where
T: Hash + Eq + Clone,
N: Clone + Ord,
impl<T, N> Counter<T, N>where
T: Hash + Eq + Clone,
N: Clone + Ord,
sourcepub fn most_common(&self) -> Vec<(T, N)>
pub fn most_common(&self) -> Vec<(T, N)>
Create a vector of (elem, frequency)
pairs, sorted most to least common.
let mc = "pappaopolo".chars().collect::<Counter<_>>().most_common();
let expected = vec![('p', 4), ('o', 3), ('a', 2), ('l', 1)];
assert_eq!(mc, expected);
Note that the ordering of duplicates is unstable.
sourcepub fn most_common_tiebreaker<F>(&self, tiebreaker: F) -> Vec<(T, N)>where
F: FnMut(&T, &T) -> Ordering,
pub fn most_common_tiebreaker<F>(&self, tiebreaker: F) -> Vec<(T, N)>where
F: FnMut(&T, &T) -> Ordering,
Create a vector of (elem, frequency)
pairs, sorted most to least common.
In the event that two keys have an equal frequency, use the supplied ordering function to further arrange the results.
For example, we can sort reverse-alphabetically:
let counter = "eaddbbccc".chars().collect::<Counter<_>>();
let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a));
let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)];
assert_eq!(by_common, expected);
sourceimpl<T, N> Counter<T, N>where
T: Hash + Eq + Clone + Ord,
N: Clone + Ord,
impl<T, N> Counter<T, N>where
T: Hash + Eq + Clone + Ord,
N: Clone + Ord,
sourcepub fn most_common_ordered(&self) -> Vec<(T, N)>
pub fn most_common_ordered(&self) -> Vec<(T, N)>
Create a vector of (elem, frequency)
pairs, sorted most to least common.
In the event that two keys have an equal frequency, use the natural ordering of the keys to further sort the results.
Examples
let mc = "abracadabra".chars().collect::<Counter<_>>().most_common_ordered();
let expect = vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)];
assert_eq!(mc, expect);
Time complexity
O(n * log n), where n is the number of items in the counter. If all you want is
the top k items and k < n then it can be more efficient to use
k_most_common_ordered
.
sourcepub fn k_most_common_ordered(&self, k: usize) -> Vec<(T, N)>
pub fn k_most_common_ordered(&self, k: usize) -> Vec<(T, N)>
Returns the k
most common items in decreasing order of their counts.
The returned vector is the same as would be obtained by calling most_common_ordered
and
then truncating the result to length k
. In particular, items with the same count are
sorted in increasing order of their keys. Further, if k
is greater than the length of
the counter then the returned vector will have length equal to that of the counter, not
k
.
Examples
let counter: Counter<_> = "abracadabra".chars().collect();
let top3 = counter.k_most_common_ordered(3);
assert_eq!(top3, vec![('a', 5), ('b', 2), ('r', 2)]);
Time complexity
This method can be much more efficient than most_common_ordered
when k is much
smaller than the length of the counter n. When k = 1 the algorithm is equivalent
to finding the minimum (or maximum) of n items, which requires n - 1 comparisons. For
a fixed value of k > 1, the number of comparisons scales with n as n + O(log n)
and the number of swaps scales as O(log n). As k approaches n, this algorithm
approaches a heapsort of the n items, which has complexity O(n * log n).
For values of k close to n the sorting algorithm used by most_common_ordered
will
generally be faster than the heapsort used by this method by a small constant factor.
Exactly where the crossover point occurs will depend on several factors. For small k
choose this method. If k is a substantial fraction of n, it may be that
most_common_ordered
is faster. If performance matters in your application then it may
be worth experimenting to see which of the two methods is faster.
sourceimpl<T, N> Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + Zero,
impl<T, N> Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + Zero,
sourcepub fn is_superset(&self, other: &Self) -> bool
pub fn is_superset(&self, other: &Self) -> bool
Test whether this counter is a superset of another counter. This is true if for all elements in this counter and the other, the count in this counter is greater than or equal to the count in the other.
c.is_superset(&d);
-> c.iter().all(|(x, n)| n >= d[x]) && d.iter().all(|(x, n)| c[x] >= n)
let c = "aaabbc".chars().collect::<Counter<_>>();
let mut d = "abb".chars().collect::<Counter<_>>();
assert!(c.is_superset(&d));
d[&'e'] = 1;
assert!(!c.is_superset(&d));
sourcepub fn is_subset(&self, other: &Self) -> bool
pub fn is_subset(&self, other: &Self) -> bool
Test whether this counter is a subset of another counter. This is true if for all elements in this counter and the other, the count in this counter is less than or equal to the count in the other.
c.is_subset(&d);
-> c.iter().all(|(x, n)| n <= d[x]) && d.iter().all(|(x, n)| c[x] <= n)
let mut c = "abb".chars().collect::<Counter<_>>();
let mut d = "aaabbc".chars().collect::<Counter<_>>();
assert!(c.is_subset(&d));
c[&'e'] = 1;
assert!(!c.is_subset(&d));
Methods from Deref<Target = HashMap<T, N>>
1.0.0 · sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the map can hold without reallocating.
This number is a lower bound; the HashMap<K, V>
might be able to hold
more, but is guaranteed to be able to hold at least this many.
Examples
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);
1.0.0 · sourcepub fn keys(&self) -> Keys<'_, K, V>
pub fn keys(&self) -> Keys<'_, K, V>
An iterator visiting all keys in arbitrary order.
The iterator element type is &'a K
.
Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for key in map.keys() {
println!("{key}");
}
Performance
In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · sourcepub fn values(&self) -> Values<'_, K, V>
pub fn values(&self) -> Values<'_, K, V>
An iterator visiting all values in arbitrary order.
The iterator element type is &'a V
.
Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for val in map.values() {
println!("{val}");
}
Performance
In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.10.0 · sourcepub fn values_mut(&mut self) -> ValuesMut<'_, K, V>
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V>
An iterator visiting all values mutably in arbitrary order.
The iterator element type is &'a mut V
.
Examples
use std::collections::HashMap;
let mut map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for val in map.values_mut() {
*val = *val + 10;
}
for val in map.values() {
println!("{val}");
}
Performance
In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · sourcepub fn iter(&self) -> Iter<'_, K, V>
pub fn iter(&self) -> Iter<'_, K, V>
An iterator visiting all key-value pairs in arbitrary order.
The iterator element type is (&'a K, &'a V)
.
Examples
use std::collections::HashMap;
let map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for (key, val) in map.iter() {
println!("key: {key} val: {val}");
}
Performance
In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, K, V>
pub fn iter_mut(&mut self) -> IterMut<'_, K, V>
An iterator visiting all key-value pairs in arbitrary order,
with mutable references to the values.
The iterator element type is (&'a K, &'a mut V)
.
Examples
use std::collections::HashMap;
let mut map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
// Update all values
for (_, val) in map.iter_mut() {
*val *= 2;
}
for (key, val) in &map {
println!("key: {key} val: {val}");
}
Performance
In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the map.
Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
1.0.0 · sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the map contains no elements.
Examples
use std::collections::HashMap;
let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
1.6.0 · sourcepub fn drain(&mut self) -> Drain<'_, K, V>
pub fn drain(&mut self) -> Drain<'_, K, V>
Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
If the returned iterator is dropped before being fully consumed, it drops the remaining key-value pairs. The returned iterator keeps a mutable borrow on the map to optimize its implementation.
Examples
use std::collections::HashMap;
let mut a = HashMap::new();
a.insert(1, "a");
a.insert(2, "b");
for (k, v) in a.drain().take(1) {
assert!(k == 1 || k == 2);
assert!(v == "a" || v == "b");
}
assert!(a.is_empty());
sourcepub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>where
F: FnMut(&K, &mut V) -> bool,
🔬This is a nightly-only experimental API. (hash_drain_filter
)
pub fn drain_filter<F>(&mut self, pred: F) -> DrainFilter<'_, K, V, F>where
F: FnMut(&K, &mut V) -> bool,
hash_drain_filter
)Creates an iterator which uses a closure to determine if an element should be removed.
If the closure returns true, the element is removed from the map and yielded. If the closure returns false, or panics, the element remains in the map and will not be yielded.
Note that drain_filter
lets you mutate every value in the filter closure, regardless of
whether you choose to keep or remove it.
If the iterator is only partially consumed or not consumed at all, each of the remaining elements will still be subjected to the closure and removed and dropped if it returns true.
It is unspecified how many more elements will be subjected to the closure
if a panic occurs in the closure, or a panic occurs while dropping an element,
or if the DrainFilter
value is leaked.
Examples
Splitting a map into even and odd keys, reusing the original map:
#![feature(hash_drain_filter)]
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
let drained: HashMap<i32, i32> = map.drain_filter(|k, _v| k % 2 == 0).collect();
let mut evens = drained.keys().copied().collect::<Vec<_>>();
let mut odds = map.keys().copied().collect::<Vec<_>>();
evens.sort();
odds.sort();
assert_eq!(evens, vec![0, 2, 4, 6]);
assert_eq!(odds, vec![1, 3, 5, 7]);
1.18.0 · sourcepub fn retain<F>(&mut self, f: F)where
F: FnMut(&K, &mut V) -> bool,
pub fn retain<F>(&mut self, f: F)where
F: FnMut(&K, &mut V) -> bool,
Retains only the elements specified by the predicate.
In other words, remove all pairs (k, v)
for which f(&k, &mut v)
returns false
.
The elements are visited in unsorted (and unspecified) order.
Examples
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
map.retain(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 4);
Performance
In the current implementation, this operation takes O(capacity) time instead of O(len) because it internally visits empty buckets too.
1.0.0 · sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
Examples
use std::collections::HashMap;
let mut a = HashMap::new();
a.insert(1, "a");
a.clear();
assert!(a.is_empty());
1.9.0 · sourcepub fn hasher(&self) -> &S
pub fn hasher(&self) -> &S
Returns a reference to the map’s BuildHasher
.
Examples
use std::collections::HashMap;
use std::collections::hash_map::RandomState;
let hasher = RandomState::new();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &RandomState = map.hasher();
1.0.0 · sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more elements to be inserted
in the HashMap
. The collection may reserve more space to speculatively
avoid frequent reallocations. After calling reserve
,
capacity will be greater than or equal to self.len() + additional
.
Does nothing if capacity is already sufficient.
Panics
Panics if the new allocation size overflows usize
.
Examples
use std::collections::HashMap;
let mut map: HashMap<&str, i32> = HashMap::new();
map.reserve(10);
1.57.0 · sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional
more elements to be inserted
in the HashMap
. The collection may reserve more space to speculatively
avoid frequent reallocations. After calling reserve
,
capacity will be greater than or equal to self.len() + additional
if
it returns Ok(())
.
Does nothing if capacity is already sufficient.
Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use std::collections::HashMap;
let mut map: HashMap<&str, isize> = HashMap::new();
map.try_reserve(10).expect("why is the test harness OOMing on a handful of bytes?");
1.0.0 · sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the map as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
Examples
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to_fit();
assert!(map.capacity() >= 2);
1.56.0 · sourcepub fn shrink_to(&mut self, min_capacity: usize)
pub fn shrink_to(&mut self, min_capacity: usize)
Shrinks the capacity of the map with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
If the current capacity is less than the lower limit, this is a no-op.
Examples
use std::collections::HashMap;
let mut map: HashMap<i32, i32> = HashMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to(10);
assert!(map.capacity() >= 10);
map.shrink_to(0);
assert!(map.capacity() >= 2);
1.0.0 · sourcepub fn entry(&mut self, key: K) -> Entry<'_, K, V>
pub fn entry(&mut self, key: K) -> Entry<'_, K, V>
Gets the given key’s corresponding entry in the map for in-place manipulation.
Examples
use std::collections::HashMap;
let mut letters = HashMap::new();
for ch in "a short treatise on fungi".chars() {
letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);
}
assert_eq!(letters[&'s'], 2);
assert_eq!(letters[&'t'], 3);
assert_eq!(letters[&'u'], 1);
assert_eq!(letters.get(&'y'), None);
1.0.0 · sourcepub fn get<Q>(&self, k: &Q) -> Option<&V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn get<Q>(&self, k: &Q) -> Option<&V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Returns a reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
1.40.0 · sourcepub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Returns the key-value pair corresponding to the supplied key.
The supplied key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
assert_eq!(map.get_key_value(&2), None);
sourcepub fn get_many_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N]
) -> Option<[&mut V; N]>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
🔬This is a nightly-only experimental API. (map_many_mut
)
pub fn get_many_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N]
) -> Option<[&mut V; N]>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
map_many_mut
)Attempts to get mutable references to N
values in the map at once.
Returns an array of length N
with the results of each query. For soundness, at most one
mutable reference will be returned to any value. None
will be returned if any of the
keys are duplicates or missing.
Examples
#![feature(map_many_mut)]
use std::collections::HashMap;
let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
let got = libraries.get_many_mut([
"Athenæum",
"Library of Congress",
]);
assert_eq!(
got,
Some([
&mut 1807,
&mut 1800,
]),
);
// Missing keys result in None
let got = libraries.get_many_mut([
"Athenæum",
"New York Public Library",
]);
assert_eq!(got, None);
// Duplicate keys result in None
let got = libraries.get_many_mut([
"Athenæum",
"Athenæum",
]);
assert_eq!(got, None);
sourcepub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N]
) -> Option<[&mut V; N]>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
🔬This is a nightly-only experimental API. (map_many_mut
)
pub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N]
) -> Option<[&mut V; N]>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
map_many_mut
)Attempts to get mutable references to N
values in the map at once, without validating that
the values are unique.
Returns an array of length N
with the results of each query. None
will be returned if
any of the keys are missing.
For a safe alternative see get_many_mut
.
Safety
Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.
Examples
#![feature(map_many_mut)]
use std::collections::HashMap;
let mut libraries = HashMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
let got = libraries.get_many_mut([
"Athenæum",
"Library of Congress",
]);
assert_eq!(
got,
Some([
&mut 1807,
&mut 1800,
]),
);
// Missing keys result in None
let got = libraries.get_many_mut([
"Athenæum",
"New York Public Library",
]);
assert_eq!(got, None);
1.0.0 · sourcepub fn contains_key<Q>(&self, k: &Q) -> boolwhere
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn contains_key<Q>(&self, k: &Q) -> boolwhere
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Returns true
if the map contains a value for the specified key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);
1.0.0 · sourcepub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Returns a mutable reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
if let Some(x) = map.get_mut(&1) {
*x = "b";
}
assert_eq!(map[&1], "b");
1.0.0 · sourcepub fn insert(&mut self, k: K, v: V) -> Option<V>
pub fn insert(&mut self, k: K, v: V) -> Option<V>
Inserts a key-value pair into the map.
If the map did not have this key present, None
is returned.
If the map did have this key present, the value is updated, and the old
value is returned. The key is not updated, though; this matters for
types that can be ==
without being identical. See the module-level
documentation for more.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);
map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(map[&37], "c");
sourcepub fn try_insert(
&mut self,
key: K,
value: V
) -> Result<&mut V, OccupiedError<'_, K, V>>
🔬This is a nightly-only experimental API. (map_try_insert
)
pub fn try_insert(
&mut self,
key: K,
value: V
) -> Result<&mut V, OccupiedError<'_, K, V>>
map_try_insert
)Tries to insert a key-value pair into the map, and returns a mutable reference to the value in the entry.
If the map already had this key present, nothing is updated, and an error containing the occupied entry and the value is returned.
Examples
Basic usage:
#![feature(map_try_insert)]
use std::collections::HashMap;
let mut map = HashMap::new();
assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
let err = map.try_insert(37, "b").unwrap_err();
assert_eq!(err.entry.key(), &37);
assert_eq!(err.entry.get(), &"a");
assert_eq!(err.value, "b");
1.0.0 · sourcepub fn remove<Q>(&mut self, k: &Q) -> Option<V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn remove<Q>(&mut self, k: &Q) -> Option<V>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Removes a key from the map, returning the value at the key if the key was previously in the map.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);
1.27.0 · sourcepub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Removes a key from the map, returning the stored key and value if the key was previously in the map.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.remove_entry(&1), Some((1, "a")));
assert_eq!(map.remove(&1), None);
sourcepub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S>
🔬This is a nightly-only experimental API. (hash_raw_entry
)
pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S>
hash_raw_entry
)Creates a raw entry builder for the HashMap.
Raw entries provide the lowest level of control for searching and manipulating a map. They must be manually initialized with a hash and then manually searched. After this, insertions into a vacant entry still require an owned key to be provided.
Raw entries are useful for such exotic situations as:
- Hash memoization
- Deferring the creation of an owned key until it is known to be required
- Using a search key that doesn’t work with the Borrow trait
- Using custom comparison logic without newtype wrappers
Because raw entries provide much more low-level control, it’s much easier
to put the HashMap into an inconsistent state which, while memory-safe,
will cause the map to produce seemingly random results. Higher-level and
more foolproof APIs like entry
should be preferred when possible.
In particular, the hash used to initialized the raw entry must still be consistent with the hash of the key that is ultimately stored in the entry. This is because implementations of HashMap may need to recompute hashes when resizing, at which point only the keys are available.
Raw entries give mutable access to the keys. This must not be used to modify how the key would compare or hash, as the map will not re-evaluate where the key should go, meaning the keys may become “lost” if their location does not reflect their state. For instance, if you change a key so that the map now contains keys which compare equal, search may start acting erratically, with two keys randomly masking each other. Implementations are free to assume this doesn’t happen (within the limits of memory-safety).
sourcepub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S>
🔬This is a nightly-only experimental API. (hash_raw_entry
)
pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S>
hash_raw_entry
)Creates a raw immutable entry builder for the HashMap.
Raw entries provide the lowest level of control for searching and manipulating a map. They must be manually initialized with a hash and then manually searched.
This is useful for
- Hash memoization
- Using a search key that doesn’t work with the Borrow trait
- Using custom comparison logic without newtype wrappers
Unless you are in such a situation, higher-level and more foolproof APIs like
get
should be preferred.
Immutable raw entries have very limited use; you might instead want raw_entry_mut
.
Trait Implementations
sourceimpl<T, N> Add<Counter<T, N>> for Counter<T, N>where
T: Clone + Hash + Eq,
N: AddAssign + Zero,
impl<T, N> Add<Counter<T, N>> for Counter<T, N>where
T: Clone + Hash + Eq,
N: AddAssign + Zero,
sourcefn add(self, rhs: Counter<T, N>) -> Self::Output
fn add(self, rhs: Counter<T, N>) -> Self::Output
Add two counters together.
out = c + d;
-> out[x] == c[x] + d[x]
for all x
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c + d;
let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
sourceimpl<I, T, N> Add<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: AddAssign + Zero + One,
impl<I, T, N> Add<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: AddAssign + Zero + One,
sourcefn add(self, rhs: I) -> Self::Output
fn add(self, rhs: I) -> Self::Output
Consume self
producing a Counter
like self
updated with the counts of
the elements of I
.
let counter = Counter::init("abbccc".chars());
let new_counter = counter + "aeeeee".chars();
let expected: HashMap<char, usize> = [('a', 2), ('b', 2), ('c', 3), ('e', 5)]
.iter().cloned().collect();
assert_eq!(new_counter.into_map(), expected);
sourceimpl<T, N> AddAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Zero + AddAssign,
impl<T, N> AddAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Zero + AddAssign,
sourcefn add_assign(&mut self, rhs: Self)
fn add_assign(&mut self, rhs: Self)
Add another counter to this counter.
c += d;
-> c[x] += d[x]
for all x
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c += d;
let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
sourceimpl<I, T, N> AddAssign<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: AddAssign + Zero + One,
impl<I, T, N> AddAssign<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: AddAssign + Zero + One,
sourcefn add_assign(&mut self, rhs: I)
fn add_assign(&mut self, rhs: I)
Directly add the counts of the elements of I
to self
.
let mut counter = Counter::init("abbccc".chars());
counter += "aeeeee".chars();
let expected: HashMap<char, usize> = [('a', 2), ('b', 2), ('c', 3), ('e', 5)]
.iter().cloned().collect();
assert_eq!(counter.into_map(), expected);
sourceimpl<T, N> BitAnd<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
impl<T, N> BitAnd<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
sourcefn bitand(self, rhs: Counter<T, N>) -> Self::Output
fn bitand(self, rhs: Counter<T, N>) -> Self::Output
Returns the intersection of self
and rhs
as a new Counter
.
out = c & d;
-> out[x] == min(c[x], d[x])
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c & d;
let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
sourceimpl<T, N> BitAndAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
impl<T, N> BitAndAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
sourcefn bitand_assign(&mut self, rhs: Counter<T, N>)
fn bitand_assign(&mut self, rhs: Counter<T, N>)
Updates self
with the intersection of self
and rhs
c &= d;
-> c[x] == min(c[x], d[x])
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c &= d;
let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
sourceimpl<T, N> BitOr<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
impl<T, N> BitOr<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
sourcefn bitor(self, rhs: Counter<T, N>) -> Self::Output
fn bitor(self, rhs: Counter<T, N>) -> Self::Output
Returns the union of self
and rhs
as a new Counter
.
out = c | d;
-> out[x] == max(c[x], d[x])
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c | d;
let expect = [('a', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
sourceimpl<T, N> BitOrAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
impl<T, N> BitOrAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: Ord + Zero,
sourcefn bitor_assign(&mut self, rhs: Counter<T, N>)
fn bitor_assign(&mut self, rhs: Counter<T, N>)
Updates self
with the union of self
and rhs
c |= d;
-> c[x] == max(c[x], d[x])
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c |= d;
let expect = [('a', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
sourceimpl<'a, T: 'a, N: 'a> Extend<(&'a T, &'a N)> for Counter<T, N>where
T: Hash + Eq + Clone,
N: AddAssign + Zero + Clone,
impl<'a, T: 'a, N: 'a> Extend<(&'a T, &'a N)> for Counter<T, N>where
T: Hash + Eq + Clone,
N: AddAssign + Zero + Clone,
sourcefn extend<I: IntoIterator<Item = (&'a T, &'a N)>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = (&'a T, &'a N)>>(&mut self, iter: I)
Extend a counter with (item, count)
tuples.
You can extend a Counter
with another Counter
:
let mut counter = "abbccc".chars().collect::<Counter<_>>();
let another = "bccddd".chars().collect::<Counter<_>>();
counter.extend(&another);
let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter()
.cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
sourcefn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)sourcefn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)sourceimpl<T, N> Extend<(T, N)> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero,
impl<T, N> Extend<(T, N)> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero,
sourcefn extend<I: IntoIterator<Item = (T, N)>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = (T, N)>>(&mut self, iter: I)
Extend a counter with (item, count)
tuples.
The counts of duplicate items are summed.
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter.extend([('a', 1), ('b', 2), ('c', 3), ('a', 4)].iter().cloned());
let expect = [('a', 6), ('b', 4), ('c', 6)].iter()
.cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
sourcefn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)sourcefn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)sourceimpl<T, N> Extend<T> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero + One,
impl<T, N> Extend<T> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero + One,
sourcefn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)
Extend a Counter
with an iterator of items.
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter.extend("bccddd".chars());
let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
sourcefn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)sourcefn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)sourceimpl<T, N> FromIterator<(T, N)> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero,
impl<T, N> FromIterator<(T, N)> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero,
sourcefn from_iter<I: IntoIterator<Item = (T, N)>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = (T, N)>>(iter: I) -> Self
Creates a counter from (item, count)
tuples.
The counts of duplicate items are summed.
let counter = [('a', 1), ('b', 2), ('c', 3), ('a', 4)].iter()
.cloned().collect::<Counter<_>>();
let expect = [('a', 5), ('b', 2), ('c', 3)].iter()
.cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
sourceimpl<T, N> FromIterator<T> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero + One,
impl<T, N> FromIterator<T> for Counter<T, N>where
T: Hash + Eq,
N: AddAssign + Zero + One,
sourcefn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self
Produce a Counter
from an iterator of items. This is called automatically
by Iterator::collect()
.
let counter = "abbccc".chars().collect::<Counter<_>>();
let expect = [('a', 1), ('b', 2), ('c', 3)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(counter.into_map(), expect);
sourceimpl<T, Q, N> Index<&Q> for Counter<T, N>where
T: Hash + Eq + Borrow<Q>,
Q: Hash + Eq,
N: Zero,
impl<T, Q, N> Index<&Q> for Counter<T, N>where
T: Hash + Eq + Borrow<Q>,
Q: Hash + Eq,
N: Zero,
sourcefn index(&self, key: &Q) -> &N
fn index(&self, key: &Q) -> &N
Index in immutable contexts.
Returns a reference to a zero
value for missing keys.
let counter = Counter::<_>::init("aabbcc".chars());
assert_eq!(counter[&'a'], 2);
assert_eq!(counter[&'b'], 2);
assert_eq!(counter[&'c'], 2);
assert_eq!(counter[&'d'], 0);
Note that the zero
is a struct field but not one of the values of the inner
HashMap
. This method does not modify any existing value.
let counter = Counter::<_>::init("".chars());
assert_eq!(counter[&'a'], 0);
assert_eq!(counter.get(&'a'), None); // as `Deref<Target = HashMap<_, _>>`
type Output = N
type Output = N
sourceimpl<T, Q, N> IndexMut<&Q> for Counter<T, N>where
T: Hash + Eq + Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = T>,
N: Zero,
impl<T, Q, N> IndexMut<&Q> for Counter<T, N>where
T: Hash + Eq + Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = T>,
N: Zero,
sourcefn index_mut(&mut self, key: &Q) -> &mut N
fn index_mut(&mut self, key: &Q) -> &mut N
Index in mutable contexts.
If the given key is not present, creates a new entry and initializes it with a zero
value.
let mut counter = Counter::<_>::init("aabbcc".chars());
counter[&'c'] += 1;
counter[&'d'] += 1;
assert_eq!(counter[&'c'], 3);
assert_eq!(counter[&'d'], 1);
Unlike Index::index
, the returned mutable reference to the zero
is actually one of the
values of the inner HashMap
.
let mut counter = Counter::<_>::init("".chars());
assert_eq!(counter.get(&'a'), None); // as `Deref<Target = HashMap<_, _>>`
let _ = &mut counter[&'a'];
assert_eq!(counter.get(&'a'), Some(&0));
sourceimpl<'a, T, N> IntoIterator for &'a Counter<T, N>where
T: Hash + Eq,
impl<'a, T, N> IntoIterator for &'a Counter<T, N>where
T: Hash + Eq,
sourceimpl<'a, T, N> IntoIterator for &'a mut Counter<T, N>where
T: Hash + Eq,
impl<'a, T, N> IntoIterator for &'a mut Counter<T, N>where
T: Hash + Eq,
sourcefn into_iter(self) -> Self::IntoIter
fn into_iter(self) -> Self::IntoIter
Creates an iterator that provides mutable references to the counts, but keeps the keys immutable.
Examples
let mut counter: Counter<_> = "aaab".chars().collect();
for (item, count) in &mut counter {
if *item == 'a' {
// 'a' is so great it counts as 2
*count *= 2;
}
}
assert_eq!(counter[&'a'], 6);
assert_eq!(counter[&'b'], 1);
sourceimpl<T, N> IntoIterator for Counter<T, N>where
T: Hash + Eq,
impl<T, N> IntoIterator for Counter<T, N>where
T: Hash + Eq,
sourcefn into_iter(self) -> Self::IntoIter
fn into_iter(self) -> Self::IntoIter
Consumes the Counter
to produce an iterator that owns the values it returns.
Examples
let counter: Counter<_> = "aaab".chars().collect();
let vec: Vec<_> = counter.into_iter().collect();
for (item, count) in &vec {
if item == &'a' {
assert_eq!(count, &3);
}
if item == &'b' {
assert_eq!(count, &1);
}
}
sourceimpl<T: PartialEq + Hash + Eq, N: PartialEq> PartialEq<Counter<T, N>> for Counter<T, N>
impl<T: PartialEq + Hash + Eq, N: PartialEq> PartialEq<Counter<T, N>> for Counter<T, N>
sourceimpl<T, N> Sub<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
impl<T, N> Sub<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
sourcefn sub(self, rhs: Counter<T, N>) -> Self::Output
fn sub(self, rhs: Counter<T, N>) -> Self::Output
Subtract (keeping only positive values).
out = c - d;
-> out[x] == c[x] - d[x]
for all x
,
keeping only items with a value greater than N::zero()
.
let c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
let e = c - d;
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
sourceimpl<I, T, N> Sub<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
impl<I, T, N> Sub<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
sourcefn sub(self, rhs: I) -> Self::Output
fn sub(self, rhs: I) -> Self::Output
Consume self
producing a Counter
like self
with the counts of the
elements of I
subtracted, keeping only positive values.
let c = "aaab".chars().collect::<Counter<_>>();
let e = c - "abb".chars();
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(e.into_map(), expect);
sourceimpl<T, N> SubAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
impl<T, N> SubAssign<Counter<T, N>> for Counter<T, N>where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
sourcefn sub_assign(&mut self, rhs: Self)
fn sub_assign(&mut self, rhs: Self)
Subtract (keeping only positive values).
c -= d;
-> c[x] -= d[x]
for all x
,
keeping only items with a value greater than N::zero()
.
let mut c = "aaab".chars().collect::<Counter<_>>();
let d = "abb".chars().collect::<Counter<_>>();
c -= d;
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);
sourceimpl<I, T, N> SubAssign<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
impl<I, T, N> SubAssign<I> for Counter<T, N>where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
sourcefn sub_assign(&mut self, rhs: I)
fn sub_assign(&mut self, rhs: I)
Directly subtract the counts of the elements of I
from self
,
keeping only items with a value greater than N::zero()
.
let mut c = "aaab".chars().collect::<Counter<_>>();
c -= "abb".chars();
let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(c.into_map(), expect);