pub struct Cache { /* private fields */ }Expand description
A thread-safe, in-memory cache with optional TTL and LRU eviction.
§Features
- Thread-safe: Can be safely shared across threads using
Arc<Cache>or cloning. - TTL support: Entries can have optional time-to-live.
- LRU eviction: When capacity is reached, least recently used entries are evicted.
- Statistics: Track hits, misses, evictions, and more.
§Example
use in_memory_cache::{Cache, CacheConfig};
use std::time::Duration;
// Create a cache with max 1000 entries and 5 minute default TTL
let config = CacheConfig::new()
.max_capacity(1000)
.default_ttl(Duration::from_secs(300))
.build();
let cache = Cache::new(config);
// Basic operations
cache.set("user:123", "Alice");
if let Some(value) = cache.get("user:123") {
println!("Found: {:?}", value);
}
// With explicit TTL
cache.set_with_ttl("session:abc", "data", Duration::from_secs(60));
// Check statistics
let stats = cache.stats();
println!("Hit rate: {:.1}%", stats.hit_rate);Implementations§
Source§impl Cache
impl Cache
Sourcepub fn new(config: CacheConfig) -> Self
pub fn new(config: CacheConfig) -> Self
Sourcepub fn get(&self, key: &str) -> Option<Bytes>
pub fn get(&self, key: &str) -> Option<Bytes>
Get a value from the cache.
Returns None if the key doesn’t exist or has expired.
Accessing a key updates its last-accessed time for LRU tracking.
§Arguments
key- The key to look up.
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
cache.set("key", "value");
match cache.get("key") {
Some(value) => println!("Found: {:?}", value),
None => println!("Not found"),
}Sourcepub fn set(&self, key: impl Into<String>, value: impl Into<Bytes>)
pub fn set(&self, key: impl Into<String>, value: impl Into<Bytes>)
Set a value in the cache.
If a default_ttl is configured, entries will use that TTL.
Otherwise, entries will not expire.
§Arguments
key- The key to store the value under.value- The value to store (anything that can be converted toBytes).
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
cache.set("string_key", "string value");
cache.set("bytes_key", vec![1, 2, 3, 4]);Sourcepub fn set_with_ttl(
&self,
key: impl Into<String>,
value: impl Into<Bytes>,
ttl: Duration,
)
pub fn set_with_ttl( &self, key: impl Into<String>, value: impl Into<Bytes>, ttl: Duration, )
Set a value in the cache with a specific TTL.
The entry will be removed after the specified duration.
§Arguments
key- The key to store the value under.value- The value to store.ttl- How long the entry should live.
§Example
use in_memory_cache::{Cache, CacheConfig};
use std::time::Duration;
let cache = Cache::new(CacheConfig::default());
cache.set_with_ttl("session", "data", Duration::from_secs(3600));Sourcepub fn delete(&self, key: &str) -> bool
pub fn delete(&self, key: &str) -> bool
Delete a key from the cache.
Returns true if the key existed and was removed.
§Arguments
key- The key to delete.
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
cache.set("key", "value");
assert!(cache.delete("key"));
assert!(!cache.delete("key")); // Already deletedSourcepub fn contains(&self, key: &str) -> bool
pub fn contains(&self, key: &str) -> bool
Check if a key exists in the cache.
Returns false if the key doesn’t exist or has expired.
Note: This does NOT update the LRU access time.
§Arguments
key- The key to check.
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
assert!(!cache.contains("key"));
cache.set("key", "value");
assert!(cache.contains("key"));Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Get the number of entries in the cache.
Note: This may include expired entries that haven’t been cleaned up yet by lazy expiration or background cleanup.
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
assert_eq!(cache.len(), 0);
cache.set("key", "value");
assert_eq!(cache.len(), 1);Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Check if the cache is empty.
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
assert!(cache.is_empty());
cache.set("key", "value");
assert!(!cache.is_empty());Sourcepub fn clear(&self)
pub fn clear(&self)
Remove all entries from the cache.
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
cache.set("key1", "value1");
cache.set("key2", "value2");
cache.clear();
assert!(cache.is_empty());Sourcepub fn stats(&self) -> StatsSnapshot
pub fn stats(&self) -> StatsSnapshot
Get a snapshot of the cache statistics.
Returns a point-in-time snapshot of hits, misses, evictions, etc.
§Example
use in_memory_cache::{Cache, CacheConfig};
let cache = Cache::new(CacheConfig::default());
cache.set("key", "value");
let _ = cache.get("key"); // Hit
let _ = cache.get("missing"); // Miss
let stats = cache.stats();
println!("Hits: {}, Misses: {}", stats.hits, stats.misses);Sourcepub fn cleanup_expired(&self) -> usize
pub fn cleanup_expired(&self) -> usize
Manually trigger cleanup of expired entries.
Returns the number of entries that were removed. This is useful if you want to control when cleanup happens instead of relying on lazy expiration or background cleanup.
§Example
use in_memory_cache::{Cache, CacheConfig};
use std::time::Duration;
let cache = Cache::new(CacheConfig::default());
cache.set_with_ttl("key", "value", Duration::from_millis(1));
std::thread::sleep(Duration::from_millis(10));
let removed = cache.cleanup_expired();
println!("Removed {} expired entries", removed);Sourcepub fn stats_ref(&self) -> Arc<CacheStats>
pub fn stats_ref(&self) -> Arc<CacheStats>
Get a reference to the internal statistics counter.
This is useful for integrating with external metrics systems.