C Collections

cbstmap · Section 3

cbmap_construct_mp

cbmap_construct_mp - declare and create an ordered map that takes its memory from a custom allocator

C Collections (libccollections, -lccollections)

#include <ccollections/cbstmap.h>
 
cbmap_construct_mp(hm_name, KeyT, ValT, mmgmt_procs);

Declares an ordered map handle named hm_name with the companion type
variables that carry KeyT and ValT to every later type-inferred macro,
then creates a map that takes all of its memory from mmgmt_procs.
 
This is cbmap_construct(3) with an allocator added; the keys keep the
default order for KeyT. cbmap_construct_cc(3) replaces the order instead,
and cbmap_construct_full(3) takes both. cbmap_construct_mp_scoped(3) is the
same macro with a cleanup attribute that destroys the map when the scope
exits.
 
The two-step form is cbmap_declare(3) followed by cbmap_init_mp(3). Use it
when the caller has to handle a creation failure and that failure must not
be fatal.

hm_name      Name for the map handle to declare
KeyT        Key type. Every later macro reads a key through it, and the
             container takes the order of the tree from it
ValT        Value type. Only the type-inferred macros read it; the
             library never passes it to the container
mmgmt_procs  Pointer to a ccol_memmgmt_procs, or NULL for the default
             allocator

None. The macro declares variables and doesn't expand to an expression.

The macro stops the program through ccol__fatal_err() if the creation
fails.
 
None of the four members of ccol_memmgmt_procs may be NULL. The map
copies the procedures into itself, so the caller's ccol_memmgmt_procs
doesn't have to outlive the call, but the procedures themselves must stay
callable for the whole life of the map. Every tree node that the map
allocates later comes from them, and everything the map frees goes back to
them.
 
The allocator doesn't affect the order. KeyT decides it, as
cbstmap_create_full(3) describes, and a walk goes in ascending key order.
 
Destroy the map with cbmap_destroy(3). The companion type variables follow
the scope of the handle, so a function that receives the handle needs
cbmap_redeclare(3) there.
 
An array key type 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. Keys and values
are copied by assignment and C can't assign an array, so the map would
otherwise keep the address of the caller's array instead of its elements.
A struct that holds the array works.

ccol_memmgmt_procs procs = {
    .malloc = my_malloc, .calloc = my_calloc,
    .realloc = my_realloc, .free = my_free,
};
 
cbmap_construct_mp(sorted, int, char *, &procs);
int k = 42;
cbmap_insert(sorted, k, "hello");
cbmap_destroy(sorted);

cbmap_construct(3), cbmap_construct_mp_scoped(3), cbmap_construct_cc(3), cbmap_construct_full(3), cbmap_init_mp(3), cbmap_declare(3), cbmap_redeclare(3), cbstmap_create_full(3), cbmap_destroy(3)