Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- use std::hash::Hash;
- pub struct Cacher<T, VIn, VOut>
- where T: Fn(&VIn) -> VOut,
- VIn: Eq + Hash
- {
- calculation: T,
- values: HashMap<VIn, VOut>
- }
- impl<T, VIn, VOut> Cacher<T, VIn, VOut>
- where T: Fn(&VIn) -> VOut,
- VIn: Eq + Hash
- {
- pub fn new(calculation: T) -> Cacher<T, VIn, VOut> {
- Cacher {
- calculation,
- values: HashMap::new(),
- }
- }
- pub fn value(&mut self, arg: VIn) -> &VOut {
- if self.values.contains_key(&arg) {
- self.values.get(&arg).unwrap()
- } else {
- let result = (self.calculation)(&arg);
- let entry = self.values.entry(arg).or_insert_with(|| result);
- &*entry
- }
- }
- }
- fn main() {
- let mut cacher = Cacher::new(|a| *a + 1);
- println!("{}", cacher.value(3));
- println!("{}", cacher.value(4));
- println!("{}", cacher.value(3));
- }
Add Comment
Please, Sign In to add comment