Guest User

Untitled

a guest
May 27th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::hash::Hash;
  3.  
  4. pub struct Cacher<T, VIn, VOut>
  5. where T: Fn(&VIn) -> VOut,
  6. VIn: Eq + Hash
  7. {
  8. calculation: T,
  9. values: HashMap<VIn, VOut>
  10. }
  11.  
  12. impl<T, VIn, VOut> Cacher<T, VIn, VOut>
  13. where T: Fn(&VIn) -> VOut,
  14. VIn: Eq + Hash
  15. {
  16. pub fn new(calculation: T) -> Cacher<T, VIn, VOut> {
  17. Cacher {
  18. calculation,
  19. values: HashMap::new(),
  20. }
  21. }
  22.  
  23. pub fn value(&mut self, arg: VIn) -> &VOut {
  24. if self.values.contains_key(&arg) {
  25. self.values.get(&arg).unwrap()
  26. } else {
  27. let result = (self.calculation)(&arg);
  28. let entry = self.values.entry(arg).or_insert_with(|| result);
  29. &*entry
  30. }
  31. }
  32. }
  33.  
  34. fn main() {
  35. let mut cacher = Cacher::new(|a| *a + 1);
  36. println!("{}", cacher.value(3));
  37. println!("{}", cacher.value(4));
  38. println!("{}", cacher.value(3));
  39. }
Add Comment
Please, Sign In to add comment