trelent-hyok 0.1.12

A Rust library implementing Hold Your Own Key (HYOK) encryption patterns with support for multiple cloud providers
Documentation
use std::sync::Arc;
use crate::cache::DEKCacheTrait;
use crate::error::cache::CacheError;

/// A custom cache that implements the [`DEKCacheTrait`].
///
/// This structure provides a flexible caching mechanism that delegates
/// to user-defined closures for retrieving and storing data.
pub struct CustomCache {
    get_fn: Arc<dyn (Fn(&String) -> Option<Vec<u8>>) + Send + Sync>,
    set_fn: Arc<dyn (Fn(String, Vec<u8>) -> Result<Vec<u8>, CacheError>) + Send + Sync>,
}

/// Implementations for creating and working with a [`CustomCache`].
impl CustomCache {
    /// Creates a new [`CustomCache`] with the specified get and set closures.
    ///
    /// # Arguments
    ///
    /// * `get_fn` - A closure that receives a `&String` reference to a key and returns an optional `Vec<u8>` of data.
    /// * `set_fn` - A closure that receives a `String` key and a `Vec<u8>` to store, returning a [`Result`] with either
    ///   the stored data or a [`CacheError`].
    ///
    /// # Returns
    ///
    /// A [`CustomCache`] instance configured with the provided closures.
    pub fn new<G, S>(get_fn: G, set_fn: S) -> Self
        where
            G: Fn(&String) -> Option<Vec<u8>> + Send + Sync + 'static,
            S: Fn(String, Vec<u8>) -> Result<Vec<u8>, CacheError> + Send + Sync + 'static
    {
        CustomCache {
            get_fn: Arc::new(get_fn),
            set_fn: Arc::new(set_fn),
        }
    }
}

impl DEKCacheTrait for CustomCache {
    type Identifier = String;

    /// Retrieves data from the cache for the provided key.
    ///
    /// # Arguments
    ///
    /// * `k` - A reference to the string key for which data should be retrieved.
    ///
    /// # Returns
    ///
    /// An [`Option<Vec<u8>>`] containing the cached data if found, or `None` if not present.
    fn get(&self, k: &String) -> Option<Vec<u8>> {
        (self.get_fn)(k)
    }

    /// Stores data in the cache for the given key.
    ///
    /// # Arguments
    ///
    /// * `k` - A string key under which the value should be stored.
    /// * `v` - A vector of bytes representing the data to be cached.
    ///
    /// # Returns
    ///
    /// A [`Result<Vec<u8>, CacheError>`] indicating either successful storage (with the stored bytes)
    /// or a [`CacheError`] if something went wrong.
    fn set(&self, k: String, v: Vec<u8>) -> Result<Vec<u8>, CacheError> {
        (self.set_fn)(k, v)
    }
}