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
//! Least-recently-used cache ordering engine.
//!
//! Mirrors the LRU bookkeeping of `bzrformats.lru_cache.LRUCache` /
//! `LRUSizeCache`: a doubly-linked list threads the entries from most- to
//! least-recently-used, and eviction walks from the LRU end. This core is
//! deliberately Python-agnostic — entries are identified by an opaque
//! [`NodeId`] and carry only an integer size, so the pyo3 wrapper can hold
//! the actual Python keys/values and compute sizes via a Python callable
//! while this module owns the ordering and eviction policy.
use std::collections::HashMap;
/// Opaque handle for a cache entry. The caller assigns ids (typically a
/// monotonically increasing counter) and maps them to its own keys/values.
pub type NodeId = u64;
struct Node {
prev: Option<NodeId>,
next: Option<NodeId>,
/// Size contribution of this entry, as computed by the caller.
size: usize,
}
/// LRU ordering engine with size-based eviction.
///
/// The `LRUCache` count-based variant in Python is the special case where
/// every entry has size 1 and `max_size`/`after_cleanup_size` are the entry
/// counts; the pyo3 layer uses this type for both.
#[derive(Default)]
pub struct LruOrder {
nodes: HashMap<NodeId, Node>,
/// Head of the list — the most recently used entry.
most_recently_used: Option<NodeId>,
/// Tail of the list — the least recently used entry.
least_recently_used: Option<NodeId>,
/// Sum of all entry sizes currently held.
total_size: usize,
}
impl LruOrder {
pub fn new() -> Self {
Self::default()
}
/// Number of entries currently tracked.
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
/// Total size of all entries (sum of per-entry sizes).
pub fn total_size(&self) -> usize {
self.total_size
}
pub fn contains(&self, id: NodeId) -> bool {
self.nodes.contains_key(&id)
}
/// The current least-recently-used entry, if any.
pub fn lru(&self) -> Option<NodeId> {
self.least_recently_used
}
/// The current most-recently-used entry, if any.
pub fn mru(&self) -> Option<NodeId> {
self.most_recently_used
}
/// The id following `id` towards the least-recently-used end, if any.
pub fn next(&self, id: NodeId) -> Option<NodeId> {
self.nodes.get(&id).and_then(|n| n.next)
}
/// The id preceding `id` towards the most-recently-used end, if any.
pub fn prev(&self, id: NodeId) -> Option<NodeId> {
self.nodes.get(&id).and_then(|n| n.prev)
}
/// The entry ids in most-recently-used to least-recently-used order.
pub fn order_mru_to_lru(&self) -> Vec<NodeId> {
let mut out = Vec::with_capacity(self.nodes.len());
let mut cur = self.most_recently_used;
while let Some(id) = cur {
out.push(id);
cur = self.nodes.get(&id).and_then(|n| n.next);
}
out
}
/// Insert a brand-new entry at the most-recently-used position.
///
/// The caller must ensure `id` is not already present (use
/// [`LruOrder::touch`] / [`LruOrder::update_size`] for existing ids).
pub fn insert(&mut self, id: NodeId, size: usize) {
debug_assert!(!self.nodes.contains_key(&id));
self.nodes.insert(
id,
Node {
prev: None,
next: None,
size,
},
);
self.total_size += size;
self.move_to_front(id);
}
/// Update the recorded size of an existing entry, adjusting the total.
pub fn update_size(&mut self, id: NodeId, size: usize) {
if let Some(node) = self.nodes.get_mut(&id) {
self.total_size -= node.size;
node.size = size;
self.total_size += size;
}
}
/// Mark an existing entry as most-recently-used. No-op for unknown ids.
pub fn touch(&mut self, id: NodeId) {
if self.nodes.contains_key(&id) {
self.move_to_front(id);
}
}
/// Remove an entry, returning its recorded size. No-op (returns `None`)
/// for unknown ids.
pub fn remove(&mut self, id: NodeId) -> Option<usize> {
let node = self.nodes.remove(&id)?;
let (prev, next, size) = (node.prev, node.next, node.size);
match prev {
Some(p) => {
if let Some(pn) = self.nodes.get_mut(&p) {
pn.next = next;
}
}
None => self.most_recently_used = next,
}
match next {
Some(n) => {
if let Some(nn) = self.nodes.get_mut(&n) {
nn.prev = prev;
}
}
None => self.least_recently_used = prev,
}
self.total_size -= size;
Some(size)
}
/// Evict least-recently-used entries until `total_size <=
/// after_cleanup`, returning the evicted ids in eviction (LRU-first)
/// order. Mirrors `LRUCache.cleanup` / `LRUSizeCache.cleanup`.
pub fn evict_until(&mut self, after_cleanup: usize) -> Vec<NodeId> {
let mut evicted = Vec::new();
while self.total_size > after_cleanup {
match self.least_recently_used {
Some(id) => {
self.remove(id);
evicted.push(id);
}
None => break,
}
}
evicted
}
/// Remove every entry, returning the ids in LRU-first order (the order
/// `LRUCache.clear` removes them in).
pub fn drain_lru(&mut self) -> Vec<NodeId> {
let mut out = Vec::new();
while let Some(id) = self.least_recently_used {
self.remove(id);
out.push(id);
}
out
}
/// Unlink `id` from its current position and splice it in at the head.
fn move_to_front(&mut self, id: NodeId) {
if self.most_recently_used == Some(id) {
return;
}
// Unlink from current position (if it is currently linked).
let (prev, next) = {
let node = &self.nodes[&id];
(node.prev, node.next)
};
if let Some(p) = prev {
if let Some(pn) = self.nodes.get_mut(&p) {
pn.next = next;
}
}
if let Some(n) = next {
if let Some(nn) = self.nodes.get_mut(&n) {
nn.prev = prev;
}
}
if self.least_recently_used == Some(id) {
self.least_recently_used = prev;
}
// Splice in at the head.
let old_head = self.most_recently_used;
{
let node = self.nodes.get_mut(&id).unwrap();
node.prev = None;
node.next = old_head;
}
if let Some(h) = old_head {
if let Some(hn) = self.nodes.get_mut(&h) {
hn.prev = Some(id);
}
}
self.most_recently_used = Some(id);
if self.least_recently_used.is_none() {
self.least_recently_used = Some(id);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert_and_order() {
let mut o = LruOrder::new();
o.insert(1, 1);
o.insert(2, 1);
o.insert(3, 1);
assert_eq!(o.len(), 3);
// LRU is the first inserted.
assert_eq!(o.lru(), Some(1));
// Touch 1 -> it is no longer LRU.
o.touch(1);
assert_eq!(o.lru(), Some(2));
}
#[test]
fn evict_until_size() {
let mut o = LruOrder::new();
o.insert(1, 5);
o.insert(2, 6);
o.insert(3, 7);
assert_eq!(o.total_size(), 18);
o.touch(2); // make 2 newer than 1 and 3? no: order is 3(mru),2,1(lru) after touch
// order now: 2, 3, 1 (lru)
let evicted = o.evict_until(10);
// remove LRU-first until <= 10: remove 1 (size5 ->13), remove 3 (->? )
assert!(o.total_size() <= 10);
assert!(!evicted.is_empty());
}
#[test]
fn remove_adjusts_size_and_links() {
let mut o = LruOrder::new();
o.insert(10, 13);
assert_eq!(o.total_size(), 13);
assert_eq!(o.remove(10), Some(13));
assert_eq!(o.total_size(), 0);
assert!(o.is_empty());
assert_eq!(o.lru(), None);
}
#[test]
fn update_size_tracks_total() {
let mut o = LruOrder::new();
o.insert(1, 3);
o.update_size(1, 8);
assert_eq!(o.total_size(), 8);
}
#[test]
fn drain_lru_order() {
let mut o = LruOrder::new();
o.insert(1, 1);
o.insert(2, 1);
o.insert(3, 1);
// LRU-first: 1, 2, 3
assert_eq!(o.drain_lru(), vec![1, 2, 3]);
assert!(o.is_empty());
}
#[test]
fn mru_tracks_most_recent_insert() {
let mut o = LruOrder::new();
assert_eq!(o.mru(), None);
o.insert(1, 1);
o.insert(2, 1);
assert_eq!(o.mru(), Some(2));
o.touch(1);
assert_eq!(o.mru(), Some(1));
}
#[test]
fn order_mru_to_lru_lists_all_entries() {
let mut o = LruOrder::new();
o.insert(1, 1);
o.insert(2, 1);
o.insert(3, 1);
// Most recently inserted first.
assert_eq!(o.order_mru_to_lru(), vec![3, 2, 1]);
o.touch(1);
assert_eq!(o.order_mru_to_lru(), vec![1, 3, 2]);
}
#[test]
fn next_and_prev_walk_the_chain() {
let mut o = LruOrder::new();
o.insert(1, 1);
o.insert(2, 1);
o.insert(3, 1);
// Chain MRU->LRU is 3, 2, 1.
assert_eq!(o.next(3), Some(2));
assert_eq!(o.next(2), Some(1));
assert_eq!(o.next(1), None);
assert_eq!(o.prev(1), Some(2));
assert_eq!(o.prev(2), Some(3));
assert_eq!(o.prev(3), None);
// Unknown ids have no neighbours.
assert_eq!(o.next(99), None);
assert_eq!(o.prev(99), None);
}
#[test]
fn contains_reflects_membership() {
let mut o = LruOrder::new();
o.insert(7, 1);
assert!(o.contains(7));
assert!(!o.contains(8));
o.remove(7);
assert!(!o.contains(7));
}
#[test]
fn update_size_unknown_id_is_noop() {
let mut o = LruOrder::new();
o.insert(1, 4);
o.update_size(99, 100);
assert_eq!(o.total_size(), 4);
}
#[test]
fn touch_unknown_id_is_noop() {
let mut o = LruOrder::new();
o.insert(1, 1);
o.insert(2, 1);
o.touch(99);
// Order unchanged: 2 is still MRU, 1 still LRU.
assert_eq!(o.mru(), Some(2));
assert_eq!(o.lru(), Some(1));
}
#[test]
fn remove_unknown_id_returns_none() {
let mut o = LruOrder::new();
o.insert(1, 5);
assert_eq!(o.remove(99), None);
assert_eq!(o.total_size(), 5);
assert_eq!(o.len(), 1);
}
#[test]
fn evict_until_removes_exact_lru_entries() {
let mut o = LruOrder::new();
o.insert(1, 5);
o.insert(2, 6);
o.insert(3, 7);
// Order MRU->LRU is 3, 2, 1. Evict until total_size <= 10:
// remove 1 (->13), remove 2 (->7). 3 stays.
let evicted = o.evict_until(10);
assert_eq!(evicted, vec![1, 2]);
assert_eq!(o.total_size(), 7);
assert_eq!(o.order_mru_to_lru(), vec![3]);
}
#[test]
fn evict_until_already_under_target_removes_nothing() {
let mut o = LruOrder::new();
o.insert(1, 3);
let evicted = o.evict_until(10);
assert!(evicted.is_empty());
assert_eq!(o.total_size(), 3);
}
#[test]
fn update_size_then_evict_uses_new_size() {
let mut o = LruOrder::new();
o.insert(1, 1);
o.update_size(1, 9);
assert_eq!(o.total_size(), 9);
let evicted = o.evict_until(5);
assert_eq!(evicted, vec![1]);
assert!(o.is_empty());
}
}