Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Created February 27, 2024 14:15
Show Gist options
  • Save MikuroXina/5807e3bd1a440b56b31c26a03aeef839 to your computer and use it in GitHub Desktop.
Save MikuroXina/5807e3bd1a440b56b31c26a03aeef839 to your computer and use it in GitHub Desktop.
Items counter with Rust
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Counter<T: Eq + std::hash::Hash> {
counts: std::collections::HashMap<T, usize>,
}
impl<T, Q> std::ops::Index<&Q> for Counter<T>
where
T: Eq + std::hash::Hash + std::borrow::Borrow<Q>,
Q: Eq + std::hash::Hash + ?Sized,
{
type Output = usize;
fn index(&self, key: &Q) -> &usize {
self.counts.get(key).unwrap_or(&0)
}
}
impl<T: Eq + std::hash::Hash> Counter<T> {
pub fn new(items: impl IntoIterator<Item = T>) -> Self {
let mut counts = std::collections::HashMap::new();
for item in items {
*counts.entry(item).or_insert(0) += 1;
}
Self { counts }
}
#[inline]
pub fn get<Q>(&self, key: &Q) -> usize
where
T: std::borrow::Borrow<Q>,
Q: Eq + std::hash::Hash + ?Sized,
{
self[key]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment