| 1 |
# LRU Cache |
| 2 |
|
| 3 |
[![Build Badge]][build status] |
| 4 |
[![crates.io Badge]][crates.io package] |
| 5 |
[![docs.rs Badge]][docs.rs documentation] |
| 6 |
[![License Badge]][license] |
| 7 |
|
| 8 |
[Documentation] |
| 9 |
|
| 10 |
An implementation of a LRU cache. The cache supports `put`, `get`, `get_mut` and `pop` operations, |
| 11 |
all of which are O(1). This crate was heavily influenced by the [LRU Cache implementation in an |
| 12 |
earlier version of Rust's std::collections crate]. |
| 13 |
|
| 14 |
The MSRV for this crate is 1.70.0. |
| 15 |
|
| 16 |
## Example |
| 17 |
|
| 18 |
Below is a simple example of how to instantiate and use a LRU cache. |
| 19 |
|
| 20 |
```rust,no_run |
| 21 |
extern crate lru; |
| 22 |
|
| 23 |
use lru::LruCache; |
| 24 |
use std::num::NonZeroUsize; |
| 25 |
|
| 26 |
fn main() { |
| 27 |
let mut cache = LruCache::new(NonZeroUsize::new(2).unwrap()); |
| 28 |
cache.put("apple", 3); |
| 29 |
cache.put("banana", 2); |
| 30 |
|
| 31 |
assert_eq!(*cache.get(&"apple").unwrap(), 3); |
| 32 |
assert_eq!(*cache.get(&"banana").unwrap(), 2); |
| 33 |
assert!(cache.get(&"pear").is_none()); |
| 34 |
|
| 35 |
assert_eq!(cache.put("banana", 4), Some(2)); |
| 36 |
assert_eq!(cache.put("pear", 5), None); |
| 37 |
|
| 38 |
assert_eq!(*cache.get(&"pear").unwrap(), 5); |
| 39 |
assert_eq!(*cache.get(&"banana").unwrap(), 4); |
| 40 |
assert!(cache.get(&"apple").is_none()); |
| 41 |
|
| 42 |
{ |
| 43 |
let v = cache.get_mut(&"banana").unwrap(); |
| 44 |
*v = 6; |
| 45 |
} |
| 46 |
|
| 47 |
assert_eq!(*cache.get(&"banana").unwrap(), 6); |
| 48 |
} |
| 49 |
``` |
| 50 |
|
| 51 |
[build badge]: https://github.com/jeromefroe/lru-rs/actions/workflows/main.yml/badge.svg |
| 52 |
[build status]: https://github.com/jeromefroe/lru-rs/actions/workflows/main.yml |
| 53 |
[crates.io badge]: https://img.shields.io/crates/v/lru.svg |
| 54 |
[crates.io package]: https://crates.io/crates/lru/ |
| 55 |
[documentation]: https://docs.rs/lru/ |
| 56 |
[docs.rs badge]: https://docs.rs/lru/badge.svg |
| 57 |
[docs.rs documentation]: https://docs.rs/lru/ |
| 58 |
[license badge]: https://img.shields.io/badge/license-MIT-blue.svg |
| 59 |
[license]: https://raw.githubusercontent.com/jeromefroe/lru-rs/master/LICENSE |
| 60 |
[lru cache implementation in an earlier version of rust's std::collections crate]: https://doc.rust-lang.org/0.12.0/std/collections/lru_cache/struct.LruCache.html |