LRU Memory Cache Library in Rust
in-memory-cache is a straightforward, yet powerful crate that delivers an easy-to-use in-memory cache solution with a Least Recently Used (LRU) eviction policy. This crate facilitates the efficient storage of key-value pairs, providing automatic eviction of the least recently accessed entries when the cache reaches its predefined capacity.
Features
- Easy-to-use API for adding and retrieving items from the cache.
- Supports two types of limits: capacity and size.
- Supports limiting cache size based on the number of entries or the total size in bytes.
- Evicts the oldest entries when the cache reaches its limit.
- Error handling for content that exceeds the cache's size limit.
Usage
To use the in-memory-cache
crate, add the following dependency to your Cargo.toml
file:
[]
= "0.4"
= "https://github.com/zeljic/in-memory-cache.git"
Example
Here is an example demonstrating how to use the in-memory-cache
crate:
use ;
In this example, we create a cache with a capacity of 5 items using Cache::with_capacity()
. We use the add()
method to add entries to the cache, and the get()
method to retrieve entries from the cache.
If the cache reaches its capacity, the oldest entry will be evicted when a new entry is added. The clear()
method can be used to remove all entries from the cache.
Further customization
The Cache
struct provides additional methods to create a cache with a size-based limit and methods to retrieve entries as bytes::Bytes
. You can choose the appropriate method based on your specific use case.
Error Handling
The add()
method returns a Result<(), Box<dyn std::error::Error>>
, allowing you to handle errors that occur when adding entries to the cache. If the content exceeds the cache's size limit, an Error
will be returned.
License
This crate is licensed under the MIT License. Please refer to the LICENSE file for detailed licensing information.