daily pastebin goal
27%
SHARE
TWEET

Untitled

a guest Jan 16th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top