1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use std::cell::UnsafeCell;
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) -> &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> {
sync: Mutex<String>,
cache: UnsafeCell<HashMap<String, T>>,
}
impl<T> Default for OptionsCache<T> {
fn default() -> Self {
Self {
sync: Default::default(),
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) -> &T {
let key = name.unwrap_or_default().to_string();
let _lock = self.sync.lock().unwrap();
unsafe {
let cache: &mut HashMap<String, T> = &mut *self.cache.get();
cache.entry(key).or_insert_with(|| create_options(name))
}
}
fn try_add(&self, name: Option<&str>, options: T) -> bool {
let key = name.unwrap_or_default();
let _lock = self.sync.lock().unwrap();
unsafe {
let cache: &mut HashMap<String, T> = &mut *self.cache.get();
if cache.contains_key(key) {
false
} else {
cache.insert(key.to_owned(), options);
true
}
}
}
fn try_remove(&self, name: Option<&str>) -> bool {
let key = name.unwrap_or_default();
let _lock = self.sync.lock().unwrap();
unsafe {
let cache: &mut HashMap<String, T> = &mut *self.cache.get();
cache.remove(key).is_some()
}
}
fn clear(&self) {
let _lock = self.sync.lock().unwrap();
unsafe {
let cache: &mut HashMap<String, T> = &mut *self.cache.get();
cache.clear();
}
}
}