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 #[inline]
42 fn default() -> Self {
43 Self {
44 cache: Default::default(),
45 }
46 }
47}
48
49impl<T: Value> OptionsMonitorCache<T> for OptionsCache<T> {
50 fn get_or_add(&self, name: Option<&str>, create_options: &dyn Fn(Option<&str>) -> T) -> Ref<T> {
51 let key = name.unwrap_or_default().to_string();
52 self.cache
53 .lock()
54 .unwrap()
55 .entry(key)
56 .or_insert_with(|| Ref::new(create_options(name)))
57 .clone()
58 }
59
60 fn try_add(&self, name: Option<&str>, options: T) -> bool {
61 let key = name.unwrap_or_default();
62 let mut cache = self.cache.lock().unwrap();
63
64 if cache.contains_key(key) {
65 false
66 } else {
67 cache.insert(key.to_owned(), Ref::new(options));
68 true
69 }
70 }
71
72 fn try_remove(&self, name: Option<&str>) -> bool {
73 let key = name.unwrap_or_default();
74 self.cache.lock().unwrap().remove(key).is_some()
75 }
76
77 fn clear(&self) {
78 self.cache.lock().unwrap().clear()
79 }
80}