Debian Codegraph @

third_party/rust/uluru/src/lib.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 #![no_std]
6 #![deny(unsafe_code)]
7
8 //! A simple, fast, least-recently-used (LRU) cache.
9 //!
10 //! [`LRUCache`] uses a fixed-capacity array for storage. It provides `O(1)` insertion, and `O(n)`
11 //! lookup. It does not require an allocator and can be used in `no_std` crates.
12 //!
13 //! See the [`LRUCache`](LRUCache) docs for details.
14
15 use arrayvec::ArrayVec;
16 use core::{fmt, mem::replace};
17
18 #[cfg(test)]
19 mod tests;
20
21 /// A LRU cache using a statically-sized array for storage.
22 ///
23 /// `LRUCache` uses a fixed-capacity array for storage. It provides `O(1)` insertion, and `O(n)`
24 /// lookup.
25 ///
26 /// All items are stored inline within the `LRUCache`, so it does not impose any heap allocation or
27 /// indirection. A linked list is used to record the cache order, so the items themselves do not
28 /// need to be moved when the order changes. (This is important for speed if the items are large.)
29 ///
30 /// # Example
31 ///
32 /// ```
33 /// use uluru::LRUCache;
34 ///
35 /// struct MyValue {
36 /// id: u32,
37 /// name: &'static str,
38 /// }
39 ///
40 /// // A cache with a capacity of three.
41 /// type MyCache = LRUCache<MyValue, 3>;
42 ///
43 /// // Create an empty cache, then insert some items.
44 /// let mut cache = MyCache::default();
45 /// cache.insert(MyValue { id: 1, name: "Mercury" });
46 /// cache.insert(MyValue { id: 2, name: "Venus" });
47 /// cache.insert(MyValue { id: 3, name: "Earth" });
48 ///
49 /// // Use the `find` method to retrieve an item from the cache.
50 /// // This also "touches" the item, marking it most-recently-used.
51 /// let item = cache.find(|x| x.id == 1);
52 /// assert_eq!(item.unwrap().name, "Mercury");
53 ///
54 /// // If the cache is full, inserting a new item evicts the least-recently-used item:
55 /// cache.insert(MyValue { id: 4, name: "Mars" });
56 /// assert!(cache.find(|x| x.id == 2).is_none());
57 /// ```
58 pub struct LRUCache<T, const N: usize> {
59 /// The most-recently-used entry is at index `head`. The entries form a linked list, linked to
60 /// each other by indices within the `entries` array. After an entry is added to the array,
61 /// its index never changes, so these links are never invalidated.
62 entries: ArrayVec<Entry<T>, N>,
63 /// Index of the first entry. If the cache is empty, ignore this field.
64 head: u16,
65 /// Index of the last entry. If the cache is empty, ignore this field.
66 tail: u16,
67 }
68
69 /// An entry in an `LRUCache`.
70 #[derive(Debug, Clone)]
71 struct Entry<T> {
72 val: T,
73 /// Index of the previous entry. If this entry is the head, ignore this field.
74 prev: u16,
75 /// Index of the next entry. If this entry is the tail, ignore this field.
76 next: u16,
77 }
78
79 impl<T, const N: usize> Default for LRUCache<T, N> {
80 fn default() -> Self {
81 let cache = LRUCache {
82 entries: ArrayVec::new(),
83 head: 0,
84 tail: 0,
85 };
86 assert!(
87 cache.entries.capacity() < u16::max_value() as usize,
88 "Capacity overflow"
89 );
90 cache
91 }
92 }
93
94 impl<T, const N: usize> LRUCache<T, N> {
95 /// Insert a given key in the cache.
96 ///
97 /// This item becomes the front (most-recently-used) item in the cache. If the cache is full,
98 /// the back (least-recently-used) item will be removed and returned.
99 pub fn insert(&mut self, val: T) -> Option<T> {
100 let entry = Entry {
101 val,
102 prev: 0,
103 next: 0,
104 };
105
106 // If the cache is full, replace the oldest entry. Otherwise, add an entry.
107 let (new_head, previous_entry) = if self.entries.len() == self.entries.capacity() {
108 let i = self.pop_back();
109 let previous_entry = replace(&mut self.entries[i as usize], entry);
110 (i, Some(previous_entry.val))
111 } else {
112 self.entries.push(entry);
113 (self.entries.len() as u16 - 1, None)
114 };
115
116 self.push_front(new_head);
117 previous_entry
118 }
119
120 /// Returns the first item in the cache that matches the given predicate.
121 /// Touches the result (makes it most-recently-used) on a hit.
122 pub fn find<F>(&mut self, pred: F) -> Option<&mut T>
123 where
124 F: FnMut(&T) -> bool,
125 {
126 if self.touch(pred) {
127 self.front_mut()
128 } else {
129 None
130 }
131 }
132
133 /// Performs a lookup on the cache with the given test routine. Touches
134 /// the result on a hit.
135 pub fn lookup<F, R>(&mut self, mut test_one: F) -> Option<R>
136 where
137 F: FnMut(&mut T) -> Option<R>,
138 {
139 let mut result = None;
140 let mut iter = self.iter_mut();
141 while let Some((i, val)) = iter.next() {
142 if let Some(r) = test_one(val) {
143 result = Some((i, r));
144 break;
145 }
146 }
147
148 match result {
149 None => None,
150 Some((i, r)) => {
151 self.touch_index(i);
152 Some(r)
153 }
154 }
155 }
156
157 /// Returns the number of elements in the cache.
158 #[inline]
159 pub fn len(&self) -> usize {
160 self.entries.len()
161 }
162
163 /// Returns true if the cache is empty.
164 #[inline]
165 pub fn is_empty(&self) -> bool {
166 self.entries.is_empty()
167 }
168
169 /// Evict all elements from the cache.
170 #[inline]
171 pub fn clear(&mut self) {
172 self.entries.clear();
173 }
174
175 /// Returns the front entry in the list (most recently used).
176 pub fn front(&self) -> Option<&T> {
177 self.entries.get(self.head as usize).map(|e| &e.val)
178 }
179
180 /// Returns a mutable reference to the front entry in the list (most recently used).
181 pub fn front_mut(&mut self) -> Option<&mut T> {
182 self.entries.get_mut(self.head as usize).map(|e| &mut e.val)
183 }
184
185 /// Returns the n-th entry in the list (most recently used).
186 pub fn get(&self, index: usize) -> Option<&T> {
187 self.iter().nth(index)
188 }
189
190 /// Touches the first item in the cache that matches the given predicate (marks it as
191 /// most-recently-used).
192 /// Returns `true` on a hit, `false` if no matches.
193 pub fn touch<F>(&mut self, mut pred: F) -> bool
194 where
195 F: FnMut(&T) -> bool,
196 {
197 let mut iter = self.iter_mut();
198 while let Some((i, val)) = iter.next() {
199 if pred(val) {
200 self.touch_index(i);
201 return true;
202 }
203 }
204 false
205 }
206
207 /// Iterate over the contents of this cache in order from most-recently-used to
208 /// least-recently-used.
209 pub fn iter(&self) -> Iter<'_, T, N> {
210 Iter {
211 pos: self.head,
212 cache: self,
213 }
214 }
215
216 /// Iterate mutably over the contents of this cache in order from most-recently-used to
217 /// least-recently-used.
218 fn iter_mut(&mut self) -> IterMut<'_, T, N> {
219 IterMut {
220 pos: self.head,
221 cache: self,
222 }
223 }
224
225 /// Touch a given entry, putting it first in the list.
226 #[inline]
227 fn touch_index(&mut self, idx: u16) {
228 if idx != self.head {
229 self.remove(idx);
230 self.push_front(idx);
231 }
232 }
233
234 /// Remove an entry from the linked list.
235 ///
236 /// Note: This only unlinks the entry from the list; it does not remove it from the array.
237 fn remove(&mut self, i: u16) {
238 let prev = self.entries[i as usize].prev;
239 let next = self.entries[i as usize].next;
240
241 if i == self.head {
242 self.head = next;
243 } else {
244 self.entries[prev as usize].next = next;
245 }
246
247 if i == self.tail {
248 self.tail = prev;
249 } else {
250 self.entries[next as usize].prev = prev;
251 }
252 }
253
254 /// Insert a new entry at the head of the list.
255 fn push_front(&mut self, i: u16) {
256 if self.entries.len() == 1 {
257 self.tail = i;
258 } else {
259 self.entries[i as usize].next = self.head;
260 self.entries[self.head as usize].prev = i;
261 }
262 self.head = i;
263 }
264
265 /// Remove the last entry from the linked list. Returns the index of the removed entry.
266 ///
267 /// Note: This only unlinks the entry from the list; it does not remove it from the array.
268 fn pop_back(&mut self) -> u16 {
269 let old_tail = self.tail;
270 let new_tail = self.entries[old_tail as usize].prev;
271 self.tail = new_tail;
272 old_tail
273 }
274 }
275
276 impl<T, const N: usize> Clone for LRUCache<T, N>
277 where
278 T: Clone,
279 {
280 fn clone(&self) -> Self {
281 Self {
282 entries: self.entries.clone(),
283 head: self.head,
284 tail: self.tail,
285 }
286 }
287 }
288
289 impl<T, const N: usize> fmt::Debug for LRUCache<T, N>
290 where
291 T: fmt::Debug,
292 {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 f.debug_struct("LRUCache")
295 .field("head", &self.head)
296 .field("tail", &self.tail)
297 .field("entries", &self.entries)
298 .finish()
299 }
300 }
301
302 /// Mutable iterator over values in an `LRUCache`, from most-recently-used to least-recently-used.
303 struct IterMut<'a, T, const N: usize> {
304 cache: &'a mut LRUCache<T, N>,
305 pos: u16,
306 }
307
308 impl<'a, T, const N: usize> IterMut<'a, T, N> {
309 fn next(&mut self) -> Option<(u16, &mut T)> {
310 let index = self.pos;
311 let entry = self.cache.entries.get_mut(index as usize)?;
312
313 self.pos = if index == self.cache.tail {
314 N as u16 // Point past the end of the array to signal we are done.
315 } else {
316 entry.next
317 };
318 Some((index, &mut entry.val))
319 }
320 }
321
322 /// Iterator over values in an [`LRUCache`], from most-recently-used to least-recently-used.
323 pub struct Iter<'a, T, const N: usize> {
324 cache: &'a LRUCache<T, N>,
325 pos: u16,
326 }
327
328 impl<'a, T, const N: usize> Iterator for Iter<'a, T, N> {
329 type Item = &'a T;
330
331 fn next(&mut self) -> Option<&'a T> {
332 let entry = self.cache.entries.get(self.pos as usize)?;
333
334 self.pos = if self.pos == self.cache.tail {
335 N as u16 // Point past the end of the array to signal we are done.
336 } else {
337 entry.next
338 };
339 Some(&entry.val)
340 }
341 }