pub struct Histogram<K: Hash + Eq, S: BuildHasher = DefaultHashBuilder> { /* private fields */ }Expand description
A histogram that counts occurrences of keys.
§Examples
§Add and get one by one
use histongram::Histogram;
let mut hist = Histogram::<String>::new();
hist.add_ref("a");
assert_eq!(hist.count("a"), 1);
assert_eq!(hist.count("b"), 0);§Filling from Iterators
use histongram::Histogram;
let mut hist: Histogram<String> = ["a", "a", "a"].into_iter().collect();
assert_eq!(hist.count("a"), 3);
hist.extend(["a", "b", "c"]);
assert_eq!(hist.count("a"), 4);
assert_eq!(hist.count("b"), 1);
assert_eq!(hist.count("c"), 1);§Iterating the counts
use histongram::Histogram;
let hist: Histogram<String> = ["a", "a", "a"].into_iter().collect();
// NOTE: The order is arbitrary for multiple items
for (key, cnt) in &hist {
assert_eq!(key, &"a");
assert_eq!(cnt, 3);
}
for (key, portion) in hist.iter_rel() {
assert_eq!(key, &"a");
assert_eq!(portion, 1.0);
}
// This consumes hist but gives back ownership of the keys
for (key, cnt) in hist {
assert_eq!(key, "a".to_string());
assert_eq!(cnt, 3);
}§Getting a sorted vector of occurences
This can be build by using Iterators or using Histogram::sorted_occurrences().
use std::cmp::Reverse;
use histongram::Histogram;
let hist: Histogram<String> = ["a","a","a","x","x","z","z","z","z","z"].into_iter().collect();
let mut counts: Vec<_> = hist.into_iter().collect();
counts.sort_by_key(|(_key, cnt)| Reverse(*cnt));
assert_eq!(counts, vec![
("z".to_string(), 5),
("a".to_string(), 3),
("x".to_string(), 2),
]);§Using a pre-allocated hashbrown::HashMap
use hashbrown::HashMap;
use histongram::Histogram;
let mut hist: Histogram<_> = HashMap::<String, usize>::with_capacity(100).into();
hist.add_ref("foo");
assert_eq!(hist.count("foo"), 1);Implementations§
Source§impl<K: Hash + Eq> Histogram<K, DefaultHashBuilder>
impl<K: Hash + Eq> Histogram<K, DefaultHashBuilder>
Sourcepub fn from_counts(iter: impl IntoIterator<Item = (K, usize)>) -> Self
pub fn from_counts(iter: impl IntoIterator<Item = (K, usize)>) -> Self
Collect the counts from iter into a new Histogram
This can be useful if you already counted occurences and just want to analyze it using
Histogram.
§Example
§Create from std::collections::HashMap
use std::collections::HashMap;
use histongram::Histogram;
let counts = HashMap::from([
("foo", 5),
("bar", 2),
("baz", 3),
]);
let hist = Histogram::from_counts(counts);
assert_eq!(hist.num_instances(), 10);§Create from raw counts
use histongram::Histogram;
let hist = Histogram::from_counts([
("foo", 5),
("bar", 2),
("baz", 3),
]);
assert_eq!(hist.num_instances(), 10);Source§impl<K: Hash + Eq, S: BuildHasher> Histogram<K, S>
impl<K: Hash + Eq, S: BuildHasher> Histogram<K, S>
Sourcepub const fn with_hasher(hash_builder: S) -> Self
pub const fn with_hasher(hash_builder: S) -> Self
Create a new Histogram using the given hash_builder
This allows you to use different hashing algorithms that might fit your use-case better.
Sourcepub fn num_categories(&self) -> usize
pub fn num_categories(&self) -> usize
Number of categories in the histogram
§Example
let mut hist = Histogram::new();
hist.add_owned("abc");
hist.add_owned("abc");
hist.add_owned("other");
assert_eq!(hist.num_categories(), 2);Sourcepub fn num_instances(&self) -> usize
pub fn num_instances(&self) -> usize
Total number of instances inserted so far
§Example
let mut hist = Histogram::new();
hist.add_owned("abc");
hist.add_owned("abc");
hist.add_owned("other");
assert_eq!(hist.num_instances(), 3);Sourcepub fn add_ref<'a, Q>(&mut self, val: &'a Q)
pub fn add_ref<'a, Q>(&mut self, val: &'a Q)
Add a new occurence of key to the Histogram
The value will be turned into an owned K if it is not yet present using From<&Q>. This
is useful for example if you want to construct a 'static Histogram from slices out of a
buffer (See example below). As you do not have to create new String instances if the key
is already present in the Histogram.
See also Histogram::extend()
§Examples
use histongram::Histogram;
let mut hist = Histogram::<String>::new();
// During reading the file
{
let my_local_buffer = "Hello world! Moin! Goedemiddag! Hoi! Moin!";
for word in my_local_buffer.split_whitespace() {
hist.add_ref(word);
}
}
// my_local_bufer is now dropped
// But the Histogram has owned Strings with copies of the words
assert_eq!(hist.count("Moin!"), 2);
assert_eq!(hist.count("Hoi!"), 1);Sourcepub fn add_owned(&mut self, val: K)
pub fn add_owned(&mut self, val: K)
Add a new occurrence of key where ownership of the key moves to the Histogram
This is useful for types that do not implement From<&Self> as hashbrown requires the
use of the From<T> for its API.
Sourcepub fn extend_from_owned<I: IntoIterator<Item = K>>(&mut self, iter: I)
pub fn extend_from_owned<I: IntoIterator<Item = K>>(&mut self, iter: I)
Extend this Histogram by counting owned instances of K
This is similar to Histogram::extend() but taking owned instances instead of references.
It is useful for types that are cheap to clone, such as types that implement Copy.
Sourcepub fn count<Q>(&self, key: &Q) -> usize
pub fn count<Q>(&self, key: &Q) -> usize
Get the number of times key was added to this histogram
Returns 0 for absent keys.
§Example
let mut hist = Histogram::<String>::new();
hist.add_ref("present");
assert_eq!(hist.count("present"), 1);
assert_eq!(hist.count("absent"), 0);Sourcepub fn count_rel<Q>(&self, key: &Q) -> f64
pub fn count_rel<Q>(&self, key: &Q) -> f64
Get the relative number of times key was added to this histogram
Returns 0.0 for absent keys, so also if asked for any key in an empty Histogram.
If all occurrences so far matched key count_rel will return 1.0.
§Example
let mut hist = Histogram::<String>::new();
hist.add_ref("present");
assert_eq!(hist.count_rel("present"), 1.0);
assert_eq!(hist.count_rel("absent"), 0.0);Sourcepub fn iter(&self) -> impl Iterator<Item = (&K, usize)>
pub fn iter(&self) -> impl Iterator<Item = (&K, usize)>
Iterate over all keys and their counts in self that have occurred at least once.
The order of keys is arbitrary.
Sourcepub fn iter_rel(&self) -> impl Iterator<Item = (&K, f64)>
pub fn iter_rel(&self) -> impl Iterator<Item = (&K, f64)>
Iterate over all keys which have occurred at least once, together with its relative
number of occurrences.
The order of keys is arbitrary.
Sourcepub fn sorted_occurrences(self) -> Vec<(K, usize)>
pub fn sorted_occurrences(self) -> Vec<(K, usize)>
Get a vector of keys and counts sorted descending by count.
This consumes the Histogram to avoid cloning the keys.
use histongram::Histogram;
let hist: Histogram<_> = Histogram::from_owned_iter("aaaxxzzzzz".chars());
assert_eq!(hist.sorted_occurrences(), vec![
('z', 5),
('a', 3),
('x', 2),
]);Sourcepub fn into_std_hash_map(self) -> HashMap<K, usize>
pub fn into_std_hash_map(self) -> HashMap<K, usize>
Turn this histogram into a HashMap from std
This can be useful if you do not want to use another HashMap such as
hashbrown::HashMap in your code base. Or you already have a struct containing
std::collections::HashMaps.
§Example
use std::collections::HashMap;
use histongram::Histogram;
struct MyStruct {
counts: HashMap<String, usize>,
}
let mut hist = Histogram::new();
hist.extend(["foo", "bar", "baz"]);
let ms = MyStruct { counts: hist.into_std_hash_map() };
assert_eq!(ms.counts["foo"], 1);Source§impl<K: Hash + Eq, S: BuildHasher + Default> Histogram<K, S>
impl<K: Hash + Eq, S: BuildHasher + Default> Histogram<K, S>
Sourcepub fn from_owned_iter<I>(iter: I) -> Selfwhere
I: IntoIterator<Item = K>,
pub fn from_owned_iter<I>(iter: I) -> Selfwhere
I: IntoIterator<Item = K>,
Create a new Histogram by counting owned instanes of K in iter.
This is similar to Histogram::from_iter() but taking owned values instead of references.
See also Histogram::extend_from_owned() for motivations.
Trait Implementations§
Source§impl<'de, K, S> Deserialize<'de> for Histogram<K, S>
Available on crate feature serde only.
impl<'de, K, S> Deserialize<'de> for Histogram<K, S>
serde only.Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Source§impl<'a, K, S, Q> Extend<&'a Q> for Histogram<K, S>
impl<'a, K, S, Q> Extend<&'a Q> for Histogram<K, S>
Source§fn extend<T: IntoIterator<Item = &'a Q>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = &'a Q>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)