1use crate::{Ref, Value};
2use std::collections::HashMap;
3use std::sync::Mutex;
4
5#[cfg_attr(feature = "async", maybe_impl::traits(Send, Sync))]
7pub trait OptionsMonitorCache<T: Value> {
8 fn get_or_add(&self, name: Option<&str>, create_options: &dyn Fn(Option<&str>) -> T) -> Ref<T>;
15
16 fn try_add(&self, name: Option<&str>, options: T) -> bool;
23
24 fn try_remove(&self, name: Option<&str>) -> bool;
30
31 fn clear(&self);
33}
34
35pub struct OptionsCache<T> {
37 cache: Mutex<HashMap<String, Ref<T>>>,
38}
39
40impl<T> Default for OptionsCache<T> {
41 fn default() -> Self {
42 Self {
43 cache: Default::default(),
44 }
45 }
46}
47
48unsafe impl<T: Send + Sync> Send for OptionsCache<T> {}
49unsafe impl<T: Send + Sync> Sync for OptionsCache<T> {}
50
51impl<T: Value> OptionsMonitorCache<T> for OptionsCache<T> {
52 fn get_or_add(&self, name: Option<&str>, create_options: &dyn Fn(Option<&str>) -> T) -> Ref<T> {
53 let key = name.unwrap_or_default().to_string();
54 self.cache
55 .lock()
56 .unwrap()
57 .entry(key)
58 .or_insert_with(|| Ref::new(create_options(name)))
59 .clone()
60 }
61
62 fn try_add(&self, name: Option<&str>, options: T) -> bool {
63 let key = name.unwrap_or_default();
64 let mut cache = self.cache.lock().unwrap();
65
66 if cache.contains_key(key) {
67 false
68 } else {
69 cache.insert(key.to_owned(), Ref::new(options));
70 true
71 }
72 }
73
74 fn try_remove(&self, name: Option<&str>) -> bool {
75 let key = name.unwrap_or_default();
76 self.cache.lock().unwrap().remove(key).is_some()
77 }
78
79 fn clear(&self) {
80 self.cache.lock().unwrap().clear()
81 }
82}