57 releases

Uses old Rust 2015

0.14.0 Apr 12, 2025
0.13.0 Jan 28, 2025
0.12.5 Oct 7, 2024
0.12.4 Jul 31, 2024
0.1.1 Dec 31, 2016

#3 in Caching

Download history 1148806/week @ 2025-01-11 965518/week @ 2025-01-18 1056967/week @ 2025-01-25 1206357/week @ 2025-02-01 1330212/week @ 2025-02-08 1245548/week @ 2025-02-15 1384964/week @ 2025-02-22 1408361/week @ 2025-03-01 1465755/week @ 2025-03-08 1440702/week @ 2025-03-15 1412959/week @ 2025-03-22 1349331/week @ 2025-03-29 1482991/week @ 2025-04-05 1317791/week @ 2025-04-12 1425474/week @ 2025-04-19 1098248/week @ 2025-04-26

5,558,097 downloads per month
Used in 3,903 crates (436 directly)

MIT license

94KB
1.5K SLoC

LRU Cache

Build Badge Codecov Badge crates.io Badge docs.rs Badge License Badge

Documentation

An implementation of a LRU cache. The cache supports put, get, get_mut and pop operations, all of which are O(1). This crate was heavily influenced by the LRU Cache implementation in an earlier version of Rust's std::collections crate.

The MSRV for this crate is 1.70.0.

Example

Below is a simple example of how to instantiate and use a LRU cache.

extern crate lru;

use lru::LruCache;
use std::num::NonZeroUsize;

fn main() {
    let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap());
    cache.put("apple", 3);
    cache.put("banana", 2);

    assert_eq!(*cache.get(&"apple").unwrap(), 3);
    assert_eq!(*cache.get(&"banana").unwrap(), 2);
    assert!(cache.get(&"pear").is_none());

    assert_eq!(cache.put("banana", 4), Some(2));
    assert_eq!(cache.put("pear", 5), None);

    assert_eq!(*cache.get(&"pear").unwrap(), 5);
    assert_eq!(*cache.get(&"banana").unwrap(), 4);
    assert!(cache.get(&"apple").is_none());

    {
        let v = cache.get_mut(&"banana").unwrap();
        *v = 6;
    }

    assert_eq!(*cache.get(&"banana").unwrap(), 6);
}

Dependencies

~1MB
~12K SLoC