daily pastebin goal
34%
SHARE
TWEET

Untitled

a guest Feb 17th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::collections::hash_map::Entry;
  2. use std::collections::HashMap;
  3.  
  4. enum CachedEntry {
  5.     SimpleString(String),
  6.     List(Vec<String>),
  7. }
  8.  
  9. struct Cache {
  10.     entries: HashMap<String, CachedEntry>,
  11. }
  12.  
  13. impl Cache {
  14.     fn new() -> Self {
  15.         Cache {
  16.             entries: HashMap::new(),
  17.         }
  18.     }
  19.  
  20.     fn get(&mut self, key: &str) -> Result<&String, ()> {
  21.         match self.entries.entry(key.to_owned()) {
  22.             Entry::Occupied(e) => match e.into_mut() {
  23.                 CachedEntry::SimpleString(ss) => {
  24.                     Ok(ss)
  25.                 },
  26.                 _ => Err(()), /* Not a string */
  27.             },
  28.             Entry::Vacant(v) => {
  29.                 /* Contrived string (real code does lookup) */
  30.                 let new = format!("{}", key);
  31.  
  32.                 let entry = CachedEntry::SimpleString(new);
  33.                 match v.insert(entry) {
  34.                     CachedEntry::SimpleString(str_ref) => Ok(str_ref),
  35.                     _ => unreachable!(),
  36.                 }
  37.             }
  38.         }
  39.     }
  40.  
  41.     fn list(&mut self, key: &str) -> Result<&Vec<String>, ()> {
  42.         match self.entries.entry(key.to_owned()) {
  43.             Entry::Occupied(e) => match e.into_mut() {
  44.                 CachedEntry::List(l) => {
  45.                     Ok(l)
  46.                 },
  47.                 _ => Err(()), /* Not a list */
  48.             },
  49.             Entry::Vacant(v) => {
  50.                 /* Contrived list (real code does lookup) */
  51.                 let new_vec = vec![format!("{}", key)];
  52.  
  53.                 let entry = CachedEntry::List(new_vec);
  54.                 if let CachedEntry::List(vec_ref) = v.insert(entry) {
  55.                     return Ok(vec_ref);
  56.                 } else {
  57.                     unreachable!();
  58.                 }
  59.             }
  60.         }
  61.     }
  62. }
  63.  
  64. fn main() {
  65.     let mut cache = Cache::new();
  66.  
  67.     for i in 0..4 {
  68.         for _ in 0..2 {
  69.             let s1 = cache.get(&format!("string:{}", i));
  70.             println!("{:?}", s1);
  71.             let l1 = cache.list(&format!("list:{}", i));
  72.             println!("{:?}", l1);
  73.         }
  74.     }
  75. }
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