Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::hash_map::Entry;
- use std::collections::HashMap;
- enum CachedEntry {
- SimpleString(String),
- List(Vec<String>),
- }
- struct Cache {
- entries: HashMap<String, CachedEntry>,
- }
- impl Cache {
- fn new() -> Self {
- Cache {
- entries: HashMap::new(),
- }
- }
- fn get(&mut self, key: &str) -> Result<&String, ()> {
- match self.entries.entry(key.to_owned()) {
- Entry::Occupied(e) => match e.into_mut() {
- CachedEntry::SimpleString(ss) => {
- Ok(ss)
- },
- _ => Err(()), /* Not a string */
- },
- Entry::Vacant(v) => {
- /* Contrived string (real code does lookup) */
- let new = format!("{}", key);
- let entry = CachedEntry::SimpleString(new);
- match v.insert(entry) {
- CachedEntry::SimpleString(str_ref) => Ok(str_ref),
- _ => unreachable!(),
- }
- }
- }
- }
- fn list(&mut self, key: &str) -> Result<&Vec<String>, ()> {
- match self.entries.entry(key.to_owned()) {
- Entry::Occupied(e) => match e.into_mut() {
- CachedEntry::List(l) => {
- Ok(l)
- },
- _ => Err(()), /* Not a list */
- },
- Entry::Vacant(v) => {
- /* Contrived list (real code does lookup) */
- let new_vec = vec![format!("{}", key)];
- let entry = CachedEntry::List(new_vec);
- if let CachedEntry::List(vec_ref) = v.insert(entry) {
- return Ok(vec_ref);
- } else {
- unreachable!();
- }
- }
- }
- }
- }
- fn main() {
- let mut cache = Cache::new();
- for i in 0..4 {
- for _ in 0..2 {
- let s1 = cache.get(&format!("string:{}", i));
- println!("{:?}", s1);
- let l1 = cache.list(&format!("list:{}", i));
- println!("{:?}", l1);
- }
- }
- }
Add Comment
Please, Sign In to add comment