2019-05-03 11:20:47 -04:00
|
|
|
#include <uthash.h>
|
|
|
|
|
|
|
|
#include "cache.h"
|
|
|
|
|
2024-02-17 19:40:07 -05:00
|
|
|
struct cache_handle *cache_get(struct cache *c, const char *key, size_t keylen) {
|
2024-02-15 16:08:48 -05:00
|
|
|
struct cache_handle *e;
|
2024-02-17 19:40:07 -05:00
|
|
|
HASH_FIND(hh, c->entries, key, keylen, e);
|
2024-02-15 15:05:09 -05:00
|
|
|
return e;
|
|
|
|
}
|
2020-12-26 02:25:34 -05:00
|
|
|
|
2024-02-17 19:40:07 -05:00
|
|
|
int cache_get_or_fetch(struct cache *c, const char *key, size_t keylen,
|
|
|
|
struct cache_handle **value, void *user_data, cache_getter_t getter) {
|
|
|
|
*value = cache_get(c, key, keylen);
|
2024-02-15 16:08:48 -05:00
|
|
|
if (*value) {
|
|
|
|
return 0;
|
2019-05-03 11:20:47 -04:00
|
|
|
}
|
|
|
|
|
2024-02-17 19:40:07 -05:00
|
|
|
int err = getter(c, key, keylen, value, user_data);
|
2024-02-15 16:08:48 -05:00
|
|
|
assert(err <= 0);
|
|
|
|
if (err < 0) {
|
|
|
|
return err;
|
2019-05-05 19:28:22 -04:00
|
|
|
}
|
2024-02-17 19:40:07 -05:00
|
|
|
// Add a NUL terminator to make things easier
|
2024-02-17 20:16:58 -05:00
|
|
|
(*value)->key = ccalloc(keylen + 1, char);
|
2024-02-17 19:40:07 -05:00
|
|
|
memcpy((*value)->key, key, keylen);
|
2019-05-05 19:28:22 -04:00
|
|
|
|
2024-02-17 19:40:07 -05:00
|
|
|
HASH_ADD_KEYPTR(hh, c->entries, (*value)->key, keylen, *value);
|
2024-02-15 16:08:48 -05:00
|
|
|
return 1;
|
2019-05-03 11:20:47 -04:00
|
|
|
}
|
|
|
|
|
2024-02-15 16:08:48 -05:00
|
|
|
static inline void
|
|
|
|
cache_invalidate_impl(struct cache *c, struct cache_handle *e, cache_free_t free_fn) {
|
2019-05-04 23:55:42 -04:00
|
|
|
free(e->key);
|
2019-05-03 11:20:47 -04:00
|
|
|
HASH_DEL(c->entries, e);
|
2024-02-15 16:08:48 -05:00
|
|
|
if (free_fn) {
|
|
|
|
free_fn(c, e);
|
|
|
|
}
|
2019-05-03 11:20:47 -04:00
|
|
|
}
|
|
|
|
|
2024-02-15 16:08:48 -05:00
|
|
|
void cache_invalidate_all(struct cache *c, cache_free_t free_fn) {
|
|
|
|
struct cache_handle *e, *tmpe;
|
2019-05-03 11:20:47 -04:00
|
|
|
HASH_ITER(hh, c->entries, e, tmpe) {
|
2024-02-15 16:08:48 -05:00
|
|
|
cache_invalidate_impl(c, e, free_fn);
|
2019-05-03 11:20:47 -04:00
|
|
|
}
|
|
|
|
}
|