Crates.io | threadsafe-lru |
lib.rs | threadsafe-lru |
version | 0.1.2 |
source | src |
created_at | 2024-10-12 00:31:43.202229 |
updated_at | 2024-10-14 15:30:22.336286 |
description | Thread-safe LRU |
homepage | https://github.com/bijanvan/threadsafe-lru |
repository | https://github.com/bijanvan/threadsafe-lru |
max_upload_size | |
id | 1406035 |
size | 56,629 |
This is a thread-safe implementation of an LRU (Least Recently Used) cache in Rust.
The LruCache
struct uses sharding to improve concurrency by splitting the cache into multiple smaller segments, each protected by a mutex.
use threadsafe_lru::LruCache;
fn main() {
// Create a new LRU cache with 4 shards and capacity of 2 per shard
let cache = LruCache::new(4, 2);
// Insert items into the cache
let five = 5;
let six = 6;
assert_eq!(cache.insert(five, 10), None);
assert_eq!(cache.insert(six, 20), None);
// Retrieve an item from the cache
assert_eq!(cache.get(&five), Some(10));
// Promote an item to make it more recently used
cache.promote(&five);
// Remove an item from the cache
assert_eq!(cache.remove(&five), Some(10));
}
In this example, a new LruCache
is created with 4 shards and a capacity of 2 entries per shard.
Items are inserted using the insert
method.
The get
method retrieves an item by key, promoting it to the most recently used position.
Finally, the remove
method deletes an item from the cache.
This implementation ensures that operations on different keys can be performed concurrently without causing race conditions due to shared state.
For detailed documentation, including all methods and usage examples, refer to the LruCache API on docs.rs.
LruCache is thoroughly tested with a suite of unit tests covering various operations. You can run the tests using cargo test
:
cargo test
This ensures that all functionalities work as expected and helps maintain high code quality.
LruCache is licensed under the MIT license. See LICENSE for more details.