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.

RustData Fetching

Code

rustsnippet
28 lines
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()
    }
}

What the code does

Structurally, expect the functions new, get, put and len and nothing else.

Points of care

  • Dependency check: lru::LruCache — not built-in, must be present in the project.

Applying it

The main signature reads fn new(capacity: usize) -> Self

The demo output is labeled (evicting the least recently used entry), so every printed line maps back to its originating operation.

new is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

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 new(capacity: usize) -> Self {
let size = NonZeroUsize::new(capacity).expect("capacity must be > 0");
Store { cache: LruCache::new(size) }
}

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `lru::LruCache`. Without it the snippet will not load.