mod moka;
mod custom_cache;
pub use custom_cache::*;
pub use moka::*;
#[cfg(feature = "debug")]
use std::collections::HashMap;
#[cfg(feature = "debug")]
use std::sync::Mutex;
use crate::error::cache::CacheError;
pub trait DEKCacheTrait {
type Identifier: AsRef<[u8]>;
fn get(&self, k: &Self::Identifier) -> Option<Vec<u8>>;
fn set(&self, k: Self::Identifier, v: Vec<u8>) -> Result<Vec<u8>, CacheError>;
}
#[cfg(feature = "debug")]
pub struct DebugCache {
cache: Mutex<HashMap<String, Vec<u8>>>,
}
#[cfg(feature = "debug")]
impl DEKCacheTrait for DebugCache {
type Identifier = String;
fn get(&self, k: &String) -> Option<Vec<u8>> {
let cache = self.cache.lock();
let mut hasher = md5::Context::new();
hasher.consume(k);
let hash_name = hex::encode(hasher.compute().0);
match cache {
Ok(cache) => cache.get(&hash_name).map(|thing| thing.clone()),
Err(_) => None,
}
}
fn set(&self, k: String, v: Vec<u8>) -> Result<Vec<u8>, CacheError> {
let data = self.cache.lock();
match data {
Ok(mut data) => {
let mut hasher = md5::Context::new();
hasher.consume(k);
let hash_name = hex::encode(hasher.compute().0);
data.insert(hash_name.clone(), v);
data.get(&hash_name).cloned().ok_or(CacheError("Could not insert!".to_string()))
}
Err(_) => Err(CacheError("Mutex error!".to_string())),
}
}
}
pub enum DEKCache {
Custom(CustomCache),
Moka(MokaCache),
NoCache,
}
impl DEKCache {
pub fn get(&self, k: &String) -> Option<Vec<u8>> {
match self {
DEKCache::Custom(cache) => cache.get(k),
DEKCache::Moka(cache) => cache.get(k),
DEKCache::NoCache => None,
}
}
pub fn set(&self, k: String, v: Vec<u8>) -> Result<Vec<u8>, CacheError> {
match self {
DEKCache::Custom(cache) => cache.set(k, v),
DEKCache::Moka(cache) => cache.set(k, v),
DEKCache::NoCache => Ok(v),
}
}
}