use crate::Ref;
use std::collections::HashMap;
use std::sync::Mutex;
pub trait OptionsMonitorCache<T> {
fn get_or_add(&self, name: Option<&str>, create_options: &dyn Fn(Option<&str>) -> T) -> Ref<T>;
fn try_add(&self, name: Option<&str>, options: T) -> bool;
fn try_remove(&self, name: Option<&str>) -> bool;
fn clear(&self);
}
pub struct OptionsCache<T> {
cache: Mutex<HashMap<String, Ref<T>>>,
}
impl<T> Default for OptionsCache<T> {
fn default() -> Self {
Self {
cache: Default::default(),
}
}
}
impl<T> OptionsMonitorCache<T> for OptionsCache<T> {
fn get_or_add(&self, name: Option<&str>, create_options: &dyn Fn(Option<&str>) -> T) -> Ref<T> {
let key = name.unwrap_or_default().to_string();
self.cache
.lock()
.unwrap()
.entry(key)
.or_insert_with(|| Ref::new(create_options(name)))
.clone()
}
fn try_add(&self, name: Option<&str>, options: T) -> bool {
let key = name.unwrap_or_default();
let mut cache = self.cache.lock().unwrap();
if cache.contains_key(key) {
false
} else {
cache.insert(key.to_owned(), Ref::new(options));
true
}
}
fn try_remove(&self, name: Option<&str>) -> bool {
let key = name.unwrap_or_default();
self.cache.lock().unwrap().remove(key).is_some()
}
fn clear(&self) {
self.cache.lock().unwrap().clear()
}
}