class
Crystallabs::Helpers::BoundedCache(K, V)
- Crystallabs::Helpers::BoundedCache(K, V)
- Reference
- Object
Overview
A size-bounded memoization cache: a Hash that evicts entries once it
grows past capacity.
Drop-in for a plain Hash used as a memo (#[], #[]?, #[]=, #has_key?,
#delete, #clear, #fetch), with two additions:
- Eviction. When adding an entry would exceed capacity, the oldest
entry is dropped (FIFO by default; strict LRU with
lru: true). A capacity of0or less means unbounded. - Memoizing
#fetch.fetch(key) { compute }stores and returns the computed value on a miss (and correctly caches anilvalue, so it works for negative caching). This differs fromHash#fetch, which does not store.
FIFO is the default because it keeps reads as pure Hash lookups, with no
reordering. Pass lru: true when recency-of-use should decide what survives
(e.g. an image decode cache) and the read cost is affordable.
Not thread-safe.
Defined in:
crystallabs-helpers.crConstructors
-
.new(capacity : Int32, *, lru : Bool = false, by_identity : Bool = false)
Creates a cache holding at most capacity entries.
Instance Method Summary
-
#[](key : K) : V
The value for key; raises
KeyErrorif absent (likeHash#[]). -
#[]=(key : K, value : V) : V
Stores value under key and returns it, evicting if over capacity.
-
#[]?(key : K) : V | Nil
The value for key, or
nilif absent. -
#capacity : Int32
Maximum entries kept;
<= 0means unbounded. -
#capacity=(capacity : Int32)
Maximum entries kept;
<= 0means unbounded. -
#clear : Nil
Empties the cache.
-
#delete(key : K) : V | Nil
Removes key, returning its value or
nil. -
#each(& : Tuple(K, V) -> _) : Nil
Yields each
{key, value}pair (insertion order). -
#fetch(key : K, & : -> V) : V
Returns the cached value for key, or computes it via the block, stores it, and returns it.
-
#has_key?(key : K) : Bool
Whether key is present (distinguishes a cached
nilvalue from absence). -
#size : Int32
Current number of entries.
Constructor Detail
Creates a cache holding at most capacity entries. lru switches
eviction from FIFO to least-recently-used. by_identity keys the cache
on object identity (same?) instead of value equality — for caches
memoizing per-object results, mirroring Hash#compare_by_identity.
Instance Method Detail
The value for key, or nil if absent. In lru mode a hit is promoted
to most-recently-used.
Returns the cached value for key, or computes it via the block, stores
it, and returns it. The block's result is cached even when nil.
Whether key is present (distinguishes a cached nil value from absence).