From 088917641f0865e11be5e81bf90de3dbc8cba19e Mon Sep 17 00:00:00 2001 From: Daniel Silverstone Date: Sun, 23 Feb 2020 20:18:08 +0000 Subject: utils: Add hashmap_count() Signed-off-by: Daniel Silverstone --- utils/hashmap.c | 23 ++++++++++++++++++++--- utils/hashmap.h | 8 ++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) (limited to 'utils') diff --git a/utils/hashmap.c b/utils/hashmap.c index b7870a3a7..814dc55b5 100644 --- a/utils/hashmap.c +++ b/utils/hashmap.c @@ -55,6 +55,11 @@ struct hashmap_s { * The number of buckets in this map */ uint32_t bucket_count; + + /** + * The number of entries in this map + */ + size_t entry_count; }; /* Exported function, documented in hashmap.h */ @@ -65,14 +70,16 @@ hashmap_create(hashmap_parameters_t *params) ret->params = params; ret->bucket_count = DEFAULT_HASHMAP_BUCKETS; + ret->entry_count = 0; ret->buckets = malloc(ret->bucket_count * sizeof(hashmap_entry_t *)); - memset(ret->buckets, 0, ret->bucket_count * sizeof(hashmap_entry_t *)); if (ret->buckets == NULL) { free(ret); return NULL; } - + + memset(ret->buckets, 0, ret->bucket_count * sizeof(hashmap_entry_t *)); + return ret; } @@ -176,7 +183,9 @@ hashmap_insert(hashmap_t *hashmap, void *key) } hashmap->buckets[bucket] = entry; - + + hashmap->entry_count++; + return entry->value; err: @@ -207,6 +216,7 @@ hashmap_remove(hashmap_t *hashmap, void *key) } *entry->prevptr = entry->next; free(entry); + hashmap->entry_count--; return true; } } @@ -233,3 +243,10 @@ hashmap_iterate(hashmap_t *hashmap, hashmap_iteration_cb_t cb, void *ctx) return false; } + +/* Exported function, documented in hashmap.h */ +size_t +hashmap_count(hashmap_t *hashmap) +{ + return hashmap->entry_count; +} diff --git a/utils/hashmap.h b/utils/hashmap.h index cb8fd5074..3968fd3fe 100644 --- a/utils/hashmap.h +++ b/utils/hashmap.h @@ -186,4 +186,12 @@ bool hashmap_remove(hashmap_t *hashmap, void *key); */ bool hashmap_iterate(hashmap_t *hashmap, hashmap_iteration_cb_t cb, void *ctx); +/** + * Get the number of entries in this map + * + * \param hashmap The hashmap to retrieve the entry count from + * \return The number of entries in the hashmap + */ +size_t hashmap_count(hashmap_t *hashmap); + #endif -- cgit v1.2.3