Skip to content

Commit 6474b86

Browse files
newrengitster
authored andcommitted
hashmap: add usage documentation explaining hashmap_free[_entries]()
The existence of hashmap_free() and hashmap_free_entries() confused me, and the docs weren't clear enough. We are dealing with a map table, entries in that table, and possibly also things each of those entries point to. I had to consult other source code examples and the implementation. Add a brief note to clarify the differences. This will become even more important once we introduce a new hashmap_partial_clear() function which will add the question of whether the table itself has been freed. Signed-off-by: Elijah Newren <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent d4a3924 commit 6474b86

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

hashmap.h

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,40 @@ void hashmap_init(struct hashmap *map,
236236
void hashmap_free_(struct hashmap *map, ssize_t offset);
237237

238238
/*
239-
* Frees a hashmap structure and allocated memory, leaves entries undisturbed
239+
* Frees a hashmap structure and allocated memory for the table, but does not
240+
* free the entries nor anything they point to.
241+
*
242+
* Usage note:
243+
*
244+
* Many callers will need to iterate over all entries and free the data each
245+
* entry points to; in such a case, they can free the entry itself while at it.
246+
* Thus, you might see:
247+
*
248+
* hashmap_for_each_entry(map, hashmap_iter, e, hashmap_entry_name) {
249+
* free(e->somefield);
250+
* free(e);
251+
* }
252+
* hashmap_free(map);
253+
*
254+
* instead of
255+
*
256+
* hashmap_for_each_entry(map, hashmap_iter, e, hashmap_entry_name) {
257+
* free(e->somefield);
258+
* }
259+
* hashmap_free_entries(map, struct my_entry_struct, hashmap_entry_name);
260+
*
261+
* to avoid the implicit extra loop over the entries. However, if there are
262+
* no special fields in your entry that need to be freed beyond the entry
263+
* itself, it is probably simpler to avoid the explicit loop and just call
264+
* hashmap_free_entries().
240265
*/
241266
#define hashmap_free(map) hashmap_free_(map, -1)
242267

243268
/*
244269
* Frees @map and all entries. @type is the struct type of the entry
245-
* where @member is the hashmap_entry struct used to associate with @map
270+
* where @member is the hashmap_entry struct used to associate with @map.
271+
*
272+
* See usage note above hashmap_free().
246273
*/
247274
#define hashmap_free_entries(map, type, member) \
248275
hashmap_free_(map, offsetof(type, member));

0 commit comments

Comments
 (0)