C Collections

chashmap · Section 3

chmap_declare

chmap_declare - declare a hash map handle and its companion type variables

C Collections (libccollections, -lccollections)

#include <ccollections/chashmap.h>
 
chmap_declare(hm_name, KeyT, ValT);

Declares a hash map handle named hm_name, along with the companion type
variables that pass KeyT and ValT on to every later type-inferred
macro. Nothing is created, and the handle holds no map until one of the
init macros runs.
 
This is the declare half of a declare-then-create pair, and
chmap_init(3), chmap_init_mp(3), chmap_init_ch(3) and chmap_init_full(3)
are the matching create half. chmap_construct(3) and its variants do
both in one step, which is shorter for the common case. You need two
separate steps when the handle is declared in one place and created in
another, for example when a condition chooses the allocator, or when the
map is created only after the enclosing function has checked its
arguments.
 
The handle and the companion type variables are left uninitialized, so
until an init macro assigns it the handle holds no usable value, not
even NULL. chmap_declare_scoped(3) sets the handle to NULL instead and
also destroys the map at scope exit.

hm_name  Name for the map handle to declare
KeyT    Key type; it tells every later macro how to read a key and, with
         ValT, which implementation strategy the init macro selects
ValT    Value type

None. The macro expands to declarations and is not an expression.

Expands to a sequence of declarations, so it has to go where a
declaration is allowed, and it takes a trailing semicolon of its own
The companion type variables live in the scope of the handle, so a
function that receives the handle needs chmap_redeclare(3) inside it
Nothing is destroyed automatically, so call chmap_destroy(3) for the map
that an init macro creates into this handle
An array key or value type, such as int[2] or char[16], is a compile
error, and the message says to wrap the array in a struct. The macros copy
a key or a value by assignment and C cannot assign an array, so the map
would store the address of the caller's array instead of its elements. A
struct that holds the array works

Every other type-inferred macro reads the handle, so do not call one
between this declaration and an init macro, or it reads an uninitialized
variable.

chmap_declare(scores, char *, int);
if (use_custom_allocator) {
    chmap_init_mp(scores, &my_procs);
} else {
    chmap_init(scores);
}
int score = 42;
chmap_insert(scores, "alice", score);
chmap_destroy(scores);

chmap_declare_scoped(3), chmap_init(3), chmap_init_mp(3), chmap_init_ch(3), chmap_init_full(3), chmap_construct(3), chmap_redeclare(3), chmap_destroy(3)