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
use crate::Ref;
use std::collections::HashMap;
use std::sync::Mutex;

/// Defines the behavior of an [`Options`](crate::Options) monitor cache.
pub trait OptionsMonitorCache<T> {
    /// Gets or adds options with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - The optional name of the options
    /// * `create_options` - The function used to create options when added
    fn get_or_add(&self, name: Option<&str>, create_options: &dyn Fn(Option<&str>) -> T) -> Ref<T>;

    /// Attempts to add options with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - The optional name of the options
    /// * `options` - The options to add
    fn try_add(&self, name: Option<&str>, options: T) -> bool;

    /// Attempts to remove options with the specified name.
    ///
    /// # Arguments
    ///
    /// * `name` - The optional name of the options
    fn try_remove(&self, name: Option<&str>) -> bool;

    /// Clears all options from the cache.
    fn clear(&self);
}

/// Represents a cache for configured options.
pub struct OptionsCache<T> {
    cache: Mutex<HashMap<String, Ref<T>>>,
}

impl<T> Default for OptionsCache<T> {
    fn default() -> Self {
        Self {
            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) -> Ref<T> {
        let key = name.unwrap_or_default().to_string();
        self.cache
            .lock()
            .unwrap()
            .entry(key)
            .or_insert_with(|| Ref::new(create_options(name)))
            .clone()
    }

    fn try_add(&self, name: Option<&str>, options: T) -> bool {
        let key = name.unwrap_or_default();
        let mut cache = self.cache.lock().unwrap();

        if cache.contains_key(key) {
            false
        } else {
            cache.insert(key.to_owned(), Ref::new(options));
            true
        }
    }

    fn try_remove(&self, name: Option<&str>) -> bool {
        let key = name.unwrap_or_default();
        self.cache.lock().unwrap().remove(key).is_some()
    }

    fn clear(&self) {
        self.cache.lock().unwrap().clear()
    }
}