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