| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#include <assert.h> |
| 5 |
#include <uthash.h> |
| 6 |
|
| 7 |
#include "cache.h" |
| 8 |
#include "misc.h" |
| 9 |
|
| 10 |
struct cache_handle *cache_get(struct cache *c, const char *key, size_t keylen) { |
| 11 |
struct cache_handle *e; |
| 12 |
HASH_FIND(hh, c->entries, key, keylen, e); |
| 13 |
return e; |
| 14 |
} |
| 15 |
|
| 16 |
int cache_get_or_fetch(struct cache *c, const char *key, size_t keylen, |
| 17 |
struct cache_handle **value, void *user_data, cache_getter_t getter) { |
| 18 |
*value = cache_get(c, key, keylen); |
| 19 |
if (*value) { |
| 20 |
return 0; |
| 21 |
} |
| 22 |
|
| 23 |
int err = getter(c, key, keylen, value, user_data); |
| 24 |
assert(err <= 0); |
| 25 |
if (err < 0) { |
| 26 |
return err; |
| 27 |
} |
| 28 |
|
| 29 |
(*value)->key = ccalloc(keylen + 1, char); |
| 30 |
memcpy((*value)->key, key, keylen); |
| 31 |
|
| 32 |
HASH_ADD_KEYPTR(hh, c->entries, (*value)->key, keylen, *value); |
| 33 |
return 1; |
| 34 |
} |
| 35 |
|
| 36 |
static inline void |
| 37 |
cache_invalidate_impl(struct cache *c, struct cache_handle *e, cache_free_t free_fn) { |
| 38 |
free(e->key); |
| 39 |
HASH_DEL(c->entries, e); |
| 40 |
if (free_fn) { |
| 41 |
free_fn(c, e); |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
void cache_invalidate_all(struct cache *c, cache_free_t free_fn) { |
| 46 |
struct cache_handle *e, *tmpe; |
| 47 |
HASH_ITER(hh, c->entries, e, tmpe) { |
| 48 |
cache_invalidate_impl(c, e, free_fn); |
| 49 |
} |
| 50 |
} |