Skip to content

Instantly share code, notes, and snippets.

@anonymouss
Created May 21, 2019 04:43
Show Gist options
  • Save anonymouss/2ead3dadd60dd3cf04783ffc7405301e to your computer and use it in GitHub Desktop.
Save anonymouss/2ead3dadd60dd3cf04783ffc7405301e to your computer and use it in GitHub Desktop.
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
struct Cacher<T>
where T: Fn(u32) -> u32
{
calculate: T,
map: HashMap<u32, u32>,
}
impl<T> Cacher<T>
where T: Fn(u32) -> u32
{
fn new(calculate: T) -> Cacher<T> {
Cacher {
calculate,
map: HashMap::new(),
}
}
fn value(&mut self, v: u32) -> u32 {
match self.map.get(&v) {
Some(value) => return *value,
None => {
let vv = (self.calculate)(v);
self.map.insert(v, vv);
vv
},
}
}
}
fn main() {
let calc_pow_with_delay = |x| {
thread::sleep(Duration::from_secs(2));
x * x
};
println!(">>> start");
let mut cacher = Cacher::new(calc_pow_with_delay);
println!("first call with 1: {}", cacher.value(1)); // not cached yet, delay 2s
println!("second call with 1: {}", cacher.value(1)); // return cached value
println!("first call with 2: {}", cacher.value(2)); // not cached yet, delay 2s
println!("second call with 2: {}", cacher.value(2)); // return cached value
println!(">>> end");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment