From e3d4ce6612a7b11cbf04e1db60c4b854a701730b Mon Sep 17 00:00:00 2001 From: Yuxuan Shui Date: Sat, 26 Dec 2020 07:25:34 +0000 Subject: [PATCH] cache: add cache_set for testing Also add documentation for the cache functions. Signed-off-by: Yuxuan Shui --- src/cache.c | 11 +++++++++++ src/cache.h | 20 +++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/cache.c b/src/cache.c index bab1874..1ffb31c 100644 --- a/src/cache.c +++ b/src/cache.c @@ -17,6 +17,17 @@ struct cache { struct cache_entry *entries; }; +void cache_set(struct cache *c, const char *key, void *data) { + struct cache_entry *e = NULL; + HASH_FIND_STR(c->entries, key, e); + CHECK(!e); + + e = ccalloc(1, struct cache_entry); + e->key = strdup(key); + e->value = data; + HASH_ADD_STR(c->entries, key, e); +} + void *cache_get(struct cache *c, const char *key, int *err) { struct cache_entry *e; HASH_FIND_STR(c->entries, key, e); diff --git a/src/cache.h b/src/cache.h index 5876ee2..3ca054f 100644 --- a/src/cache.h +++ b/src/cache.h @@ -4,11 +4,29 @@ struct cache; typedef void *(*cache_getter_t)(void *user_data, const char *key, int *err); typedef void (*cache_free_t)(void *user_data, void *data); + +/// Create a cache with `getter`, and a free function `f` which is used to free the cache +/// value when they are invalidated. +/// +/// `user_data` will be passed to `getter` and `f` when they are called. struct cache *new_cache(void *user_data, cache_getter_t getter, cache_free_t f); +/// Fetch a value from the cache. If the value doesn't present in the cache yet, the +/// getter will be called, and the returned value will be stored into the cache. void *cache_get(struct cache *, const char *key, int *err); + +/// Invalidate a value in the cache. void cache_invalidate(struct cache *, const char *key); + +/// Invalidate all values in the cache. void cache_invalidate_all(struct cache *); -/// Returns the user data passed to `new_cache` +/// Invalidate all values in the cache and free it. Returns the user data passed to +/// `new_cache` void *cache_free(struct cache *); + +/// Insert a key-value pair into the cache. Only used for internal testing. Takes +/// ownership of `data` +/// +/// If `key` already exists in the cache, this function will abort the program. +void cache_set(struct cache *c, const char *key, void *data);