Module std.cache

Keyed memoization with optional expiry and bounded FIFO eviction.

A cache is an ordinary value: copying it creates an independent snapshot. Keys and values must support Clone; reads return independent values. Use cache.new(.Some(128), .Some(5s)) for at most 128 retained entries, each expiring five seconds after insertion. Omit either option to disable that limit. A zero capacity or TTL disables retention; negative limits fail.

get and insert accept an observation instant, defaulting to the host's monotonic clock. Explicit instants must come from the same clock and move forward. An entry is absent at its exact deadline; reads never extend TTL. Insertion removes expired entries before evicting the oldest live insertion. Replacing a key makes it the newest insertion; reads do not change order. Expiry is lazy: get, insert, prune and len reclaim expired entries; there is no background task. FIFO removal and TTL pruning are linear in the retained entry count, while ordinary hits use the backing HashMap.

get_or_load(key, || load()) calls its loader only on a miss. Successful values are cached with a fresh instant.now() after loading finishes. Ordinary errors are returned without caching or evicting live entries. A fault or cancellation also leaves no partially initialized entry.

See the complete product-cache example in examples/keyed_cache.hew.

import std.cache;

fn main() {
    var values: cache.Cache<string, i64> = cache.new(capacity: .Some(2)).expect("valid capacity");
    values.insert("first", 10);
    let loaded: Result<i64, string> = values.get_or_load("second", || .Ok(20));
    println(loaded.expect("loaded value"));
    let snapshot = values;
    values.insert("third", 30);
    println(values.get("first").is_none());
    var saved = snapshot;
    println(saved.get("first").expect("snapshot retains first"));
}
// Output:
// 20
// true
// 10

Contents

Functions

Function new

pub fn new<K: Hash + Eq + Clone, V: Clone>(capacity: Option<i64> = …, ttl: Option<duration> = …) -> Cache<K, V> fails CacheError

Create an empty cache. Unspecified limits are unbounded.

Types

Enum CacheError

Invalid cache limits.

Variants

InvalidCapacity(i64)
InvalidTtl(duration)

Struct Cache

An owning value cache. Eviction and invalidation release retained values automatically; no close operation is needed.

Fields

entries: HashMap<K, Entry<V>>
order: Vec<K>
capacity: Option<i64>
ttl: Option<duration>

Inherent methods

impl<K: Hash + Eq + Clone, V: Clone> Cache<K, V>

pub fn get(var self, key: K, now: instant = …) -> Option<V>

Return an independent value, removing the entry if its TTL has elapsed.

pub fn insert(var self, consume key: K, consume value: V, now: instant = …)

Insert or replace a value. Expired entries are reclaimed first; a full bounded cache evicts its oldest insertion. Zero limits retain nothing.

pub fn get_or_load<E>(var self, consume key: K, consume load: fn() -> Result<V, E>) -> V fails E

Return a hit or run the explicit loader once. Failed loads retain no error and do not evict another live entry. TTL starts after success.

pub fn invalidate(var self, key: K) -> bool

Remove a key regardless of its age. Return whether it was retained.

pub fn prune(var self, now: instant = …) -> i64

Reclaim all entries whose TTL has elapsed. Return the number removed.

pub fn len(var self, now: instant = …) -> i64

Count live entries, reclaiming expired entries first.

pub fn clear(var self)

Release every retained key and value, preserving the configured limits.