Skip to main content

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    #[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}