Skip to content

Commit 9481877

Browse files
newrengitster
authored andcommitted
hashmap: ensure hashmaps are reusable after hashmap_clear()
In the series merged at bf0a430 (Merge branch 'en/strmap', 2020-11-21), strmap was built on top of hashmap and hashmap was extended in a few ways to support strmap and be more generally useful. One of the extensions was that hashmap_partial_clear() was introduced to allow reuse of the hashmap without freeing the table. Peff believed that it also made sense to introduce a hashmap_clear() which freed everything while allowing reuse. I added hashmap_clear(), but in doing so, overlooked the fact that for a hashmap to be reusable, it needs a defined cmpfn and data (the HASHMAP_INIT macro requires these fields as parameters, for example). So, if we want the hashmap to be reusable, we shouldn't zero out those fields. We probably also shouldn't zero out do_count_items. (We could zero out grow_at and shrink_at, but whether we zero those or not is irrelevant as they'll be automatically updated whenever a new entry is inserted.) Since clearing is associated with freeing map->table, and the only thing required for consistency after freeing map->table is zeroing tablesize and private_size, let's only zero those fields out. Signed-off-by: Elijah Newren <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent bf0a430 commit 9481877

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

hashmap.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,9 @@ void hashmap_clear_(struct hashmap *map, ssize_t entry_offset)
205205
return;
206206
if (entry_offset >= 0) /* called by hashmap_clear_and_free */
207207
free_individual_entries(map, entry_offset);
208-
free(map->table);
209-
memset(map, 0, sizeof(*map));
208+
FREE_AND_NULL(map->table);
209+
map->tablesize = 0;
210+
map->private_size = 0;
210211
}
211212

212213
struct hashmap_entry *hashmap_get(const struct hashmap *map,

0 commit comments

Comments
 (0)