redis_driver/clients/
cache.rs

1use crate::{Error, Result};
2use std::{
3    any::Any,
4    collections::{hash_map::Entry, HashMap},
5};
6
7#[derive(Default)]
8pub struct Cache {
9    cache: HashMap<String, Box<dyn Any + Send>>,
10}
11
12impl Cache {
13    pub fn new() -> Cache {
14        Cache {
15            cache: HashMap::new(),
16        }
17    }
18
19    pub fn get_entry<E: Default + Send + 'static>(&mut self, key: &str) -> Result<&mut E> {
20        let cache_entry = match self.cache.entry(key.to_string()) {
21            Entry::Occupied(o) => o.into_mut(),
22            Entry::Vacant(v) => v.insert(Box::new(E::default())),
23        };
24
25        let cache_entry = cache_entry
26            .downcast_mut::<E>()
27            .ok_or_else(|| Error::Client(format!("Cannot downcast cache entry '{key}'")));
28
29        cache_entry
30    }
31}