Bounded LRU Caching in Rust
Keep a fixed-capacity least-recently-used cache with the lru crate, evicting the coldest entry and promoting reads automatically.
Code
use lru::LruCache;
use std::num::NonZeroUsize;
struct Store {
cache: LruCache<String, String>,
}
impl Store {
fn new(capacity: usize) -> Self {
let size = NonZeroUsize::new(capacity).expect("capacity must be > 0");
Store { cache: LruCache::new(size) }
}
fn get(&mut self, key: &str) -> Option<&String> {
self.cache.get(key)
}
fn put(&mut self, key: String, value: String) {
if self.cache.len() == self.cache.cap().get() {
println!("evicting the least recently used entry");
}
self.cache.put(key, value);
}
fn len(&self) -> usize {
self.cache.len()
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.