Skip to main content

trelent_hyok/cache/
custom_cache.rs

1use std::sync::Arc;
2use crate::cache::DEKCacheTrait;
3use crate::error::cache::CacheError;
4
5/// A custom cache that implements the [`DEKCacheTrait`].
6///
7/// This structure provides a flexible caching mechanism that delegates
8/// to user-defined closures for retrieving and storing data.
9pub struct CustomCache {
10    get_fn: Arc<dyn (Fn(&String) -> Option<Vec<u8>>) + Send + Sync>,
11    set_fn: Arc<dyn (Fn(String, Vec<u8>) -> Result<Vec<u8>, CacheError>) + Send + Sync>,
12}
13
14/// Implementations for creating and working with a [`CustomCache`].
15impl CustomCache {
16    /// Creates a new [`CustomCache`] with the specified get and set closures.
17    ///
18    /// # Arguments
19    ///
20    /// * `get_fn` - A closure that receives a `&String` reference to a key and returns an optional `Vec<u8>` of data.
21    /// * `set_fn` - A closure that receives a `String` key and a `Vec<u8>` to store, returning a [`Result`] with either
22    ///   the stored data or a [`CacheError`].
23    ///
24    /// # Returns
25    ///
26    /// A [`CustomCache`] instance configured with the provided closures.
27    pub fn new<G, S>(get_fn: G, set_fn: S) -> Self
28        where
29            G: Fn(&String) -> Option<Vec<u8>> + Send + Sync + 'static,
30            S: Fn(String, Vec<u8>) -> Result<Vec<u8>, CacheError> + Send + Sync + 'static
31    {
32        CustomCache {
33            get_fn: Arc::new(get_fn),
34            set_fn: Arc::new(set_fn),
35        }
36    }
37}
38
39impl DEKCacheTrait for CustomCache {
40    type Identifier = String;
41
42    /// Retrieves data from the cache for the provided key.
43    ///
44    /// # Arguments
45    ///
46    /// * `k` - A reference to the string key for which data should be retrieved.
47    ///
48    /// # Returns
49    ///
50    /// An [`Option<Vec<u8>>`] containing the cached data if found, or `None` if not present.
51    fn get(&self, k: &String) -> Option<Vec<u8>> {
52        (self.get_fn)(k)
53    }
54
55    /// Stores data in the cache for the given key.
56    ///
57    /// # Arguments
58    ///
59    /// * `k` - A string key under which the value should be stored.
60    /// * `v` - A vector of bytes representing the data to be cached.
61    ///
62    /// # Returns
63    ///
64    /// A [`Result<Vec<u8>, CacheError>`] indicating either successful storage (with the stored bytes)
65    /// or a [`CacheError`] if something went wrong.
66    fn set(&self, k: String, v: Vec<u8>) -> Result<Vec<u8>, CacheError> {
67        (self.set_fn)(k, v)
68    }
69}