1use std::time::SystemTime;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct Entry {
10 pub document: String,
12 pub version: u64,
14 pub bytes: u64,
16 pub read: SystemTime,
18}
19
20impl Entry {
21 pub fn key(&self) -> (String, u64) {
23 (self.document.clone(), self.version)
24 }
25}
26
27pub trait Eviction: Send + Sync {
31 fn choose(&self, entries: &[Entry], limit: u64) -> Vec<(String, u64)>;
32}
33
34pub struct Lru;
37
38impl Eviction for Lru {
39 fn choose(&self, entries: &[Entry], limit: u64) -> Vec<(String, u64)> {
40 let mut size: u64 = entries.iter().map(|e| e.bytes).sum();
41 if size <= limit {
42 return Vec::new();
43 }
44 let target = limit / 10 * 9;
45 let mut oldest: Vec<&Entry> = entries.iter().collect();
46 oldest.sort_by_key(|e| e.read);
47 let mut chosen = Vec::new();
48 for entry in oldest {
49 if size <= target {
50 break;
51 }
52 size -= entry.bytes;
53 chosen.push(entry.key());
54 }
55 chosen
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62 use std::time::Duration;
63
64 fn entry(document: &str, bytes: u64, age: u64) -> Entry {
65 Entry {
66 document: document.into(),
67 version: 1,
68 bytes,
69 read: SystemTime::UNIX_EPOCH + Duration::from_secs(1000 - age),
70 }
71 }
72
73 #[test]
74 fn under_the_limit_nothing_goes() {
75 let entries = [entry("a", 40, 1), entry("b", 50, 2)];
76 assert!(Lru.choose(&entries, 100).is_empty());
77 }
78
79 #[test]
80 fn past_the_limit_the_least_recently_read_go_until_it_is_at_ninety_percent() {
81 let entries = [
82 entry("new", 30, 1),
83 entry("old", 30, 9),
84 entry("mid", 30, 5),
85 entry("older", 30, 7),
86 ];
87 assert_eq!(Lru.choose(&entries, 100), [("old".to_string(), 1)]);
89 assert_eq!(
91 Lru.choose(&entries, 60),
92 [
93 ("old".to_string(), 1),
94 ("older".to_string(), 1),
95 ("mid".to_string(), 1)
96 ]
97 );
98 }
99}