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

snippet
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()
    }
}