From af8f650a07f89eaed72277e6af20b5d17feb97dc Mon Sep 17 00:00:00 2001 From: bjorn Date: Tue, 14 Jun 2022 16:52:19 -0700 Subject: [PATCH] Make map_t size deterministic; Currently, the amount of memory allocated for a map can sometimes be different depending on whether it was allocated with an initial capacity or the items were added iteratively. This causes problems for people that want to copy data between maps that have the same number of elements. Now, the size of a map will always be the same for a given number of elements, regardless of how the elements are added. Plus this gets rid of the weird prevpo2 function. Yay. --- src/util.c | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/util.c b/src/util.c index 61a17e61..6463c918 100644 --- a/src/util.c +++ b/src/util.c @@ -65,15 +65,6 @@ void* arr_alloc(void* data, size_t size) { } // Hashmap -static uint32_t prevpo2(uint32_t x) { - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; - return x - (x >> 1); -} - static void map_rehash(map_t* map) { map_t old = *map; map->size <<= 1; @@ -110,7 +101,10 @@ static inline uint64_t map_find(map_t* map, uint64_t hash) { } void map_init(map_t* map, uint32_t n) { - map->size = prevpo2(n) + !n; + map->size = 1; + while (map->size + (map->size >> 1) < n) { + map->size <<= 1; + } map->used = 0; map->hashes = NULL; map_rehash(map);