use std::collections::HashMap;
use std::sync::RwLock;
use crate::cache::Cache;
use crate::options::EntryOptions;
pub trait DefaultEntryOptionsProvider: Send + Sync {
fn options_for(&self, key: &str) -> Option<EntryOptions>;
}
pub struct CacheRegistry<V: Clone + Send + Sync + 'static> {
caches: RwLock<HashMap<String, Cache<V>>>,
}
impl<V: Clone + Send + Sync + 'static> CacheRegistry<V> {
#[must_use]
pub fn new() -> Self {
Self {
caches: RwLock::new(HashMap::new()),
}
}
pub fn register(&self, name: impl Into<String>, cache: Cache<V>) {
if let Ok(mut map) = self.caches.write() {
map.insert(name.into(), cache);
}
}
#[must_use]
pub fn get(&self, name: &str) -> Option<Cache<V>> {
self.caches.read().ok()?.get(name).cloned()
}
pub fn get_or_create(&self, name: &str, build: impl FnOnce() -> Cache<V>) -> Cache<V> {
if let Some(existing) = self.get(name) {
return existing;
}
let cache = build();
self.register(name.to_owned(), cache.clone());
cache
}
#[must_use]
pub fn len(&self) -> usize {
self.caches.read().map(|m| m.len()).unwrap_or(0)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<V: Clone + Send + Sync + 'static> Default for CacheRegistry<V> {
fn default() -> Self {
Self::new()
}
}