cache: cache_get can now return error

Signed-off-by: Yuxuan Shui <yshuiv7@gmail.com>
This commit is contained in:
Yuxuan Shui 2019-05-06 00:28:22 +01:00
parent 93e4a53d48
commit 76c484885d
No known key found for this signature in database
GPG Key ID: 37C999F617EA1A47
2 changed files with 16 additions and 4 deletions

View File

@ -16,16 +16,28 @@ struct cache {
struct cache_entry *entries; struct cache_entry *entries;
}; };
void *cache_get(struct cache *c, const char *key) { void *cache_get(struct cache *c, const char *key, int *err) {
struct cache_entry *e; struct cache_entry *e;
HASH_FIND_STR(c->entries, key, e); HASH_FIND_STR(c->entries, key, e);
if (e) { if (e) {
return e->value; return e->value;
} }
int tmperr;
if (!err) {
err = &tmperr;
}
*err = 0;
e = ccalloc(1, struct cache_entry); e = ccalloc(1, struct cache_entry);
e->key = strdup(key); e->key = strdup(key);
e->value = c->getter(c->user_data, key); e->value = c->getter(c->user_data, key, err);
if (*err) {
free(e->key);
free(e);
return NULL;
}
HASH_ADD_STR(c->entries, key, e); HASH_ADD_STR(c->entries, key, e);
return e->value; return e->value;
} }

View File

@ -2,11 +2,11 @@
struct cache; struct cache;
typedef void *(*cache_getter_t)(void *user_data, const char *key); typedef void *(*cache_getter_t)(void *user_data, const char *key, int *err);
typedef void (*cache_free_t)(void *user_data, void *data); typedef void (*cache_free_t)(void *user_data, void *data);
struct cache *new_cache(void *user_data, cache_getter_t getter, cache_free_t f); struct cache *new_cache(void *user_data, cache_getter_t getter, cache_free_t f);
void *cache_get(struct cache *, const char *key); void *cache_get(struct cache *, const char *key, int *err);
void cache_invalidate(struct cache *, const char *key); void cache_invalidate(struct cache *, const char *key);
void cache_invalidate_all(struct cache *); void cache_invalidate_all(struct cache *);