C Collections

cbstmap · Section 3

cbstmap_create_ch

cbstmap_create_ch - create a BST map ordered by a custom comparison procedure

C Collections (libccollections, -lccollections)

#include <ccollections/cbstmap.h>
 
typedef int (*ccol_comparison_proc)(const void *first,
                                      const void *second);
 
cbmap cbstmap_create_ch(ccol_data_type key_type,
                        ccol_comparison_proc custom_comparison_proc,
                        char **err);

Creates a self-balancing BST map whose keys are ordered by
custom_comparison_proc. It is a thin inline wrapper over
cbstmap_create_full(3) that passes NULL for the memory management
procedures, so the map uses the default allocator. The type-inferred
equivalents are cbmap_construct_cc(3) and cbmap_init_cc(3).
 
The procedure only decides the order of the keys. key_type sets the width
that the map expects of every key_pair of a fixed-width key type, and it
also sets the alignment of every stored key.
 
cbmap_construct_cc(3) gives the full contract of the procedure. In short,
it returns a negative value, zero or a positive value, it defines key
equality as well as key order, and the order it gives must be consistent
and transitive for the whole life of the map.

key_type                Type of the keys that the map stores
custom_comparison_proc  Comparison procedure, or NULL for the default
                        order for key_type
err                     Optional pointer that receives an error string on
                        failure, or NULL

A new map on success. On failure it returns NULL and, when err is not
NULL, sets *err to an error string.

The procedure gets two bare pointers to key bytes, and a key that comes in
through the raw layer can sit at any address. Read a key wider than one
byte with memcpy, not through a pointer cast to the key type. The
procedure must stay callable for the whole life of the map.
 
This function reports a failure to the caller, while the
cbmap_construct_cc(3) and cbmap_init_cc(3) macros call ccol__fatal_err()
on a failure.
 
Destroy the map with cbmap_destroy(3).

typedef struct { int major; int minor; } version;
 
int version_cmp(const void *a, const void *b) {
    version x, y;
    memcpy(&x, a, sizeof(x));
    memcpy(&y, b, sizeof(y));
    if (x.major != y.major) {
        return (x.major > y.major) - (x.major < y.major);
    }
    return (x.minor > y.minor) - (x.minor < y.minor);
}
 
char *err = NULL;
cbmap releases = cbstmap_create_ch(ccol_other_types, version_cmp, &err);
if (!releases) {
    fprintf(stderr, "%s\n", err);
    return 1;
}
/* ... cbstmap_insert_elem(releases, ...) ... */
cbmap_destroy(releases);

cbstmap_create(3), cbstmap_create_full(3), cbmap_construct_cc(3), cbmap_init_cc(3), cbmap_destroy(3), ccol_determine_ccol_data_type(3)