Skip to content

Cache

Cache is a bounded least-recently-used cache (NSCache in shape): values stored under string keys, at most capacity of them. A set that would go over evicts the entry used least recently, and every get and set counts as a use. It is what a thumbnail, image or parsed-resource cache uses to stay bounded. From 0.72.

#import "Cache.xc" // or the Foundation umbrella
Cache* thumbs = new Cache();
thumbs.setCapacity((i32)64);
thumbs.set("a.png", image);
Image* i = (Image* ?)thumbs.get("a.png"); // null once evicted

Keys are copied into a String the cache owns, so the caller’s buffer may change or go away after the call.

Storage is a Map from each key to its entry and a doubly linked list of the entries from most to least recently used, so get, set and eviction are all close to O(1).

Ownership (ARC). The cache holds a strong reference to each value while it is cached, and releases it on eviction or removal.

Capacity · setCapacity · capacity · count

Storing and reading · set · get · contains

Removing · remove · removeAll


void setCapacity(i32 n)

At most n entries (at least 1); evicts down to it now, least recently used first.

i32 capacity(void)

The most entries the cache keeps.

i32 count(void)

The number of entries.

↑ Topics

void set(u8* key, Object* value)

Stores value under key, replacing what was there, and marks it most recently used; then evicts the least recently used entries past the capacity.

Object* get(u8* key)

The value under key, or null if absent or evicted; marks it most recently used.

bool contains(u8* key)

Whether key is cached. It does not count as a use.

↑ Topics

void remove(u8* key)

Removes the entry under key, if any.

void removeAll(void)

Empties the cache, releasing every value.

↑ Topics