pub struct Cache<K, V> { /* private fields */ }Expand description
A simple cache implementation with expiration and optional capacity limit.
This cache provides time-based expiration for items and an optional maximum capacity. It’s designed to be generic over both key and value types for maximum flexibility.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, u32> = Cache::new(Duration::from_secs(60));
let _ = cache.insert("visits".to_string(), 1);
assert_eq!(cache.get(&"visits".to_string()), Some(&1));Implementations§
Source§impl<K: Hash + Eq + Clone, V: Clone> Cache<K, V>
impl<K: Hash + Eq + Clone, V: Clone> Cache<K, V>
Sourcepub fn iter(&self) -> impl Iterator<Item = (&K, &V)>
pub fn iter(&self) -> impl Iterator<Item = (&K, &V)>
Returns an iterator over the key-value pairs in the cache.
Only entries that have not yet expired are yielded.
§Returns
An iterator over the key-value pairs in the cache.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, String> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("a".to_string(), "1".to_string());
let _ = cache.insert("b".to_string(), "2".to_string());
assert_eq!(cache.iter().count(), 2);Sourcepub fn with_capacity(ttl: Duration, capacity: usize) -> Self
pub fn with_capacity(ttl: Duration, capacity: usize) -> Self
Creates a new Cache with the specified TTL and initial capacity.
§Arguments
ttl- The time-to-live for cached items.capacity- The initial capacity of the cache.
§Panics
Panics if ttl is zero.
§Example
use staticweaver::cache::Cache;
use std::time::Duration;
let cache: Cache<String, String> = Cache::with_capacity(Duration::from_secs(60), 100);Sourcepub fn stats(&self) -> CacheStats
pub fn stats(&self) -> CacheStats
Returns a snapshot of cumulative cache counters (hits, misses, evictions, ttl-expirations, inserts). Issue #40.
All counters are monotonically increasing u64s. Take two
snapshots and subtract to get a per-window rate. Designed for
cheap export to prometheus, metrics, or opentelemetry
without forcing a dependency choice.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, u32> = Cache::new(Duration::from_secs(60));
assert_eq!(cache.stats().inserts, 0);
let _ = cache.insert("k".to_string(), 1);
assert_eq!(cache.stats().inserts, 1);Sourcepub fn insert(&mut self, key: K, value: V) -> Option<V>
pub fn insert(&mut self, key: K, value: V) -> Option<V>
Inserts a key-value pair into the cache.
If the cache is at capacity and the key doesn’t already exist, the least-recently-used entry is evicted to make room.
§Arguments
key- The key to insert.value- The value to insert.
§Returns
The old value if the key was already present.
§Example
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache = Cache::new(Duration::from_secs(60));
cache.insert("key".to_string(), "value".to_string());Sourcepub fn get(&mut self, key: &K) -> Option<&V>
pub fn get(&mut self, key: &K) -> Option<&V>
Retrieves a value from the cache if it exists and hasn’t expired.
§Arguments
key- The key to look up.
§Returns
An Option containing a reference to the value if it exists and hasn’t expired, or None otherwise.
§Example
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache = Cache::new(Duration::from_secs(60));
cache.insert("key".to_string(), "value".to_string());
assert_eq!(cache.get(&"key".to_string()), Some(&"value".to_string()));Sourcepub fn remove_expired(&mut self)
pub fn remove_expired(&mut self)
Removes expired items from the cache.
This method should be called periodically to clean up the cache.
Time complexity: O(n) where n is the number of items in the cache.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, String> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("k".to_string(), "v".to_string());
cache.remove_expired();
assert_eq!(cache.len(), 1);Sourcepub fn contains_key(&self, key: &K) -> bool
pub fn contains_key(&self, key: &K) -> bool
Checks if a key exists in the cache and hasn’t expired.
§Arguments
key- The key to check.
§Returns
true if the key exists and hasn’t expired, false otherwise.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, i32> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
assert!(cache.contains_key(&"n".to_string()));
assert!(!cache.contains_key(&"missing".to_string()));Sourcepub fn ttl(&self, key: &K) -> Option<Duration>
pub fn ttl(&self, key: &K) -> Option<Duration>
Gets the remaining time-to-live for an item.
§Arguments
key- The key to check.
§Returns
An Option containing the remaining TTL if the item exists and hasn’t expired, or None otherwise.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, i32> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
assert!(cache.ttl(&"n".to_string()).is_some());
assert!(cache.ttl(&"missing".to_string()).is_none());Sourcepub fn refresh(&mut self, key: &K) -> bool
pub fn refresh(&mut self, key: &K) -> bool
Refreshes the expiration time for an item.
§Arguments
key- The key of the item to refresh.
§Returns
true if the item was found and refreshed, false otherwise.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, i32> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
assert!(cache.refresh(&"n".to_string()));
assert!(!cache.refresh(&"missing".to_string()));Sourcepub fn remove(&mut self, key: &K) -> Option<V>
pub fn remove(&mut self, key: &K) -> Option<V>
Removes a key-value pair from the cache.
§Arguments
key- The key to remove.
§Returns
The removed value if the key was present, or None otherwise.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, String> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("k".to_string(), "v".to_string());
assert_eq!(cache.remove(&"k".to_string()), Some("v".to_string()));
assert_eq!(cache.remove(&"k".to_string()), None);Sourcepub fn update(&mut self, key: &K, value: V) -> bool
pub fn update(&mut self, key: &K, value: V) -> bool
Updates the value for an existing key in the cache.
§Arguments
key- The key to update.value- The new value to set.
§Returns
true if the key was found and updated, false otherwise.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, String> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("k".to_string(), "old".to_string());
assert!(cache.update(&"k".to_string(), "new".to_string()));
assert_eq!(cache.get(&"k".to_string()), Some(&"new".to_string()));Sourcepub fn set_capacity(&mut self, capacity: usize)
pub fn set_capacity(&mut self, capacity: usize)
Sets a maximum capacity for the cache.
If the cache is already larger than this capacity, it will not
remove items immediately, but it will prevent new items from being
added until it’s below capacity (via LRU eviction on insert).
§Arguments
capacity- The maximum number of items the cache can hold.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, String> =
Cache::new(Duration::from_secs(60));
cache.set_capacity(128);Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears all items from the cache.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, i32> =
Cache::new(Duration::from_secs(60));
let _ = cache.insert("n".to_string(), 1);
cache.clear();
assert!(cache.is_empty());Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of items in the cache.
§Returns
The number of key-value pairs currently in the cache.
§Examples
use staticweaver::cache::Cache;
use std::time::Duration;
let mut cache: Cache<String, i32> =
Cache::new(Duration::from_secs(60));
assert_eq!(cache.len(), 0);
let _ = cache.insert("a".to_string(), 1);
assert_eq!(cache.len(), 1);