C Collections

chashmap · Section 3

chashmap_create_full

chashmap_create_full - create a hash map with full customization

C Collections (libccollections, -lccollections)

#include <ccollections/chashmap.h>
 
typedef unsigned long (*ccol_hashing_proc)(const void *ptr, size_t size);
typedef bool (*ccol_key_equality_proc)(const void *first,
                                         size_t first_size,
                                         const void *second,
                                         size_t second_size);
 
chmap chashmap_create_full(size_t initial_bucket_array_size,
                           ccol_data_type key_type,
                           ccol_data_type val_type,
                           ccol_memmgmt_procs *mmgmt_procs,
                           ccol_hashing_proc custom_hashing_proc,
                           ccol_key_equality_proc custom_key_equality_proc,
                           char **err);

Creates a hash map with full control over the initial size, the types,
the memory management, the hash function and the key equality function.
The map picks its implementation from the key and value types
and from custom_key_equality_proc.

initial_bucket_array_size  Initial number of buckets. A value of 0 is
                           refused and the call fails; a value from 1
                           to 16 gives 16 buckets, and a larger value is
                           rounded up to the next power of two
key_type                   Type of keys
val_type                   Type of values
mmgmt_procs                Custom memory management, or NULL
custom_hashing_proc        Custom hash function, or NULL
custom_key_equality_proc   Custom key equality function, or NULL for the
                           built-in comparison; it needs a
                           custom_hashing_proc that agrees with it
err                        Optional pointer that receives an error string

A pointer to the new hash map on success, or NULL on failure, for
example when a custom_key_equality_proc comes without a
custom_hashing_proc.

A key equality procedure receives both keys and both sizes and returns true when they are the same key. The map calls it instead of its built-in comparison for every lookup, update and delete. It must agree with custom_hashing_proc, so two keys that it reports as equal must get the same hash. Without a custom hash the procedure is refused, because the built-in hash reads the bytes of a key and can't agree with an equality that treats two different byte images as one key. The pointers carry no alignment for the key type, so read each field through memcpy.

A map with a key equality procedure always uses separate chaining, whatever the key and value types are.

Without a key equality procedure, a key of a type the map doesn't know (ccol_other_types, a struct for example) equals another key only when all of their bytes are equal, and the default hash reads every byte too, the padding bytes of a struct included. Two keys whose members are equal but whose padding differs are then two different keys, and a lookup misses.

Give such a key type a custom_hashing_proc and a custom_key_equality_proc that read only the members. Without them the bytes of a padded key must be fully determined. The raw functions, such as chashmap_insert_elem(3), read exactly the object that key_pair->ptr points at, so zero the whole key object with memset() before you set its members. The type-inferred macros hand the map their own copy of the key, and C leaves the padding of a struct copy unspecified. With GCC 11 or later the macros set that padding to zero, but with any other compiler a padded key passed through the macros needs the two procedures.

Every map has two hash modes and starts in the fast one. In the fast mode an integer, float, double or pointer key gets a Fibonacci multiply: The key times the odd 64-bit constant nearest to 2^64 divided by the golden ratio, read from the high bits of the product. On a 32-bit target a 64-bit key is multiplied at 64 bits as well, so both of its halves reach the index. A key with no fixed width, such as a string (ccol_string) or a struct (ccol_other_types), gets XXH64 with a secret 64-bit seed, and the result of a custom_hashing_proc goes through the murmur3 finalizer. In this mode a sequential run of integers costs one probe per lookup, and integers scaled by a power of two, aligned addresses, packed pairs, paths, identifiers and field names spread as a random function would.

In the keyed mode a fixed-width key and the result of a custom_hashing_proc go through a mixer of two multiplies that starts with an exclusive or against a secret 64-bit seed, and a key with no fixed width gets SipHash-1-3 with a secret 128-bit key. SipHash-1-3 is a keyed pseudorandom function, so no two inputs collide for every key, and without the key two inputs collide only by chance. The mixer spreads every set of keys as a random function would, which puts a lookup at about 1.3 probes at a load of 0.38 and about 2 at the maximum load of 0.70. A long double key gets SipHash-1-3 by its value in both modes. Which keys count as the same key, -0.0 and 0.0 included, is the same in both modes.

The fast hashes are either public or keyed in a way that some key sets defeat (XXH64 has collisions that hold for every seed). Whoever controls the keys, for example the member names of a JSON document or the identifiers in a request from the network, can pick a set that falls into one bucket or one cluster of a fast map. To catch that, every insert of a new key measures how far it had to go, which is the displacement of its slot from its home slot or the number of nodes in the chain it joins. A map switches to the keyed mode when:

  • one open-addressing insert lands more than its cap from its home slot (the cap is 24 slots for each doubling of the table up to 4096 slots, and 288 slots from there on);
  • one separate-chaining insert meets 20 nodes;
  • 256 consecutive inserts of new keys cost more in total than 256 times 5 * E(a) + 0.5 slots in an open-addressing table of 4096 slots or more, 6 * E(a) + 0.5 in a smaller one, or 4.5 * lambda + 0.5 nodes under separate chaining. Here E(a) = (1 / (1 - a)^2 - 1) / 2 is the expected displacement of an insert at load a under a random function, and lambda is the number of entries for each bucket. Both a and lambda are the highest load that the 256 inserts can have reached, so a bulk delete among them does not lower the bound;
  • a shrink merges clusters or chains past the first two limits.

A lookup never writes to the map and never switches it. Until the switch, whoever controls the keys can push an open-addressing insert to about 26 probes on average at a load of 0.70 (about 31 in a table below 4096 slots), and a single insert to no more than the cap. A separate-chaining insert meets about 7.3 nodes on average at 1.5 entries per bucket, and always fewer than 20. A lookup or a delete in an open-addressing map examines at most one slot more than the largest displacement of any key in the table, which the cap bounds while the map is fast. That bound also holds for a lookup inside a long run of keys whose home slots are consecutive, a run that no insert has to pay for.

The caps are far above what ordinary keys produce. Under a random function an open-addressing insert at the highest load is displaced by more than 288 slots about once in 1.4 * 10^9 inserts, and a separate-chaining insert at 1.5 entries per bucket meets 20 nodes about once in 10^15.

For an open-addressing map the switch rebuilds the table at the same size, and the references the map handed out become invalid, as at any insert. If that allocation fails, the map stays correct and in the fast mode, the insert that asked for the switch succeeds anyway, and the next insert that asks for it tries again. A separate-chaining map rehashes its nodes in place without allocating, so every reference to a key or a value, the insertion order and every iterator stay valid. A reset and a shrink keep the mode.

When a keyed map grows, it tries the fast mode on the new table (the doubled table of an open-addressing map, or the bucket array of a separate-chaining map that grows by four). It keeps the fast mode unless that fill shows that the keys collide under it: An open-addressing entry that would land more than the new table's cap from its home slot, a separate-chaining chain that would reach 20 nodes, or displacements or chain walks that add up to more than the count plus 64. The attempt stops at the first of these and the growth fills the same new table with the keyed hash, so nothing more is allocated. For a map of n entries a failed attempt inspects at most 2 * n + cap + 65 slots, or hashes n nodes and walks at most n + 83 chain nodes, on top of the keyed fill. Since growth is geometric, a map whose every growth fails pays a constant amount of extra work per insert: At most about four slots and two keyed placements per insert in an open-addressing table of 4096 slots or more, and about three node operations and 1.3 keyed hashes under separate chaining. A map that goes back to the fast mode is judged by its inserts again, so a resumed attack switches it within two windows of 256 inserts. Integer sets that cluster under the multiply only at some sizes, such as multiples of 24, 32, 48 or 96, switch at a small size and return to the fast mode at a later growth whose table spreads them well, and at other sizes they cluster again and the window switches the map back. Whether the attempt succeeds or not it keeps every entry, and under separate chaining it keeps every reference to a key or a value, the insertion order and every iterator. If the allocation of a growth fails, the map keeps its table and its mode, as with any growth.

The secrets come from getrandom(2), once per process, the first time the process creates a map. If the kernel can't answer without blocking, the library mixes the clocks, the process id and randomized addresses instead. Every map of the process uses the same secrets for its whole life, and a child made by fork(2) keeps its parent's secrets. A separate-chaining map iterates in insertion order, which does not depend on the mode or the secrets. An open-addressing map iterates in slot order, so its order depends on the mode, and in the keyed mode it differs from one process to the next; see chashmap_begin_iter(3).

Two keys that a custom_hashing_proc gives the same value collide in both modes, since no finalizer can tell them apart. A map that takes untrusted keys through a custom hash needs a custom function whose value two such keys cannot share.

A custom hash doesn't have to spread its own entropy. The map takes a bucket or slot index from the high bits of a hash, and a value that comes from a ccol_hashing_proc first goes through the finalizer of the map's current mode. So a hash can be an identity, a counter or a value already reduced modulo a small number, and it still distributes well.

Implementation selection:
  - Open addressing: Both key and value are integral types <=8 bytes,
    and custom_key_equality_proc is NULL
  - Separate chaining: Either key or value is non-integral or >8 bytes,
    or custom_key_equality_proc is not NULL
Integral types: char, short, int, long, long long (signed/unsigned),
               float, double
long double is excluded from open addressing (it can be 10-16 bytes).
Open addressing doubles the table on an insert of a new key once the
live entries fill more than 0.70 of it, and halves it on a delete that
leaves less than 0.25 of it live. A delete moves the later entries of
its cluster back into the gap, so the table keeps no marker for a
deleted slot and only live entries decide a resize. A grow leaves the
live load between 0.25 and 0.50, and a shrink leaves it below 0.50.
For a float or double key_type, a -0.0 key is always turned into 0.0
before it is hashed, stored or compared, which matches -0.0 == 0.0 in
C. That holds when custom_hashing_proc is not NULL too: The custom
function always gets the canonical bit pattern, and that is the value
the map stores.
A long double key_type always uses separate chaining, and key equality
and the hash work on the numeric value of the key instead of its raw
bytes. -0.0L and 0.0L are one key, as -0.0 and 0.0 are for float and
double, and two keys with the same value stay one key even when their
platform-defined padding bits differ. Every NaN long double is the same
key, unlike float and double, where each distinct NaN payload is a
different key.
None of this value-based handling applies when custom_hashing_proc is
not NULL, and the custom function then gets the raw bytes, padding
included. A custom hash function for a long double key type must
therefore use the numeric value itself, for example by hashing the
result of frexpl(3), or a lookup can miss a key that is in the map.

typedef struct { char tag; long id; } tagged_id;  /* padding after tag */
 
unsigned long tagged_id_hash(const void *p, size_t size) {
    tagged_id k;
    (void)size;
    memcpy(&k, p, sizeof(k));
    return (unsigned long)k.id * 31ul + (unsigned char)k.tag;
}
 
bool tagged_id_eq(const void *a, size_t as, const void *b, size_t bs) {
    tagged_id x, y;
    (void)as; (void)bs;
    memcpy(&x, a, sizeof(x));
    memcpy(&y, b, sizeof(y));
    return x.tag == y.tag && x.id == y.id;
}
 
char *err = NULL;
chmap m = chashmap_create_full(16, ccol_other_types, ccol_int, NULL,
                               tagged_id_hash, tagged_id_eq, &err);
if (!m) {
    fprintf(stderr, "cannot create map: %s\n", err);
    return 1;
}
/* ... chashmap_insert_elem(m, ...) ... */
chmap_destroy(m);

chashmap_begin_iter(3), chashmap_create(3), chmap_construct_full(3), chmap_init_full(3), chmap_destroy(3), ccol_determine_ccol_data_type(3)