pub struct LRUCache<T, const N: usize> { /* private fields */ }
Expand description
A LRU cache using a statically-sized array for storage.
LRUCache
uses a fixed-capacity array for storage. It provides O(1)
insertion, and O(n)
lookup.
All items are stored inline within the LRUCache
, so it does not impose any heap allocation or
indirection. A linked list is used to record the cache order, so the items themselves do not
need to be moved when the order changes. (This is important for speed if the items are large.)
§Example
use uluru::LRUCache;
struct MyValue {
id: u32,
name: &'static str,
}
// A cache with a capacity of three.
type MyCache = LRUCache<MyValue, 3>;
// Create an empty cache, then insert some items.
let mut cache = MyCache::default();
cache.insert(MyValue { id: 1, name: "Mercury" });
cache.insert(MyValue { id: 2, name: "Venus" });
cache.insert(MyValue { id: 3, name: "Earth" });
// Use the `find` method to retrieve an item from the cache.
// This also "touches" the item, marking it most-recently-used.
let item = cache.find(|x| x.id == 1);
assert_eq!(item.unwrap().name, "Mercury");
// If the cache is full, inserting a new item evicts the least-recently-used item:
cache.insert(MyValue { id: 4, name: "Mars" });
assert!(cache.find(|x| x.id == 2).is_none());
Implementations§
source§impl<T, const N: usize> LRUCache<T, N>
impl<T, const N: usize> LRUCache<T, N>
sourcepub fn insert(&mut self, val: T) -> Option<T>
pub fn insert(&mut self, val: T) -> Option<T>
Insert a given key in the cache.
This item becomes the front (most-recently-used) item in the cache. If the cache is full, the back (least-recently-used) item will be removed and returned.
sourcepub fn find<F>(&mut self, pred: F) -> Option<&mut T>
pub fn find<F>(&mut self, pred: F) -> Option<&mut T>
Returns the first item in the cache that matches the given predicate. Touches the result (makes it most-recently-used) on a hit.
sourcepub fn lookup<F, R>(&mut self, pred: F) -> Option<R>
pub fn lookup<F, R>(&mut self, pred: F) -> Option<R>
Performs a lookup on the cache with the given test routine. Touches the result on a hit.
sourcepub fn front_mut(&mut self) -> Option<&mut T>
pub fn front_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the front entry in the list (most recently used).
sourcepub fn get(&self, index: usize) -> Option<&T>
pub fn get(&self, index: usize) -> Option<&T>
Returns the n-th entry in the list (most recently used).