Debian Codegraph @

src/utils/cache.h

raw symbols SCIP
1 // SPDX-License-Identifier: MPL-2.0
2 // Copyright (c) Yuxuan Shui <[email protected]>
3
4 #pragma once
5
6 #include <uthash.h>
7
8 #define cache_entry(ptr, type, member) container_of(ptr, type, member)
9
10 struct cache;
11 struct cache_handle;
12
13 /// User-provided function to fetch a value for the cache, when it's not present.
14 /// Should return 0 if the value is fetched successfully, and a negative number if the
15 /// value cannot be fetched. Getter doesn't need to initialize fields of `struct
16 /// cache_handle`.
17 typedef int (*cache_getter_t)(struct cache *, const char *key, size_t keylen,
18 struct cache_handle **value, void *user_data);
19 typedef void (*cache_free_t)(struct cache *, struct cache_handle *value);
20
21 struct cache {
22 struct cache_handle *entries;
23 };
24
25 static const struct cache CACHE_INIT = {NULL};
26
27 struct cache_handle {
28 char *key;
29 UT_hash_handle hh;
30 };
31
32 /// Get a value from the cache. If the value doesn't present in the cache yet, the
33 /// getter will be called, and the returned value will be stored into the cache.
34 /// Returns 0 if the value is already present in the cache, 1 if the value is fetched
35 /// successfully, and a negative number if the value cannot be fetched.
36 int cache_get_or_fetch(struct cache *, const char *key, size_t keylen,
37 struct cache_handle **value, void *user_data, cache_getter_t getter);
38
39 /// Get a value from the cache. If the value doesn't present in the cache, NULL will be
40 /// returned.
41 struct cache_handle *cache_get(struct cache *, const char *key, size_t keylen);
42
43 /// Invalidate all values in the cache. After this call, `struct cache` holds no allocated
44 /// memory, and can be discarded.
45 void cache_invalidate_all(struct cache *, cache_free_t free_fn);