class Crystallabs::Helpers::BoundedCache(K, V)

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:

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.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(capacity : Int32, *, lru : Bool = false, by_identity : Bool = false) #

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.


[View source]

Instance Method Detail

def [](key : K) : V #

The value for key; raises KeyError if absent (like Hash#[]).


[View source]
def []=(key : K, value : V) : V #

Stores value under key and returns it, evicting if over capacity.


[View source]
def []?(key : K) : V | Nil #

The value for key, or nil if absent. In lru mode a hit is promoted to most-recently-used.


[View source]
def capacity : Int32 #

Maximum entries kept; <= 0 means unbounded.


[View source]
def capacity=(capacity : Int32) #

Maximum entries kept; <= 0 means unbounded.


[View source]
def clear : Nil #

Empties the cache.


[View source]
def delete(key : K) : V | Nil #

Removes key, returning its value or nil.


[View source]
def each(& : Tuple(K, V) -> _) : Nil #

Yields each {key, value} pair (insertion order).


[View source]
def fetch(key : K, & : -> V) : V #

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.


[View source]
def has_key?(key : K) : Bool #

Whether key is present (distinguishes a cached nil value from absence).


[View source]
def size : Int32 #

Current number of entries.


[View source]