chashmap · Section 3
chashmap_destroy_with_dtor
NAME
chashmap_destroy_with_dtor - destroy a hash map, running a destructor on every value first, without allocating memory
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/chashmap.h>
void chashmap_destroy_with_dtor(chmap chm,
void (*val_dtor)(const cmap_pair *val_pair, void *dtor_ctx),
void *dtor_ctx);
DESCRIPTION
Destroys the map exactly as chmap_destroy(3) does, except that when val_dtor is not NULL it is called once for each live entry, with that entry's own value as a cmap_pair, right before the entry is freed. The function allocates no memory of its own. It walks the map's internal storage directly and calls the destructor inside that walk, while walking with chashmap_begin_iter(3) and destroying afterwards does allocate. It is meant for a map whose values are owned pointers to bigger structures that need their own recursive teardown, a dictionary of dictionaries for example. You could also destroy such a map by walking it with chashmap_begin_iter(3), running a value destructor on each entry and destroying the empty map at the end, but that leaves a real gap under memory pressure. The small internal allocation of chashmap_begin_iter(3) can fail, and then there is no way left to reach and free the values the map still owns. This function has no such gap, since it allocates nothing. The cmap_pair that val_dtor receives describes the stored value of the entry. val_pair->ptr points into storage that the map is about to free, val_pair->size is the size of the value, and the target is const. A destructor reads val_pair->ptr and val_pair->size and frees whatever the value itself owns, usually a pointer copied out of those bytes. Assigning to val_pair->ptr or val_pair->size is a compile error.
PARAMETERS
chm Hash map to destroy
val_dtor Destructor called once for each live value before its
entry is freed, or NULL to destroy the map with no callback
per value. Its val_pair parameter is a const cmap_pair *
dtor_ctx Opaque pointer forwarded unchanged to every val_dtor call
NOTES
Safe to call with a NULL chm (a no-op) Does not set the chm handle to NULL; use chmap_destroy(3) when the handle has to be cleared too val_dtor must not change chm itself, because the map is in the middle of its teardown for the whole call The pair describes storage that the map is about to free, and the map cannot own a pointer it did not allocate itself. That is why assigning to either field of the pair is a compile error rather than just a rule to remember Allocates nothing of its own, so it cannot fail under any memory condition that makes chashmap_begin_iter(3) fail
SEE ALSO
chmap_destroy(3), chashmap_get_elem_ref(3), chashmap_begin_iter(3)