C Collections

cvector · Section 3

cvec_init_mp

cvec_init_mp - create the vector behind a declared handle with a custom allocator

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_init_mp(v, mprocs);

Creates a vector and stores it in v just as cvec_init(3) does, except that
every allocation of the vector comes from mprocs instead of the default
allocator. v must be declared first with cvec_declare(3) or
cvec_declare_scoped(3), and the element size comes from the element type
of that declaration.
 
The vector keeps a private copy of the procedure table, so the
ccol_memmgmt_procs object passed here doesn't need to outlive the
vector, but the functions in the table do. When the vector is destroyed,
its backing buffer, the copy of the table and the container itself are
freed through those functions. A NULL mprocs is the same as calling
cvec_init(3).
 
The new vector is empty and starts at the minimum capacity of 4. The
capacity doubles when a push finds the buffer full and halves when the
element count drops below a quarter of it, but it never goes below that
minimum of 4.

v       Name of the vector variable that receives the new vector; it
        must be a plain identifier. cvec_declare(3) or
        cvec_declare_scoped(3) must have declared it, and its companion
        type variables must be in scope.
mprocs  Pointer to a ccol_memmgmt_procs. Its malloc, calloc, realloc
        and free members must all be set. Pass NULL for the default
        allocator.

None. The macro expands to a statement, not to an expression.

When the vector can't be created the macro stops the program through
ccol__fatal_err(), with a message that names v and the underlying error.
To handle a failed creation yourself, call cvector_create_full(3)
directly; it doesn't stop the program.
 
A procedure table with any of its four members left NULL is refused, and
that refusal is one of the failures that stop the program here.
 
The macro expands to a do/while block and needs a semicolon at the end of
the call.
 
v is evaluated more than once and pasted into the names of the companion
variables, so it must be a plain identifier and never an expression.
mprocs is evaluated once.
 
cvector_get_mprocs(3) reads back the table that created a vector.

ccol_memmgmt_procs procs = {
    .malloc = my_malloc, .calloc = my_calloc,
    .realloc = my_realloc, .free = my_free,
};
 
cvec_declare(my_vec, int);
cvec_init_mp(my_vec, &procs);
cvec_push(my_vec, 42);
cvec_destroy(my_vec);

cvec_init(3), cvec_declare(3), cvec_declare_scoped(3), cvec_construct_mp(3), cvec_destroy(3), cvector_create_full(3), cvector_get_mprocs(3)