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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use std::sync::{Arc, RwLock};
use std::hash::Hash;
use tokio::sync::RwLock as TokioRwLock;


/// Provides a reliable cache for HashMap<Key, Value> where value can be derived from key, but could be expensive to generate.
/// The cache is thread safe and can be used in multi-threaded environment.
/// The cache is not async, so it is not suitable for async environment.
/// For async cache, use CasheAsync instead.
/// 
/// ```
/// use anycache::Cache;
/// use anycache::CacheAsync;
/// 
/// fn my_gen(x:&String) -> String {
///   println!("Generating {}", x);
///   let mut y = x.clone();
///   y.push_str("@");
///   y
/// }
/// 
/// // For async cache, use CacheAsync
/// fn test_sync_cache() {
///   let c = Cache::new(my_gen);
/// 
///   for j in 0..2 {
///     for i in 0..10 {
///       let key = format!("key{}", i);
///       let v = c.get(&key);
///       println!("{}:{}: {}", j, i, *v);
///     }
///   }
/// }
/// 
/// // For sync cache, use Cache
/// async fn test_cache_async() {
///   // Cache is only generated once above. Similarly, for Async.
/// 
///   let c = CacheAsync::new(my_gen);
/// 
///   for j in 0..2 {
///     for i in 0..10 {
///       let key = format!("key{}", i);
///       let v = c.get(&key).await;
///       println!("{}:{}: {}", j, i, *v);
///     }
///   }
/// }
/// 
/// ```


/// Create a Cache with K, V type. Similar to Map. 
/// However, the value is generated from key on-demand using generate function
pub struct Cache<K,V> where 
    K: Hash + std::cmp::Eq + Clone,
{
    map: Arc<RwLock<std::collections::HashMap<K, Arc<V>>>>,
    generator: Generator<K, V>,
}

// Same as Cache, but using Async RwLock
pub struct CacheAsync<K, V> where 
    K: Hash + std::cmp::Eq + Clone,
{
    map: Arc<TokioRwLock<std::collections::HashMap<K, Arc<V>>>>,
    generator: GeneratorAsync<K, V>,
}

/// A generator function place holder
struct Generator<K, V> where 
K:Hash + Eq + Clone 
{
    generator: Box<dyn Fn(&K) -> V + 'static + Sync>
}

struct GeneratorAsync<K, V> where 
    K:Hash + Eq + Clone 
{
    generator: Box<dyn Fn(&K) -> V + 'static + Sync>
}

impl <K, V> Cache<K,V> where 
    K:Hash + Eq + Clone 
{
    /// Create a new cache using the given generator function
    pub fn new(generator:impl Fn(&K) -> V + 'static + Sync) -> Self 
        where K: Hash + Eq {
        Cache {
            map: Arc::new(RwLock::new(std::collections::HashMap::new())),
            generator: Generator{generator: Box::new(generator)},
        }
    }

    /// Get from the cache. If the key is missing, do not generate it and return None
    pub fn get_if(&self, key: &K) -> Option<Arc<V>> {
        let r = self.map.read().unwrap();
        let value = r.get(key);
        match value {
            Some(v) => Some(Arc::clone(v)),
            None => None
        }
    }

    /// Drop the key from the cache if it exists
    /// Does nothing if the key is not there
    pub fn drop(&self, key: &K) {
        let mut w = self.map.write().unwrap();
        w.remove(key);
    }

    /// Get the key from cache. If not found, generate one.
    pub fn get(&self, key: &K) -> Arc<V> {
        let r = self.map.read().unwrap();
        let value = r.get(key);
        match value {
            Some(v) => Arc::clone(v),
            None => {
                drop(r);
                let mut w = self.map.write().unwrap();
                let value = (self.generator.generator)(key);
                let arc = Arc::new(value);
                w.insert(key.clone(), Arc::clone(&arc));
                drop(w);
                arc
            }
        }
    }
}


/// Similar to Cache, but using async RwLock
impl <K, V> CacheAsync<K,V> where 
    K:Hash + Eq + Clone 
{
    /// Create a new cache using the given generator function
    pub fn new(generator:impl Fn(&K) -> V + 'static + Sync) -> Self 
        where K: Hash + Eq {
        CacheAsync {
            map: Arc::new(TokioRwLock::new(std::collections::HashMap::new())),
            generator: GeneratorAsync{generator: Box::new(generator)},
        }
    }

    /// Get from the cache. If the key is missing, do not generate it and return None
    pub async fn get_if(&self, key: &K) -> Option<Arc<V>> {
        let r = self.map.read().await;
        let value = r.get(key);
        match value {
            Some(v) => Some(Arc::clone(v)),
            None => None
        }
    }

    /// Drop the key from the cache if it it exists
    pub async fn drop(&self, key: &K) {
        let mut w = self.map.write().await;
        w.remove(key);
    }
    /// Get the key from cache. If not found, generate one.
    pub async fn get(&self, key: &K) -> Arc<V> {
        let r = self.map.read().await;
        let value = r.get(key);
        match value {
            Some(v) => Arc::clone(v),
            None => {
                drop(r);
                let mut w = self.map.write().await;
                let value = (self.generator.generator)(key);
                let arc = Arc::new(value);
                w.insert(key.clone(), Arc::clone(&arc));
                drop(w);
                arc
            }
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        println!("Running test...");
        let c = Cache::new(|x:&String| -> String {
            println!("Generating {}", x);
            let mut y = x.clone();
            y.push_str("@");
            y
        });

        for j in 0..2 {
            for i in 0..10 {
                let key = format!("key{}", i);
                let v = c.get(&key);
                println!("{}:{}: {}", j, i, *v);
            }
        }
    }

    #[tokio::test]
    async fn test_cache_async() {
        println!("Running test...");
        let c = CacheAsync::new(|x:&String| -> String {
            println!("Generating {}", x);
            let mut y = x.clone();
            y.push_str("@");
            y
        });

        for j in 0..2 {
            for i in 0..10 {
                let key = format!("key{}", i);
                let v = c.get(&key).await;
                println!("{}:{}: {}", j, i, *v);
            }
        }
    }
}