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
use crate::*;
use std::hash::Hash;

#[derive(Clone)]
pub struct Cache<K, T> {
    mutex: Arc<Mutex<HashMap<K, T>>>,
}

impl<K, T> Cache<K, T>
where
    K: Hash + Eq,
{
    pub fn new() -> Cache<K, T> {
        Cache {
            mutex: Arc::new(Mutex::new(HashMap::new())),
        }
    }
}

impl<K, T> Cache<K, T>
where
    T: Default + Clone,
    K: Hash + Eq + Clone,
{
    pub fn gate<F: FnOnce() -> T>(&self, key: &K, f: F) -> T {
        {
            if let Ok(mut cache) = self.mutex.lock() {
                if let Some(type_) = cache.get(key) {
                    return type_.clone();
                }

                cache.insert(key.clone(), Default::default());
            }
        }

        let result = f();

        {
            if let Ok(mut cache) = self.mutex.lock() {
                cache.insert(key.clone(), result.clone());
            }
        }

        result
    }
}

impl<K, T> Cache<K, T>
where
    T: Clone,
    K: Hash + Eq + Clone,
{
    pub fn set(&self, key: K, value: T) {
        self.mutex
            .lock()
            .expect("failed to set value in cache")
            .insert(key, value);
    }

    pub fn get(&self, key: &K) -> Option<T> {
        self.mutex
            .lock()
            .expect("failed to set value in cache")
            .get(key)
            .cloned()
    }

    pub fn gate_not_loop_safe<F: FnOnce() -> T>(&self, key: &K, f: F) -> T {
        {
            if let Ok(cache) = self.mutex.lock() {
                if let Some(type_) = cache.get(key) {
                    return type_.clone();
                }
            }
        }

        let result = f();

        {
            if let Ok(mut cache) = self.mutex.lock() {
                cache.insert(key.clone(), result.clone());
            }
        }

        result
    }
}