pub struct TtlCache<K, V> { /* private fields */ }Expand description
Thread-safe TTL cache with LRU eviction.
The cache is keyed by any Eq + Hash + Clone type and stores any
Clone value. Each insert takes a per-entry TTL. Entries expire on
the first get/insert that observes the expired deadline; an explicit
TtlCache::prune is also provided for bulk collection.
Implementations§
Source§impl<K, V> TtlCache<K, V>
impl<K, V> TtlCache<K, V>
Sourcepub fn new(capacity: NonZero<usize>) -> TtlCache<K, V>
pub fn new(capacity: NonZero<usize>) -> TtlCache<K, V>
Create a new cache with the given capacity, backed by TokioClock.
Capacity is a non-zero usize because a zero-capacity cache is degenerate (every insert would immediately evict itself).
Sourcepub fn with_clock(
capacity: NonZero<usize>,
clock: Arc<dyn Clock>,
) -> TtlCache<K, V>
pub fn with_clock( capacity: NonZero<usize>, clock: Arc<dyn Clock>, ) -> TtlCache<K, V>
Create a cache backed by a custom Clock implementation.
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Current number of entries in the cache (may include not-yet-pruned expired entries).
Sourcepub fn get(&self, key: &K) -> Option<V>
pub fn get(&self, key: &K) -> Option<V>
Look up key. Returns Some(value) on cache hit (and bumps the
entry’s recency); None on miss or expired entry. Expired entries
are removed on observation.
Sourcepub fn insert(&self, key: K, value: V, ttl: Duration)
pub fn insert(&self, key: K, value: V, ttl: Duration)
Insert value under key with the given ttl. If the cache is at
capacity, evicts the least recently used live entry first.