options/
cache.rs

1use crate::{Ref, Value};
2use std::collections::HashMap;
3use std::sync::Mutex;
4
5/// Defines the behavior of an [`Options`](crate::Options) monitor cache.
6#[cfg_attr(feature = "async", maybe_impl::traits(Send, Sync))]
7pub trait OptionsMonitorCache<T: Value> {
8    /// Gets or adds options with the specified name.
9    ///
10    /// # Arguments
11    ///
12    /// * `name` - The optional name of the options
13    /// * `create_options` - The function used to create options when added
14    fn get_or_add(&self, name: Option<&str>, create_options: &dyn Fn(Option<&str>) -> T) -> Ref<T>;
15
16    /// Attempts to add options with the specified name.
17    ///
18    /// # Arguments
19    ///
20    /// * `name` - The optional name of the options
21    /// * `options` - The options to add
22    fn try_add(&self, name: Option<&str>, options: T) -> bool;
23
24    /// Attempts to remove options with the specified name.
25    ///
26    /// # Arguments
27    ///
28    /// * `name` - The optional name of the options
29    fn try_remove(&self, name: Option<&str>) -> bool;
30
31    /// Clears all options from the cache.
32    fn clear(&self);
33}
34
35/// Represents a cache for configured options.
36pub 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}