Last active
August 17, 2018 07:16
-
-
Save konn/0c71ad8db27eaa5bca02351b49dfdbd5 to your computer and use it in GitHub Desktop.
Generic Cacher without Clone
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 std::collections::hash_map::Entry; | |
use std::collections::HashMap; | |
use std::hash::Hash; | |
use std::ops::Fn; | |
struct Cacher<'a, T, A, B> | |
where | |
T: 'a + Fn(&A) -> B, | |
A: 'a, | |
B: 'a, | |
{ | |
calculation: T, | |
values: HashMap<&'a A, B>, | |
} | |
impl<'a, T, A, B> Cacher<'a, T, A, B> | |
where | |
T: Fn(&A) -> B, | |
A: Eq + Hash, | |
{ | |
fn new(calculation: T) -> Cacher<'a, T, A, B> { | |
Cacher { | |
calculation, | |
values: HashMap::new(), | |
} | |
} | |
fn value(&mut self, arg: &'a A) -> &B { | |
let f = &self.calculation; | |
match self.values.entry(arg) { | |
Entry::Occupied(v) => v.into_mut(), | |
Entry::Vacant(a) => { | |
let v = f(&a.key()); | |
a.insert(v) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment