-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcache.rs
537 lines (470 loc) · 16.3 KB
/
cache.rs
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
// Fork of https://github.com/maidsafe/lru_time_cache to be memory limited instead.
//
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.
#![doc(
html_logo_url = "https://raw.githubusercontent.com/maidsafe/QA/master/Images/maidsafe_logo.png",
html_favicon_url = "https://maidsafe.net/img/favicon.ico",
test(attr(forbid(warnings)))
)]
// For explanation of lint checks, run `rustc -W help` or see
// https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(
bad_style,
exceeding_bitshifts,
mutable_transmutes,
no_mangle_const_items,
unknown_crate_types
)]
#![deny(
deprecated,
improper_ctypes,
missing_docs,
non_shorthand_field_patterns,
overflowing_literals,
plugin_as_library,
stable_features,
unconditional_recursion,
unknown_lints,
unsafe_code,
unused_allocation,
unused_attributes,
unused_comparisons,
unused_features,
unused_parens,
while_true
)]
#![warn(
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![allow(
box_pointers,
missing_copy_implementations,
missing_debug_implementations,
variant_size_differences,
dead_code
)]
// During testing we use a mock clock to be time independent.
#[cfg(test)]
use fake_clock::FakeClock as Instant;
use std::borrow::Borrow;
use std::collections::{btree_map, BTreeMap, VecDeque};
use std::mem::size_of;
#[cfg(not(test))]
use std::time::Instant;
use std::usize;
/// All values that the cache can store must implement this trait.
/// Returns the approximate memory size in bytes a cache value takes up.
pub trait MemorySizable {
fn get_memory_size(&self) -> usize;
}
// This could probably be generic for all primitive types.
// @todo look up how to specify trait bounds for primitive types.
impl MemorySizable for usize {
fn get_memory_size(&self) -> usize {
size_of::<usize>()
}
}
/// An iterator over an `LruCache`'s entries that updates the timestamps as values are traversed.
pub struct Iter<'a, Key: 'a, Value: 'a> {
map_iter_mut: btree_map::IterMut<'a, Key, (Value, Instant, usize)>,
list: &'a mut VecDeque<Key>,
}
impl<'a, Key, Value> Iterator for Iter<'a, Key, Value>
where
Key: Ord + Clone,
Value: MemorySizable,
{
type Item = (&'a Key, &'a Value);
fn next(&mut self) -> Option<(&'a Key, &'a Value)> {
let now = Instant::now();
let not_expired = self
.map_iter_mut
.find(|&(_, &mut (_, instant, _))| instant > now);
not_expired.map(|(key, &mut (ref value, _, _))| {
LruCache::<Key, Value>::update_key(self.list, key);
(key, value)
})
}
}
/// An iterator over an `LruCache`'s entries that does not modify the timestamp.
pub struct PeekIter<'a, Key: 'a, Value: 'a> {
map_iter: btree_map::Iter<'a, Key, (Value, Instant, usize)>,
}
impl<'a, Key, Value> Iterator for PeekIter<'a, Key, Value>
where
Key: Ord + Clone,
{
type Item = (&'a Key, &'a Value);
fn next(&mut self) -> Option<(&'a Key, &'a Value)> {
let now = Instant::now();
let not_expired = self.map_iter.find(|&(_, &(_, instant, _))| instant > now);
not_expired.map(|(key, &(ref value, _, _))| (key, value))
}
}
/// Implementation of [LRU cache](index.html#least-recently-used-lru-cache).
#[derive(Debug)]
pub struct LruCache<Key, Value> {
// Store the value itself, the expires date and a memory size of the value.
// @todo make this a proper struct instead of an anonymous tuple.
map: BTreeMap<Key, (Value, Instant, usize)>,
list: VecDeque<Key>,
// Maximum memory constraint.
max_memory_size: usize,
// Current memory usage, initialized with 0. Increased whenever an item is
// inserted into the cache. Decreases when an item is removed or expires.
current_memory_size: usize,
}
impl<Key, Value> LruCache<Key, Value>
where
Key: Ord + Clone,
Value: MemorySizable,
{
/// Constructor for a mmemory constrained cache.
pub fn with_memory_size(memory_size: usize) -> LruCache<Key, Value> {
LruCache {
map: BTreeMap::new(),
list: VecDeque::new(),
max_memory_size: memory_size,
current_memory_size: 0,
}
}
/// Inserts a key-value pair into the cache.
///
/// If the key already existed in the cache, the existing value is returned and overwritten in
/// the cache. Otherwise, the key-value pair is inserted and `None` is returned.
pub fn insert(&mut self, key: Key, value: Value, expires: Instant) -> Option<Value> {
self.remove_expired();
let old_value = self.remove(&key);
// @todo should we also add some bytes for the key size? Oh noes, we
// also own the key in self.list so the key will also have to implement
// MemorySizable...
let memory_size =
// Size of the value.
value.get_memory_size()
// Size of the expiry timestamp.
+ size_of::<Instant>()
// Size of the memory count.
+ size_of::<usize>();
if memory_size <= self.max_memory_size {
// Remove old cache entries until we have room to insert the new item.
while self.max_memory_size < self.current_memory_size + memory_size {
let remove_key = self
.list
.pop_front()
.expect("Queue is empty but current memory size > 0");
let (_, _, removed_size) = self
.map
.remove(&remove_key)
.expect("Shrinking cache failed");
self.current_memory_size -= removed_size;
}
self.list.push_back(key.clone());
self.current_memory_size += memory_size;
let _ = self.map.insert(key, (value, expires, memory_size));
}
old_value
}
/// Removes a key-value pair from the cache.
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Value>
where
Key: Borrow<Q>,
Q: Ord,
{
self.map.remove(key).map(|(value, _, memory_size)| {
let _ = self
.list
.iter()
.position(|l| l.borrow() == key)
.map(|p| self.list.remove(p));
self.current_memory_size -= memory_size;
value
})
}
/// Clears the `LruCache`, removing all values.
pub fn clear(&mut self) {
self.map.clear();
self.list.clear();
self.current_memory_size = 0;
}
/// Retrieves a reference to the value stored under `key`, or `None` if the key doesn't exist.
/// Also removes expired elements and updates the time.
pub fn get<Q: ?Sized>(&mut self, key: &Q) -> Option<&Value>
where
Key: Borrow<Q>,
Q: Ord,
{
self.remove_expired();
let list = &mut self.list;
self.map.get_mut(key).map(|result| {
Self::update_key(list, key);
&result.0
})
}
/// Returns a reference to the value with the given `key`, if present and not expired, without
/// updating the timestamp.
pub fn peek<Q: ?Sized>(&self, key: &Q) -> Option<&Value>
where
Key: Borrow<Q>,
Q: Ord,
{
self.map
.get(key)
.into_iter()
.find(|&(_, t, _)| *t >= Instant::now())
.map(|&(ref value, _, _)| value)
}
/// Returns whether `key` exists in the cache or not.
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
Key: Borrow<Q>,
Q: Ord,
{
self.peek(key).is_some()
}
/// Returns the size of the cache, i.e. the number of cached non-expired key-value pairs.
pub fn len(&self) -> usize {
self.map
.iter()
.filter(|&(_, (_, t, _))| *t >= Instant::now())
.count()
}
/// Returns `true` if there are no non-expired entries in the cache.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns an iterator over all entries that updates the timestamps as values are
/// traversed. Also removes expired elements before creating the iterator.
pub fn iter(&mut self) -> Iter<Key, Value> {
self.remove_expired();
Iter {
map_iter_mut: self.map.iter_mut(),
list: &mut self.list,
}
}
/// Returns an iterator over all entries that does not modify the timestamps.
pub fn peek_iter(&self) -> PeekIter<Key, Value> {
PeekIter {
map_iter: self.map.iter(),
}
}
// Move `key` in the ordered list to the last
fn update_key<Q: ?Sized>(list: &mut VecDeque<Key>, key: &Q)
where
Key: Borrow<Q>,
Q: Ord,
{
if let Some(pos) = list.iter().position(|k| k.borrow() == key) {
let _ = list.remove(pos).map(|it| list.push_back(it));
}
}
fn remove_expired(&mut self) {
// Because of the borrow checker we need to clone the keys to be removed
// while accessing the map. Any better ideas how to simplify this?
let remove_entries = self
.map
.iter()
.filter(|(_, (_, t, _))| *t < Instant::now())
.map(|(key, _)| key.clone())
.collect::<Vec<_>>();
for key in remove_entries {
let _ = self.remove(&key);
}
}
}
impl<Key, Value> Clone for LruCache<Key, Value>
where
Key: Clone,
Value: Clone,
{
fn clone(&self) -> LruCache<Key, Value> {
LruCache {
map: self.map.clone(),
list: self.list.clone(),
max_memory_size: self.max_memory_size,
current_memory_size: self.current_memory_size,
}
}
}
#[cfg(test)]
mod test {
use fake_clock::FakeClock as Instant;
use std::mem::size_of;
use std::time::Duration;
fn sleep(time: u64) {
use fake_clock::FakeClock;
FakeClock::advance_time(time);
}
fn generate_random_vec<T>(len: usize) -> Vec<T>
where
rand::distributions::Standard: rand::distributions::Distribution<T>,
{
let mut vec = Vec::<T>::with_capacity(len);
for _ in 0..len {
vec.push(rand::random());
}
vec
}
#[test]
fn memory_size() {
// 1x usize value, 1x usize memory size.
let size = 10 * (size_of::<usize>() * 2 + size_of::<Instant>());
let mut lru_cache = super::LruCache::<usize, usize>::with_memory_size(size);
for i in 0..10 {
assert_eq!(lru_cache.len(), i);
let _ = lru_cache.insert(i, i, Instant::now() + Duration::from_secs(1000));
assert_eq!(lru_cache.len(), i + 1);
}
for i in 10..1000 {
let _ = lru_cache.insert(i, i, Instant::now() + Duration::from_secs(1000));
assert_eq!(lru_cache.current_memory_size, size);
}
for _ in (0..1000).rev() {
assert!(lru_cache.contains_key(&(1000 - 1)));
assert!(lru_cache.get(&(1000 - 1)).is_some());
assert_eq!(*lru_cache.get(&(1000 - 1)).unwrap(), 1000 - 1);
}
}
#[test]
fn expiration_time() {
let time_to_live = Duration::from_millis(100);
let mut lru_cache = super::LruCache::<usize, usize>::with_memory_size(10000);
for i in 0..10 {
assert_eq!(lru_cache.len(), i);
let _ = lru_cache.insert(i, i, Instant::now() + time_to_live);
assert_eq!(lru_cache.len(), i + 1);
}
sleep(101);
let _ = lru_cache.insert(11, 11, Instant::now() + time_to_live);
assert_eq!(lru_cache.len(), 1);
for i in 0..10 {
assert!(!lru_cache.is_empty());
assert_eq!(lru_cache.len(), i + 1);
let _ = lru_cache.insert(i, i, Instant::now() + time_to_live);
assert_eq!(lru_cache.len(), i + 2);
}
sleep(101);
assert_eq!(0, lru_cache.len());
assert!(lru_cache.is_empty());
}
#[test]
fn time_and_size() {
let size = 10;
// 1x usize value, 1x usize memory size.
let memory_size = 10 * (size_of::<usize>() * 2 + size_of::<Instant>());
let time_to_live = Duration::from_millis(100);
let mut lru_cache = super::LruCache::<usize, usize>::with_memory_size(memory_size);
for i in 0..1000 {
if i < size {
assert_eq!(lru_cache.len(), i);
}
let _ = lru_cache.insert(i, i, Instant::now() + time_to_live);
if i < size {
assert_eq!(lru_cache.len(), i + 1);
} else {
assert_eq!(lru_cache.len(), size);
}
}
sleep(101);
let _ = lru_cache.insert(1, 1, Instant::now() + time_to_live);
assert_eq!(lru_cache.len(), 1);
}
#[derive(PartialEq, PartialOrd, Ord, Clone, Eq)]
struct Temp {
id: Vec<u8>,
}
#[test]
fn time_size_struct_value() {
let size = 100usize;
// 1x usize value, 1x usize memory size.
let memory_size = 100 * (size_of::<usize>() * 2 + size_of::<Instant>());
let time_to_live = Duration::from_millis(100);
let mut lru_cache = super::LruCache::<Temp, usize>::with_memory_size(memory_size);
for i in 0..1000 {
if i < size {
assert_eq!(lru_cache.len(), i);
}
let _ = lru_cache.insert(
Temp {
id: generate_random_vec::<u8>(64),
},
i,
Instant::now() + time_to_live,
);
if i < size {
assert_eq!(lru_cache.len(), i + 1);
} else {
assert_eq!(lru_cache.len(), size);
}
}
sleep(101);
let _ = lru_cache.insert(
Temp {
id: generate_random_vec::<u8>(64),
},
1,
Instant::now() + time_to_live,
);
assert_eq!(lru_cache.len(), 1);
}
#[test]
fn peek_iter() {
let time_to_live = Duration::from_millis(100);
let mut lru_cache = super::LruCache::<usize, usize>::with_memory_size(10000);
let _ = lru_cache.insert(0, 0, Instant::now() + time_to_live);
let _ = lru_cache.insert(2, 2, Instant::now() + time_to_live);
let _ = lru_cache.insert(3, 3, Instant::now() + time_to_live);
sleep(50);
assert_eq!(
vec![(&0, &0), (&2, &2), (&3, &3)],
lru_cache.peek_iter().collect::<Vec<_>>()
);
assert_eq!(Some(&2), lru_cache.get(&2));
let _ = lru_cache.insert(1, 1, Instant::now() + time_to_live);
let _ = lru_cache.insert(4, 4, Instant::now() + time_to_live);
sleep(51);
assert_eq!(
vec![(&1, &1), (&4, &4)],
lru_cache.peek_iter().collect::<Vec<_>>()
);
sleep(50);
assert!(lru_cache.is_empty());
}
#[test]
fn peek_time_check() {
let time_to_live = Duration::from_millis(100);
let mut lru_cache = super::LruCache::<usize, usize>::with_memory_size(10000);
assert_eq!(lru_cache.len(), 0);
let _ = lru_cache.insert(0, 0, Instant::now() + time_to_live);
assert_eq!(lru_cache.len(), 1);
sleep(50);
assert_eq!(Some(&0), lru_cache.get(&0));
assert_eq!(Some(&0), lru_cache.peek(&0));
sleep(51);
assert_eq!(None, lru_cache.peek(&0));
}
#[test]
fn deref_coercions() {
let mut lru_cache = super::LruCache::<String, usize>::with_memory_size(100);
let _ = lru_cache.insert(
"foo".to_string(),
0,
Instant::now() + Duration::from_secs(1000),
);
assert_eq!(true, lru_cache.contains_key("foo"));
assert_eq!(Some(&0), lru_cache.get("foo"));
assert_eq!(Some(&0), lru_cache.peek("foo"));
assert_eq!(Some(0), lru_cache.remove("foo"));
}
}