Created
December 12, 2023 12:58
-
-
Save zekroTJA/19aff9ca70645678b60d05b4da4d4a6f to your computer and use it in GitHub Desktop.
Simple Cache with hit and miss counter in Rust.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use core::hash::Hash; | |
use std::collections::HashMap; | |
pub struct Cache<K, V> { | |
m: HashMap<K, V>, | |
hits: usize, | |
misses: usize, | |
} | |
impl<K, V> Cache<K, V> { | |
pub fn new() -> Self { | |
Self { | |
m: HashMap::new(), | |
hits: 0, | |
misses: 0, | |
} | |
} | |
pub fn hits(&self) -> usize { | |
self.hits | |
} | |
pub fn misses(&self) -> usize { | |
self.misses | |
} | |
pub fn hit_rate(&self) -> f32 { | |
self.hits as f32 / (self.hits + self.misses) as f32 | |
} | |
} | |
impl<K, V> Default for Cache<K, V> { | |
fn default() -> Self { | |
Self::new() | |
} | |
} | |
impl<K, V> Cache<K, V> | |
where | |
K: Hash + Eq, | |
{ | |
pub fn insert(&mut self, k: K, v: V) -> Option<V> { | |
self.m.insert(k, v) | |
} | |
pub fn get(&mut self, k: &K) -> Option<&V> { | |
let res = self.m.get(k); | |
if res.is_some() { | |
self.hits += 1; | |
} else { | |
self.misses += 1; | |
} | |
res | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment