Guest User

Untitled

a guest
Jan 16th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.63 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::hash::Hash;
  3.  
  4. pub struct Cache<K, V, F> {
  5. cache: HashMap<K, V>,
  6. compute: F,
  7. }
  8.  
  9. impl<'a, K, V, F> Cache<K, V, F>
  10. where
  11. K: Hash + Eq + Copy,
  12. V: Copy,
  13. F: FnMut(K, Box<dyn FnMut(K) -> V + 'a>) -> V,
  14. {
  15. pub fn new(compute: F) -> Cache<K, V, F> {
  16. let cache = HashMap::new();
  17. Cache { cache, compute }
  18. }
  19.  
  20. pub fn get(&'a mut self, key: K) -> V {
  21. if let Some(&value) = self.cache.get(&key) {
  22. return value;
  23. }
  24.  
  25. let value = (self.compute)(key, Box::new(|k: K| self.get(k)));
  26. self.cache.insert(key, value);
  27. value
  28. }
  29. }
Add Comment
Please, Sign In to add comment