Created
January 29, 2023 13:32
-
-
Save omer-biz/3cd931415ab43799310b62b22db2c872 to your computer and use it in GitHub Desktop.
A simple cacher implemented in Rust. Calculates and stores from a closure for future use. It uses HashMap to the store the data.
This file contains hidden or 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 std::collections::HashMap; | |
use std::hash::Hash; | |
use std::thread; | |
use std::time::Duration; | |
struct Cacher<K, V, F> { | |
calculator: F, | |
value: HashMap<K, V>, | |
} | |
impl<'a, F, V, K> Cacher<K, V, F> | |
where | |
F: Fn(&K) -> V, | |
K: Eq + Hash, | |
{ | |
fn new(calculator: F) -> Cacher<K, V, F> { | |
Cacher { | |
calculator, | |
value: HashMap::new(), | |
} | |
} | |
fn value(&'a mut self, key: K) -> &'a V { | |
self.value.entry(key).or_insert_with_key(|key| (self.calculator)(&key)) | |
} | |
} | |
fn main() { | |
let mut i32_str_cacher = Cacher::new(|num: &i32| { | |
println!("doing some heavy lifting..."); | |
thread::sleep(Duration::from_secs(2)); | |
format!("hello from i32 str cacher: {}", num + 1) | |
}); | |
println!("val: {}", i32_str_cacher.value(1)); | |
println!("val: {}", i32_str_cacher.value(1)); | |
println!("val: {}", i32_str_cacher.value(2)); | |
println!("val: {}", i32_str_cacher.value(2)); | |
println!("val: {}", i32_str_cacher.value(1)); | |
let mut str_str_cacher = Cacher::new(|name: &String| { | |
println!("doing some heavy lifting..."); | |
thread::sleep(Duration::from_secs(2)); | |
format!("hello from str str cacher: {}", name) | |
}); | |
println!("val: {}", str_str_cacher.value("how".to_string())); | |
println!("val: {}", str_str_cacher.value("how".to_string())); | |
println!("val: {}", str_str_cacher.value("are".to_string())); | |
println!("val: {}", str_str_cacher.value("are".to_string())); | |
println!("val: {}", str_str_cacher.value("how".to_string())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment