use std::{any::Any, fmt::Debug, sync::Arc, time::Duration};
use moka::sync::Cache as MokaCache;
#[derive(Clone)]
pub struct Cache {
inner: MokaCache<String, Arc<dyn Any + Send + Sync>>,
}
impl Cache {
pub fn new(max_capacity: u64, time_to_live: u64) -> Self {
let inner = MokaCache::builder()
.max_capacity(max_capacity)
.time_to_live(Duration::from_secs(time_to_live))
.build();
Self { inner }
}
pub fn insert<V: 'static + Send + Sync + Debug>(
&self,
key: String,
value: V,
) {
self.inner.insert(key, Arc::new(value));
}
pub fn get<V: 'static + Clone>(&self, key: &str) -> Option<V> {
self.inner
.get(key)
.and_then(|value| value.downcast_ref::<V>().cloned())
}
pub fn remove(&self, key: &str) {
self.inner.invalidate(key);
}
pub fn len(&self) -> u64 {
self.inner.entry_count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}