Skip to main content

reth_lru/
lib.rs

1//! A length-limited LRU map tailored to reth's caches.
2//!
3//! Entries live in a `Vec` of nodes that form a doubly linked list from most to least recently
4//! used. A [`HashTable`] maps keys to node indices, so hashbrown can grow or rehash it freely
5//! without invalidating the links. Nodes freed by removals are reused by later inserts, and the
6//! node `Vec` never grows past the length limit.
7//!
8//! Insertions that evict return the evicted entry, so callers that need eviction feedback don't
9//! need a second lookup.
10
11#![doc(
12    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
13    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
14    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
15)]
16#![cfg_attr(not(test), warn(unused_crate_dependencies))]
17#![cfg_attr(docsrs, feature(doc_cfg))]
18#![no_std]
19
20extern crate alloc;
21
22use alloc::vec::Vec;
23use alloy_primitives::map::DefaultHashBuilder;
24use core::{
25    borrow::Borrow,
26    fmt,
27    hash::{BuildHasher, Hash},
28    iter::FusedIterator,
29    mem::{self, MaybeUninit},
30};
31use hashbrown::HashTable;
32
33/// Marks the end of the list and an empty free list.
34const NONE: u32 = u32::MAX;
35
36/// Hash table capacity per node slot.
37///
38/// The table holds only `u32` indices, so a sparse table costs a few bytes per entry and keeps
39/// probe sequences short and tombstone rehashes rare under eviction churn.
40const TABLE_SLACK: usize = 2;
41
42/// A hash map holding at most `max_length` entries that evicts the least recently used entry.
43///
44/// [`get`](Self::get) and the insert methods mark an entry as most recently used, the `peek`
45/// methods don't.
46pub struct LruMap<K, V, S = DefaultHashBuilder> {
47    /// Indices of the linked nodes, keyed by the hash of their key.
48    table: HashTable<u32>,
49    nodes: Vec<Node<K, V>>,
50    hasher: S,
51    max_length: u32,
52    len: u32,
53    newest: u32,
54    oldest: u32,
55    /// Head of the vacant nodes, chained through [`Node::newer`].
56    free: u32,
57}
58
59impl<K, V> LruMap<K, V> {
60    /// Creates an empty map that holds at most `max_length` entries, using the default hasher.
61    /// Does not allocate.
62    pub fn new(max_length: u32) -> Self {
63        Self::with_hasher(max_length, DefaultHashBuilder::default())
64    }
65}
66
67impl<K, V, S> LruMap<K, V, S> {
68    /// Creates an empty map that holds at most `max_length` entries, using `hasher` to hash keys.
69    /// Does not allocate.
70    pub const fn with_hasher(max_length: u32, hasher: S) -> Self {
71        Self {
72            table: HashTable::new(),
73            nodes: Vec::new(),
74            hasher,
75            max_length,
76            len: 0,
77            newest: NONE,
78            oldest: NONE,
79            free: NONE,
80        }
81    }
82
83    /// Returns the maximum number of entries.
84    pub const fn max_length(&self) -> u32 {
85        self.max_length
86    }
87
88    /// Returns the number of entries.
89    pub const fn len(&self) -> usize {
90        self.len as usize
91    }
92
93    /// Returns `true` if the map holds no entries.
94    pub const fn is_empty(&self) -> bool {
95        self.len == 0
96    }
97
98    /// Returns the number of heap bytes allocated by the map, excluding heap memory owned by keys
99    /// and values.
100    pub fn memory_usage(&self) -> usize {
101        self.table.allocation_size() + self.nodes.capacity() * size_of::<Node<K, V>>()
102    }
103
104    /// Returns the least recently used entry without changing its position.
105    pub fn peek_oldest(&self) -> Option<(&K, &V)> {
106        (self.oldest != NONE).then(|| self.entry(self.oldest))
107    }
108
109    /// Returns the most recently used entry without changing its position.
110    pub fn peek_newest(&self) -> Option<(&K, &V)> {
111        (self.newest != NONE).then(|| self.entry(self.newest))
112    }
113
114    /// Iterates from the most to the least recently used entry.
115    pub const fn iter(&self) -> Iter<'_, K, V, S> {
116        Iter { map: self, next: self.newest, remaining: self.len() }
117    }
118
119    /// Removes all entries, keeping the allocated memory.
120    pub fn clear(&mut self) {
121        self.table.clear();
122        let newest = mem::replace(&mut self.newest, NONE);
123        self.oldest = NONE;
124        self.free = NONE;
125        self.len = 0;
126        // The map is empty before any entry is dropped, so a panicking drop only leaks the rest.
127        let mut nodes = mem::take(&mut self.nodes);
128        drop_linked(&mut nodes, newest);
129        nodes.clear();
130        self.nodes = nodes;
131    }
132
133    #[inline]
134    fn node(&self, index: u32) -> &Node<K, V> {
135        debug_assert!((index as usize) < self.nodes.len());
136        // SAFETY: indices stored in the table, the list and the free list are always in bounds.
137        unsafe { self.nodes.get_unchecked(index as usize) }
138    }
139
140    #[inline]
141    fn node_mut(&mut self, index: u32) -> &mut Node<K, V> {
142        debug_assert!((index as usize) < self.nodes.len());
143        // SAFETY: see `node`.
144        unsafe { self.nodes.get_unchecked_mut(index as usize) }
145    }
146
147    /// Returns the entry of the linked node at `index`.
148    #[inline]
149    fn entry(&self, index: u32) -> (&K, &V) {
150        let node = self.node(index);
151        // SAFETY: linked nodes are initialized.
152        unsafe { (node.key.assume_init_ref(), node.value.assume_init_ref()) }
153    }
154
155    #[inline]
156    fn unlink(&mut self, index: u32) {
157        let Node { older, newer, .. } = *self.node(index);
158        if older == NONE {
159            self.oldest = newer
160        } else {
161            self.node_mut(older).newer = newer
162        }
163        if newer == NONE {
164            self.newest = older
165        } else {
166            self.node_mut(newer).older = older
167        }
168    }
169
170    #[inline]
171    fn link_newest(&mut self, index: u32) {
172        let prev = self.newest;
173        let node = self.node_mut(index);
174        node.older = prev;
175        node.newer = NONE;
176        if prev == NONE {
177            self.oldest = index
178        } else {
179            self.node_mut(prev).newer = index
180        }
181        self.newest = index;
182    }
183
184    #[inline]
185    fn promote(&mut self, index: u32) {
186        if self.newest != index {
187            self.unlink(index);
188            self.link_newest(index);
189        }
190    }
191}
192
193impl<K, V, S> LruMap<K, V, S>
194where
195    K: Hash + Eq,
196    S: BuildHasher,
197{
198    /// Returns the value for `key` and marks it as the most recently used.
199    #[inline]
200    pub fn get<Q>(&mut self, key: &Q) -> Option<&mut V>
201    where
202        K: Borrow<Q>,
203        Q: Hash + Eq + ?Sized,
204    {
205        let index = self.find(key)?;
206        self.promote(index);
207        // SAFETY: `find` only returns linked nodes, which are initialized.
208        Some(unsafe { self.node_mut(index).value.assume_init_mut() })
209    }
210
211    /// Returns the value for `key` without changing its position.
212    #[inline]
213    pub fn peek<Q>(&self, key: &Q) -> Option<&V>
214    where
215        K: Borrow<Q>,
216        Q: Hash + Eq + ?Sized,
217    {
218        self.find(key).map(|index| self.entry(index).1)
219    }
220
221    /// Returns a mutable reference to the value for `key` without changing its position.
222    #[inline]
223    pub fn peek_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
224    where
225        K: Borrow<Q>,
226        Q: Hash + Eq + ?Sized,
227    {
228        let index = self.find(key)?;
229        // SAFETY: `find` only returns linked nodes, which are initialized.
230        Some(unsafe { self.node_mut(index).value.assume_init_mut() })
231    }
232
233    /// Returns `true` if the map contains `key`, without changing its position.
234    #[inline]
235    pub fn contains<Q>(&self, key: &Q) -> bool
236    where
237        K: Borrow<Q>,
238        Q: Hash + Eq + ?Sized,
239    {
240        self.find(key).is_some()
241    }
242
243    /// Inserts `value` for `key`, or replaces the current value, and marks `key` as the most
244    /// recently used.
245    ///
246    /// Returns the least recently used entry if it was evicted to make room. If `max_length` is
247    /// zero, nothing is stored and the given entry is returned instead.
248    #[inline]
249    pub fn insert(&mut self, key: K, value: V) -> Option<(K, V)> {
250        let hash = self.hasher.hash_one(&key);
251        if let Some(index) = self.find_hashed(hash, &key) {
252            self.promote(index);
253            // SAFETY: `find_hashed` only returns linked nodes, which are initialized.
254            *unsafe { self.node_mut(index).value.assume_init_mut() } = value;
255            return None
256        }
257        self.insert_new(hash, key, value).1
258    }
259
260    /// Returns the value for `key` and marks it as the most recently used, first inserting the
261    /// value returned by `f` if `key` is absent.
262    ///
263    /// Returns `None` only if `max_length` is zero.
264    #[inline]
265    pub fn get_or_insert(&mut self, key: K, f: impl FnOnce() -> V) -> Option<&mut V> {
266        let hash = self.hasher.hash_one(&key);
267        let index = if let Some(index) = self.find_hashed(hash, &key) {
268            self.promote(index);
269            index
270        } else {
271            let index = self.insert_new(hash, key, f()).0;
272            if index == NONE {
273                return None
274            }
275            index
276        };
277        // SAFETY: both branches yield a linked node, which is initialized.
278        Some(unsafe { self.node_mut(index).value.assume_init_mut() })
279    }
280
281    /// Removes `key` and returns its value.
282    #[inline]
283    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
284    where
285        K: Borrow<Q>,
286        Q: Hash + Eq + ?Sized,
287    {
288        let index = self.find(key)?;
289        Some(self.take(index).1)
290    }
291
292    /// Removes and returns the least recently used entry.
293    #[inline]
294    pub fn pop_oldest(&mut self) -> Option<(K, V)> {
295        (self.oldest != NONE).then(|| self.take(self.oldest))
296    }
297
298    /// Removes the entries for which `f` returns `false`.
299    ///
300    /// `f` is called once for each entry, from the most to the least recently used one, and can
301    /// change the value. The entries that stay keep their order, and no entry is marked as used.
302    pub fn retain(&mut self, mut f: impl FnMut(&K, &mut V) -> bool) {
303        let mut index = self.newest;
304        while index != NONE {
305            let node = self.node_mut(index);
306            let older = node.older;
307            // SAFETY: linked nodes are initialized.
308            let (key, value) =
309                unsafe { (node.key.assume_init_ref(), node.value.assume_init_mut()) };
310            if !f(key, value) {
311                self.take(index);
312            }
313            index = older;
314        }
315    }
316
317    #[inline]
318    fn find<Q>(&self, key: &Q) -> Option<u32>
319    where
320        K: Borrow<Q>,
321        Q: Hash + Eq + ?Sized,
322    {
323        self.find_hashed(self.hasher.hash_one(key), key)
324    }
325
326    #[inline]
327    fn find_hashed<Q>(&self, hash: u64, key: &Q) -> Option<u32>
328    where
329        K: Borrow<Q>,
330        Q: Hash + Eq + ?Sized,
331    {
332        let nodes = &self.nodes;
333        self.table
334            .find(hash, |&index| {
335                // SAFETY: the table only holds indices of linked nodes, which are initialized.
336                let node = unsafe { nodes.get_unchecked(index as usize) };
337                unsafe { node.key.assume_init_ref() }.borrow() == key
338            })
339            .copied()
340    }
341
342    /// Removes the linked node at `index` from the table, list and length, moves its entry out
343    /// and puts the node on the free list.
344    fn take(&mut self, index: u32) -> (K, V) {
345        // Hashing may panic, so it happens before any state changes.
346        // SAFETY: the node is linked, so its key is initialized.
347        let hash = self.hasher.hash_one(unsafe { self.node(index).key.assume_init_ref() });
348        match self.table.find_entry(hash, |&i| i == index) {
349            Ok(slot) => {
350                slot.remove();
351            }
352            // Only reachable with a `Hash` impl that is not deterministic. The table must never
353            // point at a vacant node, so fall back to a full scan.
354            Err(_) => self.table.retain(|&mut i| i != index),
355        }
356        self.unlink(index);
357        let free = self.free;
358        let node = self.node_mut(index);
359        node.newer = free;
360        // SAFETY: the node was linked, so both are initialized. It is vacant from here on.
361        let entry = unsafe { (node.key.assume_init_read(), node.value.assume_init_read()) };
362        self.free = index;
363        self.len -= 1;
364        entry
365    }
366
367    /// Inserts an absent key, evicting the oldest entry if the map is full.
368    ///
369    /// Returns the index of the new node, or [`NONE`] with the given entry if `max_length` is
370    /// zero, and the evicted entry.
371    ///
372    /// Every linked node is initialized and counted in `len` whenever user code (hashing,
373    /// equality, drops) can panic. The table may then miss an index, which only causes lookup
374    /// misses, but never holds the index of a vacant node.
375    fn insert_new(&mut self, hash: u64, key: K, value: V) -> (u32, Option<(K, V)>) {
376        if self.max_length == 0 {
377            return (NONE, Some((key, value)))
378        }
379        let evicted = (self.len >= self.max_length).then(|| self.take(self.oldest));
380        let index = if self.free == NONE {
381            if self.nodes.len() == self.nodes.capacity() {
382                self.grow();
383            }
384            self.nodes.push(Node {
385                key: MaybeUninit::new(key),
386                value: MaybeUninit::new(value),
387                older: NONE,
388                newer: NONE,
389            });
390            self.nodes.len() as u32 - 1
391        } else {
392            let index = self.free;
393            let node = self.node_mut(index);
394            let next = node.newer;
395            node.key.write(key);
396            node.value.write(value);
397            self.free = next;
398            index
399        };
400        self.link_newest(index);
401        self.len += 1;
402        let (nodes, hasher) = (&self.nodes, &self.hasher);
403        self.table.insert_unique(hash, index, |&i| hash_node(hasher, nodes, i));
404        (index, evicted)
405    }
406
407    /// Grows the node `Vec` geometrically up to `max_length` and keeps the table sparse.
408    #[cold]
409    fn grow(&mut self) {
410        let target =
411            (self.nodes.len() * 2).clamp(4.min(self.max_length as usize), self.max_length as usize);
412        self.nodes.reserve_exact(target - self.nodes.len());
413        let (nodes, hasher) = (&self.nodes, &self.hasher);
414        let additional = target.saturating_mul(TABLE_SLACK).saturating_sub(self.table.len());
415        self.table.reserve(additional, |&i| hash_node(hasher, nodes, i));
416    }
417}
418
419impl<K, V, S: Default> Default for LruMap<K, V, S> {
420    /// Returns an empty map with `max_length` zero, which stores nothing.
421    fn default() -> Self {
422        Self::with_hasher(0, S::default())
423    }
424}
425
426impl<K, V, S> Drop for LruMap<K, V, S> {
427    fn drop(&mut self) {
428        drop_linked(&mut self.nodes, self.newest);
429    }
430}
431
432impl<K, V, S> fmt::Debug for LruMap<K, V, S> {
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        f.debug_struct("LruMap")
435            .field("len", &self.len)
436            .field("max_length", &self.max_length)
437            .finish_non_exhaustive()
438    }
439}
440
441impl<'a, K, V, S> IntoIterator for &'a LruMap<K, V, S> {
442    type Item = (&'a K, &'a V);
443    type IntoIter = Iter<'a, K, V, S>;
444
445    fn into_iter(self) -> Self::IntoIter {
446        self.iter()
447    }
448}
449
450/// Iterator over the entries of an [`LruMap`], from most to least recently used.
451#[derive(Debug)]
452pub struct Iter<'a, K, V, S> {
453    map: &'a LruMap<K, V, S>,
454    next: u32,
455    remaining: usize,
456}
457
458impl<'a, K, V, S> Iterator for Iter<'a, K, V, S> {
459    type Item = (&'a K, &'a V);
460
461    fn next(&mut self) -> Option<Self::Item> {
462        if self.next == NONE {
463            return None
464        }
465        let map = self.map;
466        let entry = map.entry(self.next);
467        self.next = map.node(self.next).older;
468        self.remaining -= 1;
469        Some(entry)
470    }
471
472    fn size_hint(&self) -> (usize, Option<usize>) {
473        (self.remaining, Some(self.remaining))
474    }
475}
476
477impl<K, V, S> ExactSizeIterator for Iter<'_, K, V, S> {}
478
479impl<K, V, S> FusedIterator for Iter<'_, K, V, S> {}
480
481/// A list node. `key` and `value` are initialized iff the node is linked into the LRU list.
482struct Node<K, V> {
483    key: MaybeUninit<K>,
484    value: MaybeUninit<V>,
485    /// Next less recently used node, or [`NONE`].
486    older: u32,
487    /// Next more recently used node, or the next vacant node for vacant nodes, or [`NONE`].
488    newer: u32,
489}
490
491/// Drops the entries of the list starting at `newest`.
492///
493/// Callers must not treat these nodes as linked afterwards.
494fn drop_linked<K, V>(nodes: &mut [Node<K, V>], newest: u32) {
495    if !mem::needs_drop::<(K, V)>() {
496        return
497    }
498    let mut index = newest;
499    while index != NONE {
500        let node = &mut nodes[index as usize];
501        index = node.older;
502        // SAFETY: linked nodes are initialized, and the caller stops treating them as linked, so
503        // each is dropped exactly once.
504        unsafe {
505            node.key.assume_init_drop();
506            node.value.assume_init_drop();
507        }
508    }
509}
510
511/// Hashes the key of the linked node at `index`, for rehashing the table.
512#[inline]
513fn hash_node<K: Hash, V, S: BuildHasher>(hasher: &S, nodes: &[Node<K, V>], index: u32) -> u64 {
514    // SAFETY: the table only holds indices of linked nodes, which are initialized.
515    hasher.hash_one(unsafe { nodes.get_unchecked(index as usize).key.assume_init_ref() })
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521    use alloc::{
522        string::{String, ToString},
523        sync::Arc,
524        vec,
525    };
526
527    fn keys<K: Copy, V, S>(map: &LruMap<K, V, S>) -> Vec<K> {
528        map.iter().map(|(k, _)| *k).collect()
529    }
530
531    #[test]
532    fn evicts_least_recently_used() {
533        let mut map = LruMap::<u64, u64>::new(3);
534        assert_eq!(map.insert(1, 10), None);
535        assert_eq!(map.insert(2, 20), None);
536        assert_eq!(map.insert(3, 30), None);
537        assert_eq!(map.get(&1), Some(&mut 10));
538        assert_eq!(map.peek(&2), Some(&20));
539        assert_eq!(map.insert(4, 40), Some((2, 20)));
540        assert_eq!(keys(&map), [4, 1, 3]);
541        assert_eq!(map.peek_oldest(), Some((&3, &30)));
542        assert_eq!(map.peek_newest(), Some((&4, &40)));
543        assert_eq!(map.insert(3, 31), None);
544        assert_eq!(keys(&map), [3, 4, 1]);
545        assert_eq!(map.remove(&4), Some(40));
546        assert_eq!(map.get_or_insert(5, || 50), Some(&mut 50));
547        assert_eq!(map.get_or_insert(1, || 0), Some(&mut 10));
548        assert_eq!(keys(&map), [1, 5, 3]);
549        assert_eq!(map.pop_oldest(), Some((3, 31)));
550        assert_eq!(map.len(), 2);
551        assert_eq!(map.iter().len(), 2);
552        map.retain(|key, value| {
553            *value += 1;
554            *key != 5
555        });
556        assert_eq!(keys(&map), [1]);
557        assert_eq!(map.peek(&1), Some(&11));
558    }
559
560    #[test]
561    fn zero_length_stores_nothing() {
562        let mut map = LruMap::<u64, u64>::default();
563        assert_eq!(map.insert(1, 1), Some((1, 1)));
564        assert_eq!(map.get_or_insert(1, || 1), None);
565        assert!(map.is_empty());
566        assert_eq!(map.memory_usage(), 0);
567    }
568
569    #[test]
570    fn borrowed_lookups() {
571        let mut map = LruMap::<String, u64>::new(2);
572        map.insert("a".to_string(), 1);
573        assert_eq!(map.get("a"), Some(&mut 1));
574        assert!(map.contains("a"));
575        assert_eq!(map.peek_mut("a"), Some(&mut 1));
576        assert_eq!(map.remove("a"), Some(1));
577        assert!(!map.contains("a"));
578    }
579
580    #[test]
581    fn never_grows_past_max_length() {
582        let mut map = LruMap::<u64, ()>::new(5);
583        for i in 0..100 {
584            map.insert(i, ());
585            if i % 7 == 6 {
586                map.remove(&(i - 1));
587            }
588        }
589        assert_eq!(map.nodes.capacity(), 5);
590        assert_eq!(map.len(), 5);
591    }
592
593    /// Every value is dropped exactly once across evictions, removals, replacements, retains,
594    /// clears and drop.
595    #[test]
596    fn drops_each_value_once() {
597        let token = Arc::new(());
598        {
599            let mut map = LruMap::<u64, Arc<()>>::new(4);
600            for i in 0..64u64 {
601                map.insert(i % 9, Arc::clone(&token));
602                if i % 3 == 0 {
603                    map.remove(&(i % 7));
604                }
605                if i % 5 == 0 {
606                    map.pop_oldest();
607                }
608                if i % 4 == 0 {
609                    map.retain(|key, _| key % 2 == 0);
610                }
611                map.get_or_insert(i % 11, || Arc::clone(&token));
612                assert_eq!(Arc::strong_count(&token), 1 + map.len());
613                if i == 32 {
614                    map.clear();
615                    assert_eq!(Arc::strong_count(&token), 1);
616                }
617            }
618        }
619        assert_eq!(Arc::strong_count(&token), 1);
620    }
621
622    /// Replays a random trace against a `Vec` model, newest first.
623    #[test]
624    fn matches_model() {
625        let steps = if cfg!(miri) { 2_000 } else { 100_000 };
626        for max_length in [1u32, 2, 3, 7, 64, 333] {
627            let mut map = LruMap::<u64, u64>::new(max_length);
628            let mut model: Vec<(u64, u64)> = vec![];
629            let mut x = 0x9e37_79b9_7f4a_7c15u64;
630            for step in 0..steps {
631                x ^= x << 13;
632                x ^= x >> 7;
633                x ^= x << 17;
634                let key = x % (max_length as u64 * 3 + 1);
635                let position = model.iter().position(|e| e.0 == key);
636                match x >> 61 {
637                    0..=2 => {
638                        let expected = match position {
639                            Some(p) => {
640                                model.remove(p);
641                                None
642                            }
643                            None if model.len() == max_length as usize => model.pop(),
644                            None => None,
645                        };
646                        model.insert(0, (key, step));
647                        assert_eq!(map.insert(key, step), expected);
648                    }
649                    3 | 4 => {
650                        let expected = position.map(|p| {
651                            let entry = model.remove(p);
652                            model.insert(0, entry);
653                            entry.1
654                        });
655                        assert_eq!(map.get(&key).copied(), expected);
656                    }
657                    5 => assert_eq!(map.remove(&key), position.map(|p| model.remove(p).1)),
658                    6 => assert_eq!(map.pop_oldest(), model.pop()),
659                    _ => assert_eq!(map.peek(&key).copied(), position.map(|p| model[p].1)),
660                }
661                if step % 1013 == 0 {
662                    let keep = |entry: (u64, u64)| entry.0 % 3 != key % 3;
663                    model.retain_mut(|entry| {
664                        entry.1 += 1;
665                        keep(*entry)
666                    });
667                    map.retain(|k, v| {
668                        *v += 1;
669                        keep((*k, *v))
670                    });
671                    assert_eq!(map.iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>(), model);
672                }
673                assert_eq!(map.len(), model.len());
674                if step % 997 == 0 {
675                    assert_eq!(map.iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>(), model);
676                }
677            }
678        }
679    }
680}