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
use std::sync::{Arc, Mutex, RwLock};
use writium::prelude::*;
const ERR_UNEXPECTED_OCCUPANCY: &str = "Unexpected use of cache.";
const ERR_POISONED_THREAD: &str = "Current thread is poisoned.";
#[derive(Clone)]
pub struct Cache<T: 'static> {
cache: Arc<Mutex<Vec<(String, Arc<RwLock<T>>)>>>,
src: Arc<CacheSource<Value=T>>,
}
impl<T: 'static> Cache<T> {
pub fn new<Src>(capacity: usize, src: Src) -> Cache<T>
where Src: 'static + CacheSource<Value=T> {
Cache {
cache: Arc::new(Mutex::new(Vec::with_capacity(capacity))),
src: Arc::new(src),
}
}
pub fn create(&self, id: &str) -> Result<Arc<RwLock<T>>> {
self._get(&id, true)
}
pub fn get(&self, id: &str) -> Result<Arc<RwLock<T>>> {
self._get(&id, false)
}
fn _get(&self, id: &str, create: bool) -> Result<Arc<RwLock<T>>> {
let mut cache = if let Ok(locked) = self.cache.lock() {
locked
} else {
return Err(Error::internal(ERR_POISONED_THREAD))
};
if let Some(pos) = cache.iter().position(|&(ref jd, _)| jd == id) {
let rsc = cache.remove(pos);
let rv = rsc.1.clone();
cache.push(rsc);
Ok(rv)
} else {
if cache.len() == cache.capacity() {
Arc::try_unwrap(cache.remove(0).1)
.map_err(|_| Error::internal(ERR_UNEXPECTED_OCCUPANCY))?
.into_inner()
.map_err(|_| Error::internal(ERR_POISONED_THREAD))
.and_then(|mut val| self.src.unload(id, &mut val))?;
}
let arc = Arc::new(RwLock::new(self.src.load(&id, create)?));
cache.push((id.to_string(), arc.clone()));
Ok(arc)
}
}
pub fn remove(&self, id: &str) -> Result<()> {
let mut cache = self.cache.lock().unwrap();
cache.iter()
.position(|&(ref nid, _)| nid == &id)
.map(|pos| cache.remove(pos));
self.src.remove(&id)
}
pub fn capacity(&self) -> usize {
self.cache.lock().unwrap().capacity()
}
pub fn len(&self) -> usize {
self.cache.lock().unwrap().len()
}
}
pub trait CacheSource: 'static + Send + Sync {
type Value: 'static;
fn load(&self, id: &str, create: bool) -> Result<Self::Value>;
fn unload(&self, _id: &str, _obj: &Self::Value) -> Result<()> {
Ok(())
}
fn remove(&self, _id: &str) -> Result<()> {
Ok(())
}
}
impl<T: 'static> Drop for Cache<T> {
fn drop(&mut self) {
info!("Writing cached data back to source...");
let mut lock = self.cache.lock().unwrap();
while let Some((id, val)) = lock.pop() {
if let Ok(val) = Arc::try_unwrap(val) {
let unload = self.src.unload(&id, &mut val.into_inner().unwrap());
if let Err(err) = unload {
warn!("Unable to unload '{}': {}", id, err);
}
} else {
warn!("Unexpected use of '{}'", id);
}
}
}
}
#[cfg(test)]
mod tests {
use writium::prelude::*;
struct TestSource(bool);
impl super::CacheSource for TestSource {
type Value = &'static str;
fn load(&self, id: &str, _create: bool) -> Result<Self::Value> {
if self.0 { Err(Error::not_found("")) }
else { Ok(&["cache0", "cache1", "cache2", "cache3"][id.parse::<usize>().unwrap()]) }
}
fn unload(&self, _id: &str, _obj: &Self::Value) -> Result<()> {
Ok(())
}
fn remove(&self, _id: &str) -> Result<()> {
Ok(())
}
}
type TestCache = super::Cache<&'static str>;
fn make_cache(fail: bool) -> TestCache {
TestCache::new(3, TestSource(fail))
}
#[test]
fn test_cache() {
let cache = make_cache(false);
assert!(cache.get("0").is_ok());
assert!(cache.get("1").is_ok());
assert!(cache.get("2").is_ok());
}
#[test]
fn test_cache_failure() {
let cache = make_cache(true);
assert!(cache.get("0").is_err());
assert!(cache.get("1").is_err());
assert!(cache.get("2").is_err());
}
#[test]
fn test_max_cache() {
let cache = make_cache(false);
assert!(cache.len() == 0);
assert!(cache.get("0").is_ok());
assert!(cache.len() == 1);
assert!(cache.get("1").is_ok());
assert!(cache.len() == 2);
assert!(cache.get("2").is_ok());
assert!(cache.len() == 3);
assert!(cache.get("3").is_ok());
assert!(cache.len() == 3);
}
#[test]
fn test_max_cache_failure() {
let cache = make_cache(true);
assert!(cache.len() == 0);
assert!(cache.get("0").is_err());
assert!(cache.len() == 0);
assert!(cache.get("1").is_err());
assert!(cache.len() == 0);
assert!(cache.get("2").is_err());
assert!(cache.len() == 0);
}
#[test]
fn test_remove() {
let cache = make_cache(false);
assert!(cache.get("0").is_ok());
assert!(cache.len() == 1);
assert!(cache.remove("0").is_ok());
assert!(cache.len() == 0);
assert!(cache.remove("0").is_ok());
}
}