pub struct TtlCache<K, V> { /* private fields */ }Expand description
A cache that automatically expires entries after a configurable TTL.
This is useful for tracking order lifetimes in rate limiting, where orders cancelled within certain time windows incur different penalties.
Implementations§
Source§impl<K, V> TtlCache<K, V>
impl<K, V> TtlCache<K, V>
Sourcepub fn new(ttl: Duration) -> Self
pub fn new(ttl: Duration) -> Self
Create a new TTL cache with the specified time-to-live duration.
Entries will be considered expired after this duration.
Sourcepub fn with_capacity(ttl: Duration, capacity: usize) -> Self
pub fn with_capacity(ttl: Duration, capacity: usize) -> Self
Create a new TTL cache with a specific initial capacity.
Sourcepub fn insert(&mut self, key: K, value: V)
pub fn insert(&mut self, key: K, value: V)
Insert a key-value pair into the cache.
The entry will be timestamped with the current time.
Sourcepub fn get(&self, key: &K) -> Option<&V>
pub fn get(&self, key: &K) -> Option<&V>
Get a reference to a value if it exists and hasn’t expired.
Sourcepub fn get_mut(&mut self, key: &K) -> Option<&mut V>
pub fn get_mut(&mut self, key: &K) -> Option<&mut V>
Get a mutable reference to a value if it exists and hasn’t expired.
Sourcepub fn get_timestamp(&self, key: &K) -> Option<Instant>
pub fn get_timestamp(&self, key: &K) -> Option<Instant>
Get the timestamp when the entry was inserted.
Returns None if the key doesn’t exist or has expired.
Sourcepub fn get_age(&self, key: &K) -> Option<Duration>
pub fn get_age(&self, key: &K) -> Option<Duration>
Get the age of an entry in the cache.
Returns None if the key doesn’t exist or has expired.
Sourcepub fn remove(&mut self, key: &K) -> Option<V>
pub fn remove(&mut self, key: &K) -> Option<V>
Remove an entry from the cache.
Returns the value if it existed and hadn’t expired, None otherwise.
Sourcepub fn remove_with_age(&mut self, key: &K) -> Option<(V, Duration)>
pub fn remove_with_age(&mut self, key: &K) -> Option<(V, Duration)>
Remove an entry and return both the value and its age.
Useful for calculating rate limit penalties based on order age.
Sourcepub fn cleanup(&mut self)
pub fn cleanup(&mut self)
Remove all expired entries from the cache.
Call this periodically to free memory from expired entries.
Sourcepub fn active_count(&self) -> usize
pub fn active_count(&self) -> usize
Get the number of non-expired entries.