|
| 1 | +use lru::LruCache; |
| 2 | +use std::borrow::Borrow; |
| 3 | +use std::fmt; |
| 4 | +use std::hash::Hash; |
| 5 | +use std::num::NonZeroUsize; |
| 6 | + |
| 7 | +/// An LRU cache that allocates its backing storage on first insertion. |
| 8 | +/// |
| 9 | +/// `lru::LruCache::new(capacity)` reserves the full configured capacity. |
| 10 | +/// Template parsers own several independent caches, most of which remain unused |
| 11 | +/// for a given exporter. This wrapper retains the same capacity and eviction |
| 12 | +/// semantics without reserving memory for empty caches. |
| 13 | +pub(crate) struct LazyLruCache<K: Hash + Eq, V> { |
| 14 | + capacity: NonZeroUsize, |
| 15 | + cache: Option<LruCache<K, V>>, |
| 16 | +} |
| 17 | + |
| 18 | +impl<K: Hash + Eq, V> fmt::Debug for LazyLruCache<K, V> { |
| 19 | + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 20 | + // Preserve the parser's existing debug representation. |
| 21 | + formatter |
| 22 | + .debug_struct("LruCache") |
| 23 | + .field("len", &self.len()) |
| 24 | + .field("cap", &self.capacity) |
| 25 | + .finish() |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +impl<K: Hash + Eq, V> LazyLruCache<K, V> { |
| 30 | + pub(crate) fn new(capacity: NonZeroUsize) -> Self { |
| 31 | + Self { |
| 32 | + capacity, |
| 33 | + cache: None, |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + fn cache_mut(&mut self) -> &mut LruCache<K, V> { |
| 38 | + let capacity = self.capacity; |
| 39 | + self.cache.get_or_insert_with(|| { |
| 40 | + // `unbounded()` starts with an empty hash map. Resizing it before |
| 41 | + // the first insertion sets the eviction limit without reserving |
| 42 | + // storage for every possible entry. |
| 43 | + let mut cache = LruCache::unbounded(); |
| 44 | + cache.resize(capacity); |
| 45 | + cache |
| 46 | + }) |
| 47 | + } |
| 48 | + |
| 49 | + fn release_if_empty(&mut self) { |
| 50 | + if self.cache.as_ref().is_some_and(LruCache::is_empty) { |
| 51 | + self.cache = None; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + pub(crate) fn push(&mut self, key: K, value: V) -> Option<(K, V)> { |
| 56 | + self.cache_mut().push(key, value) |
| 57 | + } |
| 58 | + |
| 59 | + #[cfg(test)] |
| 60 | + pub(crate) fn put(&mut self, key: K, value: V) -> Option<V> { |
| 61 | + self.cache_mut().put(key, value) |
| 62 | + } |
| 63 | + |
| 64 | + pub(crate) fn peek<Q>(&self, key: &Q) -> Option<&V> |
| 65 | + where |
| 66 | + K: Borrow<Q>, |
| 67 | + Q: Hash + Eq + ?Sized, |
| 68 | + { |
| 69 | + self.cache.as_ref()?.peek(key) |
| 70 | + } |
| 71 | + |
| 72 | + pub(crate) fn pop<Q>(&mut self, key: &Q) -> Option<V> |
| 73 | + where |
| 74 | + K: Borrow<Q>, |
| 75 | + Q: Hash + Eq + ?Sized, |
| 76 | + { |
| 77 | + let value = self.cache.as_mut()?.pop(key); |
| 78 | + self.release_if_empty(); |
| 79 | + value |
| 80 | + } |
| 81 | + |
| 82 | + pub(crate) fn promote<Q>(&mut self, key: &Q) -> bool |
| 83 | + where |
| 84 | + K: Borrow<Q>, |
| 85 | + Q: Hash + Eq + ?Sized, |
| 86 | + { |
| 87 | + self.cache.as_mut().is_some_and(|cache| cache.promote(key)) |
| 88 | + } |
| 89 | + |
| 90 | + pub(crate) fn resize(&mut self, capacity: NonZeroUsize) { |
| 91 | + self.capacity = capacity; |
| 92 | + if let Some(cache) = self.cache.as_mut() { |
| 93 | + cache.resize(capacity); |
| 94 | + } |
| 95 | + self.release_if_empty(); |
| 96 | + } |
| 97 | + |
| 98 | + pub(crate) fn clear(&mut self) { |
| 99 | + self.cache = None; |
| 100 | + } |
| 101 | + |
| 102 | + pub(crate) fn len(&self) -> usize { |
| 103 | + self.cache.as_ref().map_or(0, LruCache::len) |
| 104 | + } |
| 105 | + |
| 106 | + #[cfg(test)] |
| 107 | + pub(crate) fn cap(&self) -> NonZeroUsize { |
| 108 | + self.capacity |
| 109 | + } |
| 110 | + |
| 111 | + pub(crate) fn iter(&self) -> impl Iterator<Item = (&K, &V)> { |
| 112 | + self.cache.iter().flat_map(|cache| cache.iter()) |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +#[cfg(test)] |
| 117 | +mod tests { |
| 118 | + use super::*; |
| 119 | + |
| 120 | + #[test] |
| 121 | + fn reads_and_resizes_do_not_allocate_an_empty_cache() { |
| 122 | + let mut cache = LazyLruCache::<u16, u16>::new(NonZeroUsize::new(10).unwrap()); |
| 123 | + |
| 124 | + assert!(cache.cache.is_none()); |
| 125 | + assert_eq!(cache.cap().get(), 10); |
| 126 | + assert_eq!(cache.len(), 0); |
| 127 | + assert_eq!(cache.peek(&1), None); |
| 128 | + assert!(!cache.promote(&1)); |
| 129 | + assert_eq!(cache.pop(&1), None); |
| 130 | + assert_eq!(cache.iter().count(), 0); |
| 131 | + |
| 132 | + cache.resize(NonZeroUsize::new(20).unwrap()); |
| 133 | + assert!(cache.cache.is_none()); |
| 134 | + assert_eq!(cache.cap().get(), 20); |
| 135 | + } |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn first_insert_allocates_and_preserves_lru_eviction() { |
| 139 | + let mut cache = LazyLruCache::new(NonZeroUsize::new(2).unwrap()); |
| 140 | + |
| 141 | + assert_eq!(cache.push(1, "one"), None); |
| 142 | + assert!(cache.cache.is_some()); |
| 143 | + assert_eq!(cache.push(2, "two"), None); |
| 144 | + assert!(cache.promote(&1)); |
| 145 | + assert_eq!(cache.push(3, "three"), Some((2, "two"))); |
| 146 | + assert_eq!(cache.peek(&1), Some(&"one")); |
| 147 | + assert_eq!(cache.peek(&2), None); |
| 148 | + assert_eq!(cache.peek(&3), Some(&"three")); |
| 149 | + } |
| 150 | + |
| 151 | + #[test] |
| 152 | + fn removing_the_last_entry_releases_storage() { |
| 153 | + let mut cache = LazyLruCache::new(NonZeroUsize::new(2).unwrap()); |
| 154 | + cache.put(1, "one"); |
| 155 | + |
| 156 | + assert_eq!(cache.pop(&1), Some("one")); |
| 157 | + assert!(cache.cache.is_none()); |
| 158 | + |
| 159 | + cache.put(2, "two"); |
| 160 | + cache.clear(); |
| 161 | + assert!(cache.cache.is_none()); |
| 162 | + assert_eq!(cache.cap().get(), 2); |
| 163 | + } |
| 164 | +} |
0 commit comments