pub struct Counter<T: Hash + Eq, N = usize> { /* private fields */ }

Implementations

Consumes this counter and returns a HashMap mapping the items to the counts.

Returns the sum of the counts.

Use len to get the number of elements in the counter and use total to get the sum of their counts.

Examples
let counter = Counter::init("abracadabra".chars());
assert_eq!(counter.total::<usize>(), 11);
assert_eq!(counter.len(), 5);

Create a new, empty Counter

Create a new Counter initialized with the given iterable.

Add the counts of the elements from the given iterable to this counter.

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);

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.

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);

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.

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.

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));

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>>

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);

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.

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.

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.

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.

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.

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);

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());

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());
🔬This is a nightly-only experimental API. (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]);

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.

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());

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();

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);

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?");

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);

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);

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);

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);

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);
🔬This is a nightly-only experimental API. (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);
🔬This is a nightly-only experimental API. (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);

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);

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");

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");
🔬This is a nightly-only experimental API. (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");

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 · source

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);
source

pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S>

🔬This is a nightly-only experimental API. (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).

source

pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S>

🔬This is a nightly-only experimental API. (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

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);
The resulting type after applying the + operator.

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);
The resulting type after applying the + operator.

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);

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);

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);
The resulting type after applying the & operator.

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);

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);
The resulting type after applying the | operator.

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);
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
The resulting type after dereferencing.
Dereferences the value.
Mutably dereferences the value.

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);
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more

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);
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more

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);
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more

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);

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);

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<_, _>>`
The returned type after indexing.

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));
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more

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);
The type of the elements being iterated over.
Which kind of iterator are we turning this into?

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);
    }
}
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more

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);
The resulting type after applying the - operator.

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);
The resulting type after applying the - operator.

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);

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);

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.