master ohmu/fastfetch-openbsd / src / common / impl / FFcache.c
ohmu  ·  2026-10-15
 1#include "common/FFcache.h"
 2
 3// Entries are file scope statics owned by the cache owner, so they can be linked into a list
 4// without any allocation. The list holds every entry that has been used at least once: an entry
 5// that was never used has nothing to drop.
 6static FFcacheEntry* entries = nullptr;
 7
 8static void registerEntry(FFcacheEntry* entry) {
 9    if (entry->registered) {
10        return;
11    }
12
13    entry->registered = true;
14    entry->next = entries;
15    entries = entry;
16}
17
18void* ffCacheGet(FFcacheEntry* entry) {
19    if (ffCacheBeginInit(entry) && entry->init) {
20        entry->init(entry->storage);
21    }
22
23    return entry->storage;
24}
25
26bool ffCacheBeginInit(FFcacheEntry* entry) {
27    registerEntry(entry);
28
29    if (entry->initialized) {
30        return false;
31    }
32
33    entry->initialized = true;
34    return true;
35}
36
37void ffCacheInvalidate(FFcacheEntry* entry) {
38    if (!entry->initialized) {
39        return;
40    }
41
42    entry->initialized = false;
43
44    if (entry->destroy) {
45        entry->destroy(entry->storage);
46    }
47}
48
49void ffCacheInvalidateAll(void) {
50    for (FFcacheEntry* entry = entries; entry; entry = entry->next) {
51        ffCacheInvalidate(entry);
52    }
53}