Created
May 21, 2019 04:43
-
-
Save anonymouss/2ead3dadd60dd3cf04783ffc7405301e to your computer and use it in GitHub Desktop.
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::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