From 54b1960d18042cf6dfd86cfe01d58455357586d2 Mon Sep 17 00:00:00 2001 From: Daniel Silverstone Date: Sun, 23 Feb 2020 16:46:22 +0000 Subject: utils: Add iteration API to hashmap Signed-off-by: Daniel Silverstone --- utils/hashmap.c | 19 +++++++++++++++++++ utils/hashmap.h | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+) (limited to 'utils') diff --git a/utils/hashmap.c b/utils/hashmap.c index 7ed19946b..bfbf6ceb8 100644 --- a/utils/hashmap.c +++ b/utils/hashmap.c @@ -213,3 +213,22 @@ hashmap_remove(hashmap_t *hashmap, void *key) return false; } + +/* Exported function, documented in hashmap.h */ +bool +hashmap_iterate(hashmap_t *hashmap, hashmap_iteration_cb_t cb, void *ctx) +{ + for (uint32_t bucket = 0; + bucket < hashmap->bucket_count; + bucket++) { + for (hashmap_entry_t *entry = hashmap->buckets[bucket]; + entry != NULL; + entry = entry->next) { + /* If the callback returns true, we early-exit */ + if (cb(entry->key, entry->value, ctx)) + return true; + } + } + + return false; +} diff --git a/utils/hashmap.h b/utils/hashmap.h index 462b51ed2..cb8fd5074 100644 --- a/utils/hashmap.h +++ b/utils/hashmap.h @@ -61,6 +61,16 @@ typedef void* (*hashmap_value_alloc_t)(void *); */ typedef void (*hashmap_value_destroy_t)(void *); +/** + * Hashmap iteration callback function type. + * + * First parameter is the key, second is the value. + * The final parameter is the context pointer for the iteration. + * + * Return true to stop iterating early + */ +typedef bool (*hashmap_iteration_cb_t)(void *, void *, void *); + /** * Parameters for hashmaps */ @@ -163,5 +173,17 @@ void *hashmap_insert(hashmap_t *hashmap, void *key); */ bool hashmap_remove(hashmap_t *hashmap, void *key); +/** + * Iterate the hashmap + * + * For each key/value pair in the hashmap, call the callback passing in + * the key and value. During iteration you MUST NOT mutate the hashmap. + * + * \param hashmap The hashmap to iterate + * \param cb The callback for each key,value pair + * \param ctx The callback context + * \return Whether or not we stopped iteration early + */ +bool hashmap_iterate(hashmap_t *hashmap, hashmap_iteration_cb_t cb, void *ctx); #endif -- cgit v1.2.3