LCOV - code coverage report
Current view: top level - include - common.h (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 96.9 % 64 62
Test Date: 2026-11-15 18:57:05 Functions: 100.0 % 3 3
Legend: Lines: hit not hit

            Line data    Source code
       1              : /*
       2              : MIT License
       3              : 
       4              : Copyright (c) 2026 - A bunch of nerds
       5              : 
       6              : Permission is hereby granted, free of charge, to any person obtaining a copy
       7              : of this software and associated documentation files (the "Software"), to deal
       8              : in the Software without restriction, including without limitation the rights
       9              : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      10              : copies of the Software, and to permit persons to whom the Software is
      11              : furnished to do so, subject to the following conditions:
      12              : 
      13              : The above copyright notice and this permission notice shall be included in all
      14              : copies or substantial portions of the Software.
      15              : 
      16              : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      17              : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      18              : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      19              : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      20              : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      21              : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      22              : SOFTWARE.
      23              : */
      24              : 
      25              : #pragma once
      26              : 
      27              : // Common definitions of the library: The version, the pthread wrappers, error
      28              : // reporting, the allocator layer, the return codes, type introspection with
      29              : // _Generic, and the key/value carrier of the maps. Every other header includes
      30              : // it.
      31              : #include <ctype.h>
      32              : #include <errno.h>
      33              : #include <limits.h>
      34              : #include <pthread.h>
      35              : #include <semaphore.h>
      36              : #include <time.h>
      37              : #include <unistd.h>
      38              : #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 202311L
      39              : #include <stdbool.h>
      40              : #endif
      41              : #include <stddef.h>
      42              : #include <stdint.h>
      43              : #include <stdio.h>
      44              : #include <stdlib.h>
      45              : #include <string.h>
      46              : 
      47              : // Everything from here to the matching pop is the public ABI and the shared
      48              : // library exports it. The library builds with -fvisibility=hidden, so anything
      49              : // outside these blocks stays internal and can't collide with a symbol of an
      50              : // application.
      51              : #pragma GCC visibility push(default)
      52              : 
      53              : // Version
      54              : //
      55              : // The release this header belongs to. The root Makefile reads the three numbers
      56              : // from here, so the header, the library's file name and the pkg-config version
      57              : // always agree.
      58              : 
      59              : // The major number of the release this header belongs to, below 256. The
      60              : // version of the library loaded at run time comes from ccol_version().
      61              : #define CCOL_VERSION_MAJOR 2
      62              : // The minor number of the release this header belongs to, below 256. The
      63              : // version of the library loaded at run time comes from ccol_version().
      64              : #define CCOL_VERSION_MINOR 0
      65              : // The patch number of the release this header belongs to, below 256. The
      66              : // version of the library loaded at run time comes from ccol_version().
      67              : #define CCOL_VERSION_PATCH 0
      68              : // The release this header belongs to, packed as 0xMMmmpp so that versions
      69              : // compare as integers (2.1.3 is 0x020103); use it for a version test in #if.
      70              : // ccol_version() gives the version of the library loaded at run time.
      71              : #define CCOL_VERSION_NUMBER \
      72              :   ((CCOL_VERSION_MAJOR << 16) | (CCOL_VERSION_MINOR << 8) | CCOL_VERSION_PATCH)
      73              : // The release this header belongs to, as a string literal such as "2.0.0",
      74              : // for messages. ccol_version_string() gives the version of the library loaded
      75              : // at run time.
      76              : #define CCOL_VERSION_STRING                                    \
      77              :   ccol__x_stringify(CCOL_VERSION_MAJOR) "." ccol__x_stringify( \
      78              :       CCOL_VERSION_MINOR) "." ccol__x_stringify(CCOL_VERSION_PATCH)
      79              : 
      80              : // Gives the version of the library the program runs with, packed as 0xMMmmpp
      81              : // (2.1.3 is 0x020103) so that versions compare as integers. The
      82              : // CCOL_VERSION_ macros give the version of the header you compiled with; use
      83              : // this to learn the one the dynamic loader picked, which can be a later
      84              : // release with the same SONAME.
      85              : unsigned int ccol_version(void);
      86              : 
      87              : // Gives the version of the library the program runs with as a string such as
      88              : // "2.0.0", for logs and messages. The string is static: Don't free it. It can
      89              : // differ from CCOL_VERSION_STRING, the version of the header you compiled
      90              : // with, when the dynamic loader picked a later release with the same SONAME.
      91              : const char *ccol_version_string(void);
      92              : 
      93              : // Fork safety switch
      94              : #ifndef CCOL_FORK_SAFETY_REQUIRED
      95              : // Build switch, 1 by default. With 1, some modules (cthreadpool, cthreadcomm,
      96              : // clogger, chttpserver, chttpclient) register pthread_atfork() handlers that
      97              : // lock every live handle before a fork, so the child never inherits a mutex
      98              : // that stays locked for ever; that costs work on every fork() of the process.
      99              : // A program that never forks, or always calls exec() right after fork(), can
     100              : // build the library with -DCCOL_FORK_SAFETY_REQUIRED=0 to drop those handlers
     101              : // and the state that exists only for them. The modules' own locks stay either
     102              : // way. Define it before the first include of this header.
     103              : #define CCOL_FORK_SAFETY_REQUIRED 1
     104              : #endif
     105              : 
     106              : // Internal. OpenBSD's fork() leaves the lock of its handler list held in the
     107              : // child, so a pthread_atfork() in a threaded child waits for ever. There every
     108              : // module registers its fork handlers at load, never on first use.
     109              : #if defined(__OpenBSD__)
     110              : #define CCOL__ATFORK_AT_LOAD 1
     111              : #endif
     112              : 
     113              : // Threading primitives
     114              : //
     115              : // Every wrapper below is internal. The library reaches pthreads and POSIX
     116              : // semaphores only through them, so a port to a system without pthreads replaces
     117              : // this header alone. Applications use pthreads or <threads.h> directly.
     118              : //
     119              : // macOS has no pthread_mutex_timedlock(), pthread_rwlock_timedwrlock(),
     120              : // pthread_condattr_setclock() or working sem_init(). CCOL__EMULATE_DARWIN_SYNC
     121              : // selects our replacements: A timed lock polls a try-lock, a condition variable
     122              : // remembers its clock, and a semaphore is a pipe. It's on by itself on macOS,
     123              : // and the Linux and FreeBSD test builds define it to run the same code.
     124              : #if defined(__APPLE__) && !defined(CCOL__EMULATE_DARWIN_SYNC)
     125              : #define CCOL__EMULATE_DARWIN_SYNC 1
     126              : #endif
     127              : 
     128              : // The close-on-exec gate. Where a descriptor can't be made close-on-exec in one
     129              : // call (sockets and pipes on macOS), the library creates it and sets FD_CLOEXEC
     130              : // afterwards, between ccol__cloexec_gate_enter() and
     131              : // ccol__cloexec_gate_leave(). Those take the read side of a process-wide lock
     132              : // and a fork-prepare handler takes the write side, so a fork() waits until no
     133              : // descriptor is between the two steps. posix_spawn(3) runs no fork handler, so
     134              : // a macOS program that spawns while the library makes a socket uses
     135              : // POSIX_SPAWN_CLOEXEC_DEFAULT. The gate exists only where the two steps exist;
     136              : // on Linux and FreeBSD it costs nothing. These functions are hidden.
     137              : #if defined(__APPLE__) || defined(CCOL__EMULATE_DARWIN_SYNC) || \
     138              :     defined(CCOL__EMULATE_DARWIN_SOCK)
     139              : #define CCOL__CLOEXEC_GATE 1
     140              : #pragma GCC visibility push(hidden)
     141              : void ccol__cloexec_gate_enter(void);
     142              : void ccol__cloexec_gate_leave(void);
     143              : void ccol__cloexec_gate_register(void);
     144              : #pragma GCC visibility pop
     145              : #endif
     146              : 
     147              : // Mutex wrappers: The type, destroy, init with default attributes, lock,
     148              : // unlock, trylock and timedlock. Every module locks through them, so a port
     149              : // changes this header only. m is the mutex object (the macros take its
     150              : // address). Each evaluates to what the pthread call gives: 0 or an error
     151              : // number. trylock gives EBUSY instead of waiting; timedlock gives up with
     152              : // ETIMEDOUT at t, an absolute CLOCK_REALTIME struct timespec, through a
     153              : // try-lock loop on macOS.
     154              : #define ccol__mutex pthread_mutex_t
     155              : 
     156              : #define ccol__mutex_destroy(m) pthread_mutex_destroy(&(m))
     157              : 
     158              : #define ccol__mutex_init(m) pthread_mutex_init(&(m), NULL)
     159              : 
     160              : #define ccol__mutex_lock(m) pthread_mutex_lock(&(m))
     161              : 
     162              : #define ccol__mutex_unlock(m) pthread_mutex_unlock(&(m))
     163              : 
     164              : #define ccol__mutex_trylock(m) pthread_mutex_trylock(&(m))
     165              : 
     166              : #if defined(CCOL__EMULATE_DARWIN_SYNC)
     167              : #define ccol__mutex_timedlock(m, t) ccol__mutex_timedlock_poll(&(m), &(t))
     168              : #else
     169              : #define ccol__mutex_timedlock(m, t) pthread_mutex_timedlock(&(m), &(t))
     170              : #endif
     171              : 
     172              : // Read-write lock wrappers: The type, destroy, init, write lock, read lock,
     173              : // timed write lock and unlock, for the slot tables and registries that many
     174              : // threads read and few write. a is the lock object. Each evaluates to 0 or an
     175              : // error number; the timed write lock takes the same absolute CLOCK_REALTIME
     176              : // deadline t as ccol__mutex_timedlock.
     177              : #define ccol__rw_lock pthread_rwlock_t
     178              : 
     179              : #define ccol__rw_lock_destroy(a) pthread_rwlock_destroy(&(a))
     180              : 
     181              : #define ccol__rw_lock_init(a) pthread_rwlock_init(&(a), NULL)
     182              : 
     183              : // Initializes again, in the child of fork(), the rwlock a that the forking
     184              : // thread held for writing (as a fork-prepare handler leaves it). The fork child
     185              : // handlers need it because a plain unlock doesn't always release such a lock
     186              : // there: glibc checks the writer's thread ID, and the child's thread has a new
     187              : // one. macOS refuses to init an object it still sees as a lock in use, so the
     188              : // impl clears it first. Evaluates to 0 or an error number. The impl takes
     189              : // void * because a strict -std=c11 <pthread.h> declares no rwlock type.
     190              : #define ccol__rw_lock_reinit_in_child(a) \
     191              :   ccol__rw_lock_reinit_in_child_impl(&(a))
     192              : #pragma GCC visibility push(hidden)
     193              : int ccol__rw_lock_reinit_in_child_impl(void *lock);
     194              : #pragma GCC visibility pop
     195              : 
     196              : #define ccol__rw_lock_wrlock(a) pthread_rwlock_wrlock(&(a))
     197              : 
     198              : #define ccol__rw_lock_rdlock(a) pthread_rwlock_rdlock(&(a))
     199              : 
     200              : #if defined(CCOL__EMULATE_DARWIN_SYNC)
     201              : #define ccol__rw_lock_timedwrlock(a, t) \
     202              :   ccol__rw_lock_timedwrlock_poll(&(a), &(t))
     203              : #else
     204              : #define ccol__rw_lock_timedwrlock(a, t) pthread_rwlock_timedwrlock(&(a), &(t))
     205              : #endif
     206              : 
     207              : #define ccol__rw_lock_unlock(a) pthread_rwlock_unlock(&(a))
     208              : 
     209              : // Condition variable wrappers: The types, attribute init, destroy and setclock,
     210              : // init with default or given attributes (ca), wait, timed wait, signal and
     211              : // broadcast. Queues, pools and the logger wait on them, and the monotonic clock
     212              : // needs setclock. c is the condition variable and m its mutex, unlocked while
     213              : // waiting. Each evaluates to 0 or an error number; the timed wait gives
     214              : // ETIMEDOUT at t, an absolute deadline on the clock of c. On macOS the second
     215              : // set below emulates the clock.
     216              : #if !defined(CCOL__EMULATE_DARWIN_SYNC)
     217              : #define ccol__cond_var pthread_cond_t
     218              : 
     219              : #define ccol__cond_var_attr pthread_condattr_t
     220              : 
     221              : #define ccol__cond_var_attr_destroy(ca) pthread_condattr_destroy(&(ca))
     222              : 
     223              : #define ccol__cond_var_attr_init(ca) pthread_condattr_init(&(ca))
     224              : 
     225              : #define ccol__cond_var_attr_setclock(ca, clk) \
     226              :   pthread_condattr_setclock(&(ca), clk)
     227              : 
     228              : #define ccol__cond_var_destroy(c) pthread_cond_destroy(&(c))
     229              : 
     230              : #define ccol__cond_var_init(c) pthread_cond_init(&(c), NULL)
     231              : 
     232              : #define ccol__cond_var_init_ca(c, ca) pthread_cond_init(&(c), &(ca))
     233              : 
     234              : #define ccol__cond_var_wait(c, m) pthread_cond_wait(&(c), &(m))
     235              : 
     236              : #define ccol__cond_var_timedwait(c, m, t) \
     237              :   pthread_cond_timedwait(&(c), &(m), &(t))
     238              : 
     239              : #define ccol__cond_var_signal(c) pthread_cond_signal(&(c))
     240              : 
     241              : #define ccol__cond_var_broadcast(c) pthread_cond_broadcast(&(c))
     242              : #else
     243              : // The emulated condition variable and its attributes remember the clock of
     244              : // their deadlines (see CCOL__EMULATE_DARWIN_SYNC).
     245              : typedef struct {
     246              :   pthread_cond_t cond;
     247              :   clockid_t clock;
     248              : } ccol__cond_var_s;
     249              : typedef struct {
     250              :   clockid_t clock;
     251              : } ccol__cond_var_attr_s;
     252              : 
     253              : // Sets the clock of emulated condition variable attributes and gives 0. The
     254              : // attribute macros of the emulation use it, since there is no
     255              : // pthread_condattr_setclock() on macOS.
     256              : static inline int ccol__cond_var_attr_set(ccol__cond_var_attr_s *ca,
     257              :                                           clockid_t clk) {
     258              :   ca->clock = clk;
     259              :   return 0;
     260              : }
     261              : // Initializes an emulated condition variable that remembers clk, so
     262              : // ccol__cond_var_timedwait_clock knows how to read its deadlines. Gives what
     263              : // pthread_cond_init() gives.
     264              : static inline int ccol__cond_var_init_clock(ccol__cond_var_s *c,
     265              :                                             clockid_t clk) {
     266              :   c->clock = clk;
     267              :   return pthread_cond_init(&c->cond, NULL);
     268              : }
     269              : 
     270              : #define ccol__cond_var ccol__cond_var_s
     271              : #define ccol__cond_var_attr ccol__cond_var_attr_s
     272              : #define ccol__cond_var_attr_destroy(ca) \
     273              :   ccol__cond_var_attr_set(&(ca), (ca).clock)
     274              : #define ccol__cond_var_attr_init(ca) \
     275              :   ccol__cond_var_attr_set(&(ca), CLOCK_REALTIME)
     276              : #define ccol__cond_var_attr_setclock(ca, clk) \
     277              :   ccol__cond_var_attr_set(&(ca), (clk))
     278              : #define ccol__cond_var_destroy(c) pthread_cond_destroy(&(c).cond)
     279              : #define ccol__cond_var_init(c) ccol__cond_var_init_clock(&(c), CLOCK_REALTIME)
     280              : #define ccol__cond_var_init_ca(c, ca) \
     281              :   ccol__cond_var_init_clock(&(c), (ca).clock)
     282              : #define ccol__cond_var_wait(c, m) pthread_cond_wait(&(c).cond, &(m))
     283              : #define ccol__cond_var_timedwait(c, m, t) \
     284              :   ccol__cond_var_timedwait_clock(&(c), &(m), &(t))
     285              : #define ccol__cond_var_signal(c) pthread_cond_signal(&(c).cond)
     286              : #define ccol__cond_var_broadcast(c) pthread_cond_broadcast(&(c).cond)
     287              : #endif
     288              : 
     289              : // Semaphore wrappers: The type, init with count value, destroy, wait and post,
     290              : // on an unnamed process-private semaphore s. They exist for the one
     291              : // synchronization a signal handler may do: ccol__semaphore_post is
     292              : // async-signal-safe (POSIX says so for sem_post(3)), while mutexes, condition
     293              : // variables, thread creation and call_once are not. An entry point that must
     294              : // work from a signal handler posts to a watcher thread that does the real work,
     295              : // as the engine-stop watcher of chttpserver does. Init, destroy, wait and post
     296              : // evaluate to 0, or -1 with errno set. wait may block, so never call it from a
     297              : // handler.
     298              : #if !defined(CCOL__EMULATE_DARWIN_SYNC)
     299              : #define ccol__semaphore sem_t
     300              : 
     301              : #define ccol__semaphore_init(s, value) sem_init(&(s), 0, (value))
     302              : 
     303              : #define ccol__semaphore_destroy(s) sem_destroy(&(s))
     304              : 
     305              : #define ccol__semaphore_wait(s) sem_wait(&(s))
     306              : 
     307              : #define ccol__semaphore_post(s) sem_post(&(s))
     308              : #else
     309              : // The emulated semaphore is a pipe, one byte per unit. The write end doesn't
     310              : // block, so a post on a full pipe leaves the count as it is and still succeeds.
     311              : // That's safe because every user sets a request flag before it posts and the
     312              : // waiter reads every flag after each wake.
     313              : typedef struct {
     314              :   int fd[2];
     315              : } ccol__semaphore_s;
     316              : #define ccol__semaphore ccol__semaphore_s
     317              : #define ccol__semaphore_init(s, value) ccol__semaphore_pipe_init(&(s), (value))
     318              : #define ccol__semaphore_destroy(s) ccol__semaphore_pipe_destroy(&(s))
     319              : #define ccol__semaphore_wait(s) ccol__semaphore_pipe_wait(&(s))
     320              : #define ccol__semaphore_post(s) ccol__semaphore_pipe_post(&(s))
     321              : #endif
     322              : 
     323              : #if defined(CCOL__EMULATE_DARWIN_SYNC)
     324              : #include <fcntl.h>
     325              : 
     326              : // True once the clock clk has reached the absolute time t. The try-lock loops
     327              : // use it to stop at their deadline.
     328              : static inline bool ccol__time_reached(clockid_t clk, const struct timespec *t) {
     329              :   struct timespec now;
     330              :   clock_gettime(clk, &now);
     331              :   return now.tv_sec > t->tv_sec ||
     332              :          (now.tv_sec == t->tv_sec && now.tv_nsec >= t->tv_nsec);
     333              : }
     334              : 
     335              : // Sleeps one pause of a try-lock loop and updates *us, the length of the next:
     336              : // 20 microseconds at first, doubling up to 1 ms, so a short wait is cheap and a
     337              : // long one doesn't burn CPU.
     338              : static inline void ccol__try_lock_pause(unsigned *us) {
     339              :   *us = *us ? (*us >= 500u ? 1000u : *us * 2u) : 20u;
     340              :   struct timespec ts = {0, (long)*us * 1000L};
     341              :   nanosleep(&ts, NULL);
     342              : }
     343              : 
     344              : // Locks m or gives up at t on CLOCK_REALTIME, as a try-lock loop, because macOS
     345              : // has no pthread_mutex_timedlock(). Gives 0, ETIMEDOUT, or the try-lock's
     346              : // error.
     347              : static inline int ccol__mutex_timedlock_poll(pthread_mutex_t *m,
     348              :                                              const struct timespec *t) {
     349              :   unsigned us = 0;
     350              :   for (;;) {
     351              :     int rc = pthread_mutex_trylock(m);
     352              :     if (rc != EBUSY) return rc;
     353              :     if (ccol__time_reached(CLOCK_REALTIME, t)) return ETIMEDOUT;
     354              :     ccol__try_lock_pause(&us);
     355              :   }
     356              : }
     357              : 
     358              : // Takes the write side of a or gives up at t on CLOCK_REALTIME, as a try-lock
     359              : // loop, because macOS has no pthread_rwlock_timedwrlock(). Gives 0, ETIMEDOUT,
     360              : // or the try-lock's error.
     361              : static inline int ccol__rw_lock_timedwrlock_poll(pthread_rwlock_t *a,
     362              :                                                  const struct timespec *t) {
     363              :   unsigned us = 0;
     364              :   for (;;) {
     365              :     int rc = pthread_rwlock_trywrlock(a);
     366              :     if (rc != EBUSY) return rc;
     367              :     if (ccol__time_reached(CLOCK_REALTIME, t)) return ETIMEDOUT;
     368              :     ccol__try_lock_pause(&us);
     369              :   }
     370              : }
     371              : 
     372              : // Waits on c with m held until a deadline t on the clock that c remembers.
     373              : // It's the emulated ccol__cond_var_timedwait, needed because macOS can't set a
     374              : // condition variable's clock. A realtime deadline goes straight to
     375              : // pthread_cond_timedwait(). A monotonic one becomes the time left, worked out
     376              : // field by field so a saturated deadline can't overflow, and cut to 10^9
     377              : // seconds (every caller waits in a loop that checks its condition). macOS waits
     378              : // for it with pthread_cond_timedwait_relative_np(); a test build elsewhere adds
     379              : // it to the realtime clock, saturating at the largest time_t so a 32-bit time_t
     380              : // never wraps into the past. Gives 0 or ETIMEDOUT.
     381              : static inline int ccol__cond_var_timedwait_clock(ccol__cond_var_s *c,
     382              :                                                  pthread_mutex_t *m,
     383              :                                                  const struct timespec *t) {
     384              :   if (c->clock != CLOCK_MONOTONIC)
     385              :     return pthread_cond_timedwait(&c->cond, m, t);
     386              :   struct timespec now;
     387              :   clock_gettime(CLOCK_MONOTONIC, &now);
     388              :   struct timespec rel = {0, 0};
     389              :   if (t->tv_sec > now.tv_sec ||
     390              :       (t->tv_sec == now.tv_sec && t->tv_nsec > now.tv_nsec)) {
     391              :     if ((long long)t->tv_sec - (long long)now.tv_sec > 1000000000LL) {
     392              :       rel.tv_sec = (time_t)1000000000;
     393              :     } else {
     394              :       rel.tv_sec = t->tv_sec - now.tv_sec;
     395              :       rel.tv_nsec = t->tv_nsec - now.tv_nsec;
     396              :       if (rel.tv_nsec < 0) {
     397              :         rel.tv_sec--;
     398              :         rel.tv_nsec += 1000000000L;
     399              :       }
     400              :     }
     401              :   }
     402              : #if defined(__APPLE__)
     403              :   return pthread_cond_timedwait_relative_np(&c->cond, m, &rel);
     404              : #else
     405              :   struct timespec at;
     406              :   clock_gettime(CLOCK_REALTIME, &at);
     407              :   const long long tmax =
     408              :       sizeof(time_t) >= 8 ? (long long)INT64_MAX : (long long)INT32_MAX;
     409              :   if ((long long)rel.tv_sec > tmax - 1 - (long long)at.tv_sec) {
     410              :     at.tv_sec = (time_t)tmax;
     411              :     at.tv_nsec = 999999999L;
     412              :   } else {
     413              :     at.tv_sec += rel.tv_sec;
     414              :     at.tv_nsec += rel.tv_nsec;
     415              :     if (at.tv_nsec >= 1000000000L) {
     416              :       at.tv_sec++;
     417              :       at.tv_nsec -= 1000000000L;
     418              :     }
     419              :   }
     420              :   return pthread_cond_timedwait(&c->cond, m, &at);
     421              : #endif
     422              : }
     423              : 
     424              : // Initializes s as a semaphore with count value: A pipe holding value bytes,
     425              : // with a write end that doesn't block. It replaces sem_init(), which doesn't
     426              : // work on macOS. Both ends become close-on-exec inside the gate. Gives 0, or -1
     427              : // with errno set; a value the pipe can't hold fails with EINVAL.
     428              : static inline int ccol__semaphore_pipe_init(ccol__semaphore_s *s,
     429              :                                             unsigned value) {
     430              :   ccol__cloexec_gate_enter();
     431              :   if (pipe(s->fd) != 0) {
     432              :     int saved = errno;
     433              :     ccol__cloexec_gate_leave();
     434              :     errno = saved;
     435              :     return -1;
     436              :   }
     437              :   (void)fcntl(s->fd[0], F_SETFD, FD_CLOEXEC);
     438              :   (void)fcntl(s->fd[1], F_SETFD, FD_CLOEXEC);
     439              :   ccol__cloexec_gate_leave();
     440              :   int wfl = fcntl(s->fd[1], F_GETFL);
     441              :   if (wfl < 0 || fcntl(s->fd[1], F_SETFL, wfl | O_NONBLOCK) != 0) {
     442              :     int saved = errno;
     443              :     close(s->fd[0]);
     444              :     close(s->fd[1]);
     445              :     errno = saved;
     446              :     return -1;
     447              :   }
     448              :   for (unsigned i = 0; i < value; i++) {
     449              :     ssize_t n;
     450              :     do {
     451              :       n = write(s->fd[1], "", 1);
     452              :     } while (n < 0 && errno == EINTR);
     453              :     if (n != 1) {
     454              :       int saved =
     455              :           (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK) ? errno : EINVAL;
     456              :       close(s->fd[0]);
     457              :       close(s->fd[1]);
     458              :       errno = saved;
     459              :       return -1;
     460              :     }
     461              :   }
     462              :   return 0;
     463              : }
     464              : 
     465              : // Destroys the pipe semaphore s by closing both ends, like sem_destroy(). Gives
     466              : // 0.
     467              : static inline int ccol__semaphore_pipe_destroy(ccol__semaphore_s *s) {
     468              :   close(s->fd[0]);
     469              :   close(s->fd[1]);
     470              :   return 0;
     471              : }
     472              : 
     473              : // Waits until the count of s is above 0 and takes one unit, by reading one
     474              : // byte, like sem_wait(). Gives 0, or -1 with errno set; the end of the pipe and
     475              : // a descriptor that isn't open give EINVAL, as sem_wait() does for an invalid
     476              : // semaphore.
     477              : static inline int ccol__semaphore_pipe_wait(ccol__semaphore_s *s) {
     478              :   char b;
     479              :   for (;;) {
     480              :     ssize_t n = read(s->fd[0], &b, 1);
     481              :     if (n == 1) return 0;
     482              :     if (n < 0 && errno == EINTR) continue;
     483              :     if (n >= 0 || errno == EBADF) errno = EINVAL;
     484              :     return -1;
     485              :   }
     486              : }
     487              : 
     488              : // Adds one unit to s by writing one byte, like sem_post(), and is
     489              : // async-signal-safe like write(2), which is why the semaphore exists. A full
     490              : // pipe counts as success. Gives 0 or -1. errno keeps its value on success, so a
     491              : // post from a signal handler doesn't change the errno of the thread it
     492              : // interrupts.
     493              : static inline int ccol__semaphore_pipe_post(ccol__semaphore_s *s) {
     494              :   int saved = errno;
     495              :   for (;;) {
     496              :     ssize_t n = write(s->fd[1], "", 1);
     497              :     if (n == 1) {
     498              :       errno = saved;
     499              :       return 0;
     500              :     }
     501              :     if (n < 0 && errno == EINTR) continue;
     502              :     if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
     503              :       errno = saved;
     504              :       return 0;
     505              :     }
     506              :     return -1;
     507              :   }
     508              : }
     509              : #endif
     510              : 
     511              : // Thread wrappers: The id type, the caller's id, id comparison, create, join,
     512              : // signal mask and kill, for the worker, poller and writer threads of the
     513              : // modules. ccol__thread_create runs fn(arg) with default attributes and stores
     514              : // the thread in handle; join waits for it. sigmask takes how, set and oldset as
     515              : // pthread_sigmask() does, and kill sends sig to handle; both need <signal.h> in
     516              : // the caller. All evaluate to 0 or an error number, except equal (nonzero for
     517              : // the same thread) and get_thread_id.
     518              : #define ccol__thread_id pthread_t
     519              : 
     520              : #define ccol__get_thread_id pthread_self
     521              : 
     522              : #define ccol__thread_id_equal(a, b) pthread_equal((a), (b))
     523              : 
     524              : #define ccol__thread_create(handle, fn, arg) \
     525              :   pthread_create(&(handle), NULL, (fn), (arg))
     526              : 
     527              : #define ccol__thread_join(handle) pthread_join((handle), NULL)
     528              : 
     529              : #define ccol__thread_sigmask(how, set, oldset) \
     530              :   pthread_sigmask((how), (set), (oldset))
     531              : 
     532              : #define ccol__thread_kill(handle, sig) pthread_kill((handle), (sig))
     533              : 
     534              : // One-time initialization: The flag type, its static initializer and
     535              : // ccol__call_once, which runs fn exactly once for every caller that races on
     536              : // flag and evaluates to 0 or an error number. The library initializes every
     537              : // lock lazily behind a once flag, so a port never needs a static lock
     538              : // initializer; CCOL__ONCE_INIT is the only static initializer this file offers,
     539              : // because a once flag holds a plain "not run yet" state.
     540              : #define ccol__once_flag pthread_once_t
     541              : 
     542              : #define CCOL__ONCE_INIT PTHREAD_ONCE_INIT
     543              : 
     544              : #define ccol__call_once(flag, fn) pthread_once(&(flag), (fn))
     545              : 
     546              : // Thread-local storage key wrappers: The type, create with a destructor that
     547              : // runs at thread exit, delete, and set and get of the calling thread's value.
     548              : // The per-thread caches of cjson, cyaml, cmempool and clogger hang off them.
     549              : // create, delete and set evaluate to 0 or an error number; get gives the value
     550              : // or NULL.
     551              : #define ccol__thread_ls_key pthread_key_t
     552              : 
     553              : #define ccol__thread_ls_key_create(key, destructor) \
     554              :   pthread_key_create(&(key), (destructor))
     555              : 
     556              : #define ccol__thread_ls_key_delete(key) pthread_key_delete((key))
     557              : 
     558              : #define ccol__thread_ls_set(key, val) pthread_setspecific((key), (val))
     559              : 
     560              : #define ccol__thread_ls_get(key) pthread_getspecific((key))
     561              : 
     562              : // Register prepare, parent and child handlers around fork(2), which the fork
     563              : // safety of the modules needs. They evaluate to what pthread_atfork() gives, 0
     564              : // or an error number. Where the close-on-exec gate exists, ccol__at_fork
     565              : // registers the gate's handlers first, once, so the gate's prepare handler runs
     566              : // after every other prepare handler of the library. Library code uses
     567              : // ccol__at_fork, never the raw form.
     568              : #define ccol__at_fork_raw(prepare, parent, child) \
     569              :   pthread_atfork((prepare), (parent), (child))
     570              : #if defined(CCOL__CLOEXEC_GATE)
     571              : #define ccol__at_fork_first() ccol__cloexec_gate_register()
     572              : #endif
     573              : #if defined(ccol__at_fork_first)
     574              : #define ccol__at_fork(prepare, parent, child) \
     575              :   (ccol__at_fork_first(), ccol__at_fork_raw(prepare, parent, child))
     576              : #else
     577              : #define ccol__at_fork(prepare, parent, child) \
     578              :   ccol__at_fork_raw(prepare, parent, child)
     579              : #endif
     580              : 
     581              : // Copies the name of thread into buf (len bytes), for clogger's thread identity
     582              : // on systems that can't read the name from /proc. Evaluates to 0 or an error
     583              : // number; OpenBSD's pthread_get_name_np() gives no result, so there it's
     584              : // always 0.
     585              : #if defined(__OpenBSD__)
     586              : #define ccol__get_thread_name_np(thread, buf, len) \
     587              :   (pthread_get_name_np((thread), (buf), (len)), 0)
     588              : #else
     589              : #define ccol__get_thread_name_np(thread, buf, len) \
     590              :   pthread_getname_np((thread), (buf), (len))
     591              : #endif
     592              : 
     593              : // Renames the calling thread to name, for the non-Linux branches of
     594              : // ccol_set_thread_name(). Evaluates to 0 or an error number. macOS takes only
     595              : // the name, FreeBSD the thread too, and OpenBSD's pthread_set_name_np() gives
     596              : // no result, so there it's always 0.
     597              : #if defined(__APPLE__)
     598              : #define ccol__set_own_thread_name_np(name) pthread_setname_np((name))
     599              : #elif defined(__OpenBSD__)
     600              : #define ccol__set_own_thread_name_np(name) \
     601              :   (pthread_set_name_np(pthread_self(), (name)), 0)
     602              : #else
     603              : #define ccol__set_own_thread_name_np(name) \
     604              :   pthread_setname_np(pthread_self(), (name))
     605              : #endif
     606              : 
     607              : // macOS only: Stores the 64-bit numeric id of thread in *out_id, for the thread
     608              : // id that clogger writes into each record. Evaluates to 0 or an error number.
     609              : #define ccol__get_thread_id_np(thread, out_id) \
     610              :   pthread_threadid_np((thread), (out_id))
     611              : 
     612              : // FreeBSD only: Evaluates to the kernel thread id of the calling thread, for
     613              : // the thread id that clogger writes into each record. The caller includes
     614              : // <pthread_np.h>.
     615              : #if defined(__FreeBSD__)
     616              : #define ccol__get_own_thread_os_id_np() pthread_getthreadid_np()
     617              : #endif
     618              : 
     619              : // Checks cond, a condition that must hold, and calls abort() after printing the
     620              : // file, line and condition when it's false. It's the library's assert: Many
     621              : // checks (double free, a foreign pointer, corruption) are part of the contract,
     622              : // so unlike assert() this always evaluates cond and never compiles away under
     623              : // NDEBUG. It's a statement with no value.
     624              : #define ccol__assert(cond)                                                   \
     625              :   do {                                                                       \
     626              :     if (!(cond)) {                                                           \
     627              :       fprintf(stderr, "%s:%d: ccol_assert failed: %s\n", __FILE__, __LINE__, \
     628              :               #cond);                                                        \
     629              :       abort();                                                               \
     630              :     }                                                                        \
     631              :   } while (0)
     632              : 
     633              : // Error handling
     634              : //
     635              : // Turn s into a string literal, as written (ccol__stringify) or after macro
     636              : // expansion (ccol__x_stringify). CCOL__ERR_STR and the version string need the
     637              : // expanded form for __LINE__ and the version numbers.
     638              : #define ccol__stringify(s) #s
     639              : 
     640              : #define ccol__x_stringify(s) ccol__stringify(s)
     641              : 
     642              : // Evaluates to the identifier prefix_n, unique in the translation unit when n
     643              : // is
     644              : // __COUNTER__. The container macros name every temporary this way: A temporary
     645              : // is in scope inside its own initializer, where the caller's argument is
     646              : // evaluated, so nested public macros (chmap_get(m, chmap_get(m, k))) would
     647              : // otherwise shadow each other under -Wshadow. The second level makes n expand
     648              : // before the paste.
     649              : #define ccol__uniq(prefix, n) ccol__uniq_paste(prefix, n)
     650              : #define ccol__uniq_paste(prefix, n) prefix##_##n
     651              : 
     652              : // Expands to one _Generic association that maps the type of C23 nullptr to v,
     653              : // with its comma, or to nothing when the compiler has no nullptr. A classifying
     654              : // _Generic adds it so that nullptr is classified like a void * NULL instead of
     655              : // falling to the default. GCC 13 and Clang 16 report a __STDC_VERSION__ below
     656              : // 202311L for -std=c2x, so the test names them.
     657              : #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201710L && \
     658              :     ((defined(__clang__) && __clang_major__ >= 16) ||          \
     659              :      (!defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 13))
     660              : #define CCOL__NULLPTR_ASSOC(v) __typeof__(nullptr) : v,
     661              : #else
     662              : #define CCOL__NULLPTR_ASSOC(v)
     663              : #endif
     664              : 
     665              : // Defined for a Clang that knows -Wunreachable-code-generic-assoc. The
     666              : // classifying macros list qualified associations on purpose, so they have a
     667              : // form that turns the warning off for such a compiler. An older Clang takes the
     668              : // plain form, since naming an unknown warning is a diagnostic of its own.
     669              : #if defined(__clang__) && defined(__has_warning)
     670              : #if __has_warning("-Wunreachable-code-generic-assoc")
     671              : #define CCOL__CLANG_GENERIC_ASSOC_WARNING 1
     672              : #endif
     673              : #endif
     674              : 
     675              : // Every err and err_str out-parameter of the library points to storage the
     676              : // library owns; never free it. Most are CCOL__ERR_STR() literals that live for
     677              : // the whole process. cjson and cyaml build their parse messages in a per-thread
     678              : // buffer, valid until the next failing call of the same kind on the same thread
     679              : // (like strerror(3)). A string the caller does own is never called err.
     680              : //
     681              : // CCOL__ERR_STR builds such a literal from the message x: "file:line - x". The
     682              : // file and line tell a caller where in the library the error came from.
     683              : #define CCOL__ERR_STR(x) (__FILE__ ":" ccol__x_stringify(__LINE__) " - " x)
     684              : 
     685              : // Prints a printf-style message (format first, then its arguments) with the
     686              : // file and line to stderr in one fprintf(), and stops the program with
     687              : // ccol__assert(false). The library and the type-inferred macros use it for
     688              : // errors nobody can recover from, such as a failed chmap_get. It's a statement
     689              : // with no value. The public macro appends an empty string that the trailing %s
     690              : // of the format prints, so the argument list after the format is never empty
     691              : // and no GNU comma extension is needed; the installed headers must build under
     692              : // -std=c11 -pedantic.
     693              : #define ccol__fatal_err(...) ccol__fatal_err_impl(__VA_ARGS__, "")
     694              : 
     695              : #define ccol__fatal_err_impl(ccol__err_fmt, ...)                               \
     696              :   do {                                                                         \
     697              :     fprintf(stderr, "%s:%d: fatal: " ccol__err_fmt "%s\n", __FILE__, __LINE__, \
     698              :             __VA_ARGS__);                                                      \
     699              :     ccol__assert(false);                                                       \
     700              :   } while (0)
     701              : 
     702              : // Memory management
     703              : //
     704              : // The default allocator: malloc, calloc, realloc and free with the same
     705              : // arguments and results. ccol__mem_* and the containers use them when they got
     706              : // no procs.
     707              : #define ccol__default_mem_alloc(size) malloc((size))
     708              : 
     709              : #define ccol__default_mem_calloc(elem_count, elem_size) \
     710              :   calloc((elem_count), (elem_size))
     711              : 
     712              : #define ccol__default_mem_realloc(ptr, new_size) realloc((ptr), (new_size))
     713              : 
     714              : #define ccol__default_mem_free(ptr) free((ptr))
     715              : 
     716              : // Allocate, zero-allocate, reallocate and free through m_procs, or through the
     717              : // default allocator when it's NULL. Every allocation of the library goes
     718              : // through them, so a container honours the procs it was created with. The
     719              : // arguments after m_procs are those of the standard function, and each
     720              : // evaluates to what that function gives. The outer parentheses matter: ?: Binds
     721              : // more loosely than a cast or +, so without them (char *)ccol__mem_alloc(mp, n)
     722              : // + off would cast m_procs and add the offset to one arm only, and it would
     723              : // compile silently.
     724              : #define ccol__mem_alloc(m_procs, size) \
     725              :   ((m_procs) ? (m_procs)->malloc((size)) : ccol__default_mem_alloc((size)))
     726              : 
     727              : #define ccol__mem_calloc(m_procs, e_count, e_size)    \
     728              :   ((m_procs) ? (m_procs)->calloc((e_count), (e_size)) \
     729              :              : ccol__default_mem_calloc((e_count), (e_size)))
     730              : 
     731              : #define ccol__mem_realloc(m_procs, ptr, new_size)    \
     732              :   ((m_procs) ? (m_procs)->realloc((ptr), (new_size)) \
     733              :              : ccol__default_mem_realloc((ptr), (new_size)))
     734              : 
     735              : #define ccol__mem_free(m_procs, ptr) \
     736              :   ((m_procs) ? (m_procs)->free((ptr)) : ccol__default_mem_free((ptr)))
     737              : 
     738              : // The invalid size_t, (size_t)-1, its largest value. Functions that give a
     739              : // size or an index give it for "not found", "none" or a failure, so compare a
     740              : // result with it before you use the result as an index.
     741              : #define ccol_invalid_size ((size_t)-1)
     742              : 
     743              : // Internal: The largest power of two a size_t can hold (2^31 or 2^63), the cap
     744              : // of the power-of-two growth of the containers.
     745              : #define ccol__max_power_of_two_size \
     746              :   ((size_t)1 << ((sizeof(size_t) * CHAR_BIT) - 1))
     747              : 
     748              : // The largest element count of a collection, the largest power of two a
     749              : // size_t holds (2^31 with a 32-bit size_t, 2^63 with a 64-bit one). A growth
     750              : // past it fails, with ccol_container_full or false as each function documents.
     751              : #define ccol_max_elem_count ccol__max_power_of_two_size
     752              : 
     753              : // Return codes
     754              : //
     755              : // The result of a collection operation: Zero is success and every error is
     756              : // negative. Each enumerator has an explicit value on purpose. Some callers test
     757              : // "== 0", and with implicit values a new enumerator in the middle would
     758              : // renumber every later one, ccol_success included. Add new codes with explicit
     759              : // values.
     760              : typedef enum ccollections_retval {
     761              :   ccol_unexpected_failure = -18,
     762              :   // HTTP client failures. tls_cert_load_failed is a local certificate, key or
     763              :   // CA file that can't be read or parsed; transfer_aborted is a send or receive
     764              :   // error or a stream callback that aborted.
     765              :   ccol_http_connection_failed = -17,
     766              :   ccol_http_host_resolution_failed = -16,
     767              :   ccol_http_tls_handshake_failed = -15,
     768              :   ccol_http_tls_cert_verification_failed = -14,
     769              :   ccol_http_tls_cert_load_failed = -13,
     770              :   ccol_http_too_many_redirects = -12,
     771              :   ccol_http_invalid_url = -11,
     772              :   ccol_http_transfer_aborted = -10,
     773              :   // msg_too_large: A message above the configured size limit.
     774              :   ccol_msg_too_large = -9,
     775              :   ccol_container_empty = -8,
     776              :   ccol_container_full = -7,
     777              :   ccol_timed_out = -6,
     778              :   ccol_not_permitted = -5,
     779              :   ccol_invalid_args = -4,
     780              :   ccol_key_not_found = -3,
     781              :   ccol_key_already_present = -2,
     782              :   ccol_not_enough_memory = -1,
     783              :   ccol_success = 0
     784              : } ccol_retval;
     785              : 
     786              : // Gives the name of r as a string literal ("unknown" for a value it doesn't
     787              : // know), handy in a log or a ccol__fatal_err() message.
     788           39 : static inline const char *ccol_retval_to_str(ccol_retval r) {
     789           39 :   switch (r) {
     790            0 :     case ccol_success:
     791            0 :       return "ccol_success";
     792            2 :     case ccol_not_enough_memory:
     793            2 :       return "ccol_not_enough_memory";
     794            1 :     case ccol_key_already_present:
     795            1 :       return "ccol_key_already_present";
     796            1 :     case ccol_key_not_found:
     797            1 :       return "ccol_key_not_found";
     798            8 :     case ccol_invalid_args:
     799            8 :       return "ccol_invalid_args";
     800            1 :     case ccol_not_permitted:
     801            1 :       return "ccol_not_permitted";
     802            4 :     case ccol_timed_out:
     803            4 :       return "ccol_timed_out";
     804            1 :     case ccol_container_full:
     805            1 :       return "ccol_container_full";
     806            1 :     case ccol_container_empty:
     807            1 :       return "ccol_container_empty";
     808            3 :     case ccol_msg_too_large:
     809            3 :       return "ccol_msg_too_large";
     810            1 :     case ccol_http_connection_failed:
     811            1 :       return "ccol_http_connection_failed";
     812            1 :     case ccol_http_host_resolution_failed:
     813            1 :       return "ccol_http_host_resolution_failed";
     814            1 :     case ccol_http_tls_handshake_failed:
     815            1 :       return "ccol_http_tls_handshake_failed";
     816            1 :     case ccol_http_tls_cert_verification_failed:
     817            1 :       return "ccol_http_tls_cert_verification_failed";
     818            1 :     case ccol_http_tls_cert_load_failed:
     819            1 :       return "ccol_http_tls_cert_load_failed";
     820            1 :     case ccol_http_too_many_redirects:
     821            1 :       return "ccol_http_too_many_redirects";
     822            1 :     case ccol_http_invalid_url:
     823            1 :       return "ccol_http_invalid_url";
     824            7 :     case ccol_http_transfer_aborted:
     825            7 :       return "ccol_http_transfer_aborted";
     826            1 :     case ccol_unexpected_failure:
     827            1 :       return "ccol_unexpected_failure";
     828            1 :     default:
     829            1 :       return "unknown";
     830              :   }
     831              : }
     832              : 
     833              : // Writes a hex dump of the size bytes at data to stderr (offset, hex columns,
     834              : // printable ASCII). The cbmap and chmap macros call it before a
     835              : // ccol__fatal_err() for a failed insert or lookup, so you can see a key that is
     836              : // binary data.
     837           12 : static inline void ccol__dump_key_to_stderr(const void *data, size_t size) {
     838           12 :   const unsigned char *p = (const unsigned char *)data;
     839           23 :   fprintf(stderr, "Key dump (%zu byte%s):\n", size, size == 1 ? "" : "s");
     840           21 :   for (size_t i = 0; i < size; i += 16) {
     841            9 :     fprintf(stderr, "  %08zx  ", i);
     842          153 :     for (size_t j = 0; j < 16; j++) {
     843          144 :       if (i + j < size)
     844           57 :         fprintf(stderr, "%02x ", p[i + j]);
     845              :       else
     846           87 :         fprintf(stderr, "   ");
     847          144 :       if (j == 7) fprintf(stderr, " ");
     848              :     }
     849            9 :     fprintf(stderr, " |");
     850           66 :     for (size_t j = 0; j < 16 && i + j < size; j++)
     851           57 :       fprintf(stderr, "%c", isprint(p[i + j]) ? (char)p[i + j] : '.');
     852            9 :     fprintf(stderr, "|\n");
     853              :   }
     854           12 : }
     855              : 
     856              : // Attaches the cleanup function destructor to a variable declaration; it runs
     857              : // with a pointer to the variable when the variable goes out of scope. The
     858              : // _scoped forms of the containers and ccol_scoped_ptr use it to destroy a
     859              : // handle on every way out of a scope.
     860              : #define ccol__destructor(destructor) __attribute__((cleanup(destructor)))
     861              : 
     862              : // Custom memory management types
     863              : 
     864              : // The malloc of a custom allocator. It must behave like malloc(3): Give a
     865              : // block of size bytes aligned for any object type (_Alignof(max_align_t)), or
     866              : // NULL when it can't.
     867              : typedef void *(*ccol_malloc)(size_t size);
     868              : 
     869              : // The free of a custom allocator. It must behave like free(3): Release a
     870              : // block that the same allocator gave, and do nothing for NULL.
     871              : typedef void (*ccol_free)(void *ptr);
     872              : 
     873              : // The calloc of a custom allocator. It must behave like calloc(3): Give a
     874              : // zeroed block of elem_count * elem_size bytes aligned for any object type,
     875              : // or NULL when it can't or the product overflows.
     876              : typedef void *(*ccol_calloc)(size_t elem_count, size_t elem_size);
     877              : 
     878              : // The realloc of a custom allocator. It must behave like realloc(3): Resize
     879              : // the block of ptr to size bytes, aligned for any object type, and give its
     880              : // new address, or give NULL and leave the old block as it was when it can't.
     881              : // A NULL ptr must work as a malloc of size bytes.
     882              : typedef void *(*ccol_realloc)(void *ptr, size_t size);
     883              : 
     884              : // A custom allocator. Give it to a collection's _mp or _full constructor. All
     885              : // four functions must be non-NULL and behave like the standard ones, including
     886              : // alignment: Every block must be aligned for any object type
     887              : // (_Alignof(max_align_t)), since containers put such entries at the start of a
     888              : // block.
     889              : typedef struct ccol_memmgmt_procs {
     890              :   ccol_malloc malloc;
     891              :   ccol_free free;
     892              :   ccol_calloc calloc;
     893              :   ccol_realloc realloc;
     894              : } ccol_memmgmt_procs;
     895              : 
     896              : // Comparison and hashing types
     897              : //
     898              : // A comparison for sorts and ordered maps: Negative when first < second, zero
     899              : // when equal, positive when first > second.
     900              : typedef int (*ccol_comparison_proc)(const void *first, const void *second);
     901              : 
     902              : // A hash for hash maps; a good one spreads the values evenly. size is the map's
     903              : // key size for a fixed-size key type, or the byte length the caller gives for a
     904              : // string or other variable-length key, so the function always hashes exactly
     905              : // ptr[0..size).
     906              : typedef unsigned long (*ccol_hashing_proc)(const void *ptr, size_t size);
     907              : 
     908              : // A key equality for hash maps, used with a ccol_hashing_proc. It gives true
     909              : // when the two keys are the same key, and two keys it calls equal must hash the
     910              : // same, or a lookup misses a key that is present. The pointers carry no
     911              : // alignment for the key type, so read fields through memcpy.
     912              : typedef bool (*ccol_key_equality_proc)(const void *first, size_t first_size,
     913              :                                        const void *second, size_t second_size);
     914              : 
     915              : // Map key-value types
     916              : //
     917              : // A pointer and a size that carry a key or a value of any type to a map, which
     918              : // copies the bytes. For a string, size counts the NUL.
     919              : typedef struct cmap_pair {
     920              :   void *ptr;
     921              :   size_t size;
     922              : } cmap_pair;
     923              : 
     924              : // The iterator of every container. The pointers are valid until the container
     925              : // changes, and you must destroy the iterator unless the walk reached its end.
     926              : typedef struct cmap_iterator {
     927              :   // Both point at the container's own accessor of the current entry. You can
     928              :   // write the bytes they address, but not the pairs: A stored pointer the
     929              :   // container never allocated would be freed by cbstmap's teardown.
     930              :   const cmap_pair *key_pair;
     931              :   const cmap_pair *val_pair;
     932              :   // Internal: Advance and destroy functions of the container.
     933              :   struct cmap_iterator *(*ccol__next_fn)(struct cmap_iterator *);
     934              :   void (*ccol__free_fn)(struct cmap_iterator *);
     935              :   // true when val_pair->ptr is the element itself (cvector); false when the
     936              :   // map's inline-storage rules apply.
     937              :   bool ccol__direct_ptr;
     938              : } cmap_iterator;
     939              : 
     940              : // Memory management utilities
     941              : //
     942              : // Checks a caller's allocator before a container stores it, so a missing
     943              : // function fails the create instead of crashing later. Evaluates to true when
     944              : // mmgt_procs is NULL or all four functions are set, and to false otherwise,
     945              : // with *err set to a library-owned string when err isn't NULL.
     946              : #define ccol__verify_memmgmt_procs(mmgt_procs, err)                        \
     947              :   ({                                                                       \
     948              :     bool ccol__vmp_ok = true;                                              \
     949              :     if ((mmgt_procs) && (!(mmgt_procs)->malloc || !(mmgt_procs)->calloc || \
     950              :                          !(mmgt_procs)->realloc || !(mmgt_procs)->free)) { \
     951              :       if ((err)) {                                                         \
     952              :         *(err) = CCOL__ERR_STR(                                            \
     953              :             "Detected at least one NULL memory management function");      \
     954              :       }                                                                    \
     955              :       ccol__vmp_ok = false;                                                \
     956              :     }                                                                      \
     957              :     ccol__vmp_ok;                                                          \
     958              :   })
     959              : 
     960              : // Copies mmgmt_procs into a block allocated with it and stores that in
     961              : // container->m_procs, so the container doesn't depend on the caller's struct
     962              : // staying alive. A NULL mmgmt_procs stores NULL (the default allocator).
     963              : // Evaluates to true, or to false with *err set when the allocation fails.
     964              : #define ccol__populate_mem_mgmt_procs(container, mmgmt_procs, err) \
     965              :   ({                                                               \
     966              :     bool ccol__pmp_ok = true;                                      \
     967              :     if ((mmgmt_procs)) {                                           \
     968              :       (container)->m_procs =                                       \
     969              :           (mmgmt_procs)->malloc(sizeof(ccol_memmgmt_procs));       \
     970              :       if (!(container)->m_procs) {                                 \
     971              :         if ((err)) {                                               \
     972              :           *(err) = CCOL__ERR_STR(                                  \
     973              :               "Failed to allocate buffer for memory mgmt buffer"); \
     974              :         }                                                          \
     975              :         ccol__pmp_ok = false;                                      \
     976              :       } else {                                                     \
     977              :         memcpy((container)->m_procs, (mmgmt_procs),                \
     978              :                sizeof(ccol_memmgmt_procs));                        \
     979              :       }                                                            \
     980              :     } else {                                                       \
     981              :       (container)->m_procs = NULL;                                 \
     982              :     }                                                              \
     983              :     ccol__pmp_ok;                                                  \
     984              :   })
     985              : 
     986              : // Internal: What the cleanup of ccol_scoped_ptr needs at the end of the scope,
     987              : // the address of the guarded pointer and the allocator that frees it. The
     988              : // macros fill it in.
     989              : typedef struct ccol__scoped_ptr_ctx {
     990              :   void **ptr_addr;
     991              :   ccol_memmgmt_procs *m_procs;
     992              : } ccol__scoped_ptr_ctx;
     993              : 
     994              : // Frees the current value of the pointer that ctx guards, if any, with ctx's
     995              : // allocator, and sets it to NULL. ccol_scoped_ptr_mp attaches it as the cleanup
     996              : // that runs at the end of the scope.
     997           12 : static inline void ccol__scoped_ptr_cleanup(ccol__scoped_ptr_ctx *ctx) {
     998           12 :   if (ctx->ptr_addr && *ctx->ptr_addr) {
     999            9 :     ccol__mem_free(ctx->m_procs, *ctx->ptr_addr);
    1000            9 :     *ctx->ptr_addr = NULL;
    1001              :   }
    1002           12 : }
    1003              : 
    1004              : // Declares type *name = NULL and frees whatever name holds at the end of the
    1005              : // enclosing scope, with mmgmt_procs->free or with free() when mmgmt_procs is
    1006              : // NULL. It saves the free on every return path of a function that owns a
    1007              : // buffer. mmgmt_procs is kept by reference, so it must outlive the scope. Only
    1008              : // the last value is freed, so free an earlier value yourself before you assign
    1009              : // a new one. Hand the pointer out of the scope with ccol_scoped_ptr_release().
    1010              : // It's two declarations, so use it as a statement of its own.
    1011              : #define ccol_scoped_ptr_mp(name, type, mmgmt_procs)                    \
    1012              :   type *name = NULL;                                                   \
    1013              :   ccol__scoped_ptr_ctx name##__ccol_scoped_ctx __attribute__((unused)) \
    1014              :   ccol__destructor(ccol__scoped_ptr_cleanup) = {(void **)&(name),      \
    1015              :                                                 (mmgmt_procs)}
    1016              : 
    1017              : // Declares type *name = NULL and frees whatever name holds with free() at the
    1018              : // end of the enclosing scope, on every way out, for the common case of a
    1019              : // malloc'ed buffer. Only the last value is freed, so free an earlier value
    1020              : // yourself before you assign a new one. Hand the pointer out of the scope with
    1021              : // ccol_scoped_ptr_release(). It's two declarations, so use it as a statement
    1022              : // of its own.
    1023              : #define ccol_scoped_ptr(name, type) ccol_scoped_ptr_mp(name, type, NULL)
    1024              : 
    1025              : // Evaluates to the current value of name, a ccol_scoped_ptr variable, and sets
    1026              : // name to NULL, so the scoped cleanup does nothing. Use it to hand the pointer
    1027              : // to code outside the scope, as a return value for example.
    1028              : #define ccol_scoped_ptr_release(name)             \
    1029              :   ({                                              \
    1030              :     __typeof__(name) ccol__released_ptr = (name); \
    1031              :     (name) = NULL;                                \
    1032              :     ccol__released_ptr;                           \
    1033              :   })
    1034              : 
    1035              : // Type introspection
    1036              : //
    1037              : // Evaluates to true when x has a standard integer or floating-point type, const
    1038              : // or not, and to false otherwise. chmap uses it to choose open addressing for
    1039              : // numeric keys and values. Only the type of x is read. The Clang form turns
    1040              : // -Wunreachable-code-generic-assoc off around the _Generic.
    1041              : #if defined(CCOL__CLANG_GENERIC_ASSOC_WARNING)
    1042              : #define ccol__is_integral_type(x)                                           \
    1043              :   ({                                                                        \
    1044              :     _Pragma("GCC diagnostic push");                                         \
    1045              :     _Pragma("GCC diagnostic ignored \"-Wunreachable-code-generic-assoc\""); \
    1046              :     bool ccol__iit_result = _Generic((x),                                   \
    1047              :         char: true,                                                         \
    1048              :         signed char: true,                                                  \
    1049              :         short: true,                                                        \
    1050              :         int: true,                                                          \
    1051              :         long: true,                                                         \
    1052              :         long long: true,                                                    \
    1053              :         unsigned char: true,                                                \
    1054              :         unsigned short: true,                                               \
    1055              :         unsigned int: true,                                                 \
    1056              :         unsigned long: true,                                                \
    1057              :         unsigned long long: true,                                           \
    1058              :         float: true,                                                        \
    1059              :         double: true,                                                       \
    1060              :         long double: true,                                                  \
    1061              :         const char: true,                                                   \
    1062              :         const signed char: true,                                            \
    1063              :         const short: true,                                                  \
    1064              :         const int: true,                                                    \
    1065              :         const long: true,                                                   \
    1066              :         const long long: true,                                              \
    1067              :         const unsigned char: true,                                          \
    1068              :         const unsigned short: true,                                         \
    1069              :         const unsigned int: true,                                           \
    1070              :         const unsigned long: true,                                          \
    1071              :         const unsigned long long: true,                                     \
    1072              :         const float: true,                                                  \
    1073              :         const double: true,                                                 \
    1074              :         const long double: true,                                            \
    1075              :         default: false);                                                    \
    1076              :     _Pragma("GCC diagnostic pop");                                          \
    1077              :     ccol__iit_result;                                                       \
    1078              :   })
    1079              : #else
    1080              : #define ccol__is_integral_type(x)     \
    1081              :   _Generic((x),                       \
    1082              :       char: true,                     \
    1083              :       signed char: true,              \
    1084              :       short: true,                    \
    1085              :       int: true,                      \
    1086              :       long: true,                     \
    1087              :       long long: true,                \
    1088              :       unsigned char: true,            \
    1089              :       unsigned short: true,           \
    1090              :       unsigned int: true,             \
    1091              :       unsigned long: true,            \
    1092              :       unsigned long long: true,       \
    1093              :       float: true,                    \
    1094              :       double: true,                   \
    1095              :       long double: true,              \
    1096              :       const char: true,               \
    1097              :       const signed char: true,        \
    1098              :       const short: true,              \
    1099              :       const int: true,                \
    1100              :       const long: true,               \
    1101              :       const long long: true,          \
    1102              :       const unsigned char: true,      \
    1103              :       const unsigned short: true,     \
    1104              :       const unsigned int: true,       \
    1105              :       const unsigned long: true,      \
    1106              :       const unsigned long long: true, \
    1107              :       const float: true,              \
    1108              :       const double: true,             \
    1109              :       const long double: true,        \
    1110              :       default: false)
    1111              : #endif
    1112              : 
    1113              : // Evaluates to true when x points to a type that ccol__is_integral_type()
    1114              : // accepts, and to false otherwise, for code that classifies a key through a
    1115              : // pointer to it. Only the type of x is read.
    1116              : #if defined(CCOL__CLANG_GENERIC_ASSOC_WARNING)
    1117              : #define ccol__is_integral_ptr(x)                                            \
    1118              :   ({                                                                        \
    1119              :     _Pragma("GCC diagnostic push");                                         \
    1120              :     _Pragma("GCC diagnostic ignored \"-Wunreachable-code-generic-assoc\""); \
    1121              :     bool ccol__iip_result = _Generic((x),                                   \
    1122              :         char *: true,                                                       \
    1123              :         signed char *: true,                                                \
    1124              :         short *: true,                                                      \
    1125              :         int *: true,                                                        \
    1126              :         long *: true,                                                       \
    1127              :         long long *: true,                                                  \
    1128              :         unsigned char *: true,                                              \
    1129              :         unsigned short *: true,                                             \
    1130              :         unsigned int *: true,                                               \
    1131              :         unsigned long *: true,                                              \
    1132              :         unsigned long long *: true,                                         \
    1133              :         float *: true,                                                      \
    1134              :         double *: true,                                                     \
    1135              :         long double *: true,                                                \
    1136              :         const char *: true,                                                 \
    1137              :         const signed char *: true,                                          \
    1138              :         const short *: true,                                                \
    1139              :         const int *: true,                                                  \
    1140              :         const long *: true,                                                 \
    1141              :         const long long *: true,                                            \
    1142              :         const unsigned char *: true,                                        \
    1143              :         const unsigned short *: true,                                       \
    1144              :         const unsigned int *: true,                                         \
    1145              :         const unsigned long *: true,                                        \
    1146              :         const unsigned long long *: true,                                   \
    1147              :         const float *: true,                                                \
    1148              :         const double *: true,                                               \
    1149              :         const long double *: true,                                          \
    1150              :         default: false);                                                    \
    1151              :     ccol__iip_result;                                                       \
    1152              :     _Pragma("GCC diagnostic pop");                                          \
    1153              :   })
    1154              : #else
    1155              : #define ccol__is_integral_ptr(x)        \
    1156              :   _Generic((x),                         \
    1157              :       char *: true,                     \
    1158              :       signed char *: true,              \
    1159              :       short *: true,                    \
    1160              :       int *: true,                      \
    1161              :       long *: true,                     \
    1162              :       long long *: true,                \
    1163              :       unsigned char *: true,            \
    1164              :       unsigned short *: true,           \
    1165              :       unsigned int *: true,             \
    1166              :       unsigned long *: true,            \
    1167              :       unsigned long long *: true,       \
    1168              :       float *: true,                    \
    1169              :       double *: true,                   \
    1170              :       long double *: true,              \
    1171              :       const char *: true,               \
    1172              :       const signed char *: true,        \
    1173              :       const short *: true,              \
    1174              :       const int *: true,                \
    1175              :       const long *: true,               \
    1176              :       const long long *: true,          \
    1177              :       const unsigned char *: true,      \
    1178              :       const unsigned short *: true,     \
    1179              :       const unsigned int *: true,       \
    1180              :       const unsigned long *: true,      \
    1181              :       const unsigned long long *: true, \
    1182              :       const float *: true,              \
    1183              :       const double *: true,             \
    1184              :       const long double *: true,        \
    1185              :       default: false)
    1186              : #endif
    1187              : 
    1188              : // Evaluates to true when ccol__ptr points to a signed integer type (char
    1189              : // counts), const or not. cbstmap uses it to pick a signed or unsigned key
    1190              : // comparison. Only the type is read.
    1191              : #define ccol__is_signed_int_ptr(ccol__ptr) \
    1192              :   _Generic((ccol__ptr),                    \
    1193              :       char *: true,                        \
    1194              :       signed char *: true,                 \
    1195              :       short *: true,                       \
    1196              :       int *: true,                         \
    1197              :       long *: true,                        \
    1198              :       long long *: true,                   \
    1199              :       const char *: true,                  \
    1200              :       const signed char *: true,           \
    1201              :       const short *: true,                 \
    1202              :       const int *: true,                   \
    1203              :       const long *: true,                  \
    1204              :       const long long *: true,             \
    1205              :       default: false)
    1206              : 
    1207              : // Evaluates to 1 when data has an array-of-character type and 0 when it's a
    1208              : // character pointer; only those two reach it, through ccol__is_char_array. It
    1209              : // lets a string key be stored the right way. A pointer has the same type as its
    1210              : // ccol__char_ptr_flavour() while an array doesn't, and
    1211              : // __builtin_types_compatible_p() ignores top-level qualifiers, so a
    1212              : // `const char *const` counts as a pointer. It's a constant expression that
    1213              : // never evaluates data.
    1214              : #define ccol__type_is_array_of_char(data)          \
    1215              :   (!__builtin_types_compatible_p(__typeof__(data), \
    1216              :                                  __typeof__(ccol__char_ptr_flavour(data))))
    1217              : 
    1218              : // ccol__is_char_ptr evaluates to true when data is a pointer to a character
    1219              : // type (signed and unsigned char too), or an array of one, which _Generic
    1220              : // decays. ccol__is_char_array then tells an array from a pointer; a pointer
    1221              : // that is itself qualified is a pointer. The containers use both to treat every
    1222              : // character pointer as a NUL-terminated string. Only the type of data is
    1223              : // read.
    1224              : #if defined(CCOL__CLANG_GENERIC_ASSOC_WARNING)
    1225              : #define ccol__is_char_ptr(data)                                             \
    1226              :   ({                                                                        \
    1227              :     _Pragma("GCC diagnostic push");                                         \
    1228              :     _Pragma("GCC diagnostic ignored \"-Wunreachable-code-generic-assoc\""); \
    1229              :     bool ccol__icp_result = _Generic((data),                                \
    1230              :         char *: true,                                                       \
    1231              :         const char *: true,                                                 \
    1232              :         signed char *: true,                                                \
    1233              :         const signed char *: true,                                          \
    1234              :         unsigned char *: true,                                              \
    1235              :         const unsigned char *: true,                                        \
    1236              :         default: false);                                                    \
    1237              :     _Pragma("GCC diagnostic pop");                                          \
    1238              :     ccol__icp_result;                                                       \
    1239              :   })
    1240              : 
    1241              : #define ccol__is_char_array(data) \
    1242              :   (ccol__is_char_ptr((data)) && ccol__type_is_array_of_char(data))
    1243              : #else
    1244              : #define ccol__is_char_ptr(data)    \
    1245              :   _Generic((data),                 \
    1246              :       char *: true,                \
    1247              :       const char *: true,          \
    1248              :       signed char *: true,         \
    1249              :       const signed char *: true,   \
    1250              :       unsigned char *: true,       \
    1251              :       const unsigned char *: true, \
    1252              :       default: false)
    1253              : 
    1254              : #define ccol__is_char_array(data) \
    1255              :   (ccol__is_char_ptr((data)) && ccol__type_is_array_of_char(data))
    1256              : #endif
    1257              : 
    1258              : // The key and value types the containers tell apart. Every enumerator has an
    1259              : // explicit value for the same reason as in ccol_retval; add a new one at the
    1260              : // end with the next number. ccol_signed_char exists because the platform
    1261              : // decides whether plain char is signed; a signed char * is still a ccol_string.
    1262              : typedef enum ccollections_data_type {
    1263              :   ccol_char = 0,
    1264              :   ccol_short = 1,
    1265              :   ccol_int = 2,
    1266              :   ccol_long = 3,
    1267              :   ccol_long_long = 4,
    1268              :   ccol_unsigned_char = 5,
    1269              :   ccol_unsigned_short = 6,
    1270              :   ccol_unsigned_int = 7,
    1271              :   ccol_unsigned_long = 8,
    1272              :   ccol_unsigned_long_long = 9,
    1273              :   ccol_float = 10,
    1274              :   ccol_double = 11,
    1275              :   ccol_long_double = 12,
    1276              :   ccol_pointer = 13,
    1277              :   ccol_string = 14,
    1278              :   ccol_other_types = 15,
    1279              :   ccol_signed_char = 16,
    1280              : } ccol_data_type;
    1281              : 
    1282              : // Gives sizeof() of the C type that type names, or 0 for ccol_string,
    1283              : // ccol_other_types and unknown values, which have no single width. The map
    1284              : // modules use it to refuse, with ccol_invalid_args, a hand-built cmap_pair
    1285              : // whose size doesn't match the declared key type, and you can use it to size
    1286              : // such a pair.
    1287     39887948 : static inline size_t ccol_fixed_width_data_type_size(ccol_data_type type) {
    1288     39887948 :   switch (type) {
    1289              :     case ccol_char:
    1290              :     case ccol_signed_char:
    1291              :     case ccol_unsigned_char:
    1292              :       return sizeof(char);
    1293              :     case ccol_short:
    1294              :     case ccol_unsigned_short:
    1295              :       return sizeof(short);
    1296              :     case ccol_int:
    1297              :     case ccol_unsigned_int:
    1298              :       return sizeof(int);
    1299              :     case ccol_long:
    1300              :     case ccol_unsigned_long:
    1301              :       return sizeof(long);
    1302              :     case ccol_long_long:
    1303              :     case ccol_unsigned_long_long:
    1304              :       return sizeof(long long);
    1305              :     case ccol_float:
    1306              :       return sizeof(float);
    1307              :     case ccol_double:
    1308              :       return sizeof(double);
    1309              :     case ccol_long_double:
    1310              :       return sizeof(long double);
    1311              :     case ccol_pointer:
    1312              :       return sizeof(uintptr_t);
    1313              :     case ccol_string:
    1314              :     case ccol_other_types:
    1315              :     default:
    1316              :       return 0;
    1317              :   }
    1318              : }
    1319              : 
    1320              : // Internal: Evaluates to the ccol_data_type of a scalar var, or to
    1321              : // ccol_other_types for anything else. ccol_determine_ccol_data_type uses it
    1322              : // after it has ruled out strings and pointers. Only the type of var is read.
    1323              : #if defined(CCOL__CLANG_GENERIC_ASSOC_WARNING)
    1324              : #define ccol__determine_non_special_data_type(var)                          \
    1325              :   ({                                                                        \
    1326              :     _Pragma("GCC diagnostic push");                                         \
    1327              :     _Pragma("GCC diagnostic ignored \"-Wunreachable-code-generic-assoc\""); \
    1328              :     ccol_data_type ccol__dnsdt_result = _Generic((var),                     \
    1329              :         char: ccol_char,                                                    \
    1330              :         signed char: ccol_signed_char,                                      \
    1331              :         short: ccol_short,                                                  \
    1332              :         int: ccol_int,                                                      \
    1333              :         long: ccol_long,                                                    \
    1334              :         long long: ccol_long_long,                                          \
    1335              :         unsigned char: ccol_unsigned_char,                                  \
    1336              :         unsigned short: ccol_unsigned_short,                                \
    1337              :         unsigned int: ccol_unsigned_int,                                    \
    1338              :         unsigned long: ccol_unsigned_long,                                  \
    1339              :         unsigned long long: ccol_unsigned_long_long,                        \
    1340              :         float: ccol_float,                                                  \
    1341              :         double: ccol_double,                                                \
    1342              :         long double: ccol_long_double,                                      \
    1343              :         const char: ccol_char,                                              \
    1344              :         const signed char: ccol_signed_char,                                \
    1345              :         const short: ccol_short,                                            \
    1346              :         const int: ccol_int,                                                \
    1347              :         const long: ccol_long,                                              \
    1348              :         const long long: ccol_long_long,                                    \
    1349              :         const unsigned char: ccol_unsigned_char,                            \
    1350              :         const unsigned short: ccol_unsigned_short,                          \
    1351              :         const unsigned int: ccol_unsigned_int,                              \
    1352              :         const unsigned long: ccol_unsigned_long,                            \
    1353              :         const unsigned long long: ccol_unsigned_long_long,                  \
    1354              :         const float: ccol_float,                                            \
    1355              :         const double: ccol_double,                                          \
    1356              :         const long double: ccol_long_double,                                \
    1357              :         default: ccol_other_types);                                         \
    1358              :     _Pragma("GCC diagnostic pop");                                          \
    1359              :     ccol__dnsdt_result;                                                     \
    1360              :   })
    1361              : #else
    1362              : #define ccol__determine_non_special_data_type(var)       \
    1363              :   _Generic((var),                                        \
    1364              :       char: ccol_char,                                   \
    1365              :       signed char: ccol_signed_char,                     \
    1366              :       short: ccol_short,                                 \
    1367              :       int: ccol_int,                                     \
    1368              :       long: ccol_long,                                   \
    1369              :       long long: ccol_long_long,                         \
    1370              :       unsigned char: ccol_unsigned_char,                 \
    1371              :       unsigned short: ccol_unsigned_short,               \
    1372              :       unsigned int: ccol_unsigned_int,                   \
    1373              :       unsigned long: ccol_unsigned_long,                 \
    1374              :       unsigned long long: ccol_unsigned_long_long,       \
    1375              :       float: ccol_float,                                 \
    1376              :       double: ccol_double,                               \
    1377              :       long double: ccol_long_double,                     \
    1378              :       const char: ccol_char,                             \
    1379              :       const signed char: ccol_signed_char,               \
    1380              :       const short: ccol_short,                           \
    1381              :       const int: ccol_int,                               \
    1382              :       const long: ccol_long,                             \
    1383              :       const long long: ccol_long_long,                   \
    1384              :       const unsigned char: ccol_unsigned_char,           \
    1385              :       const unsigned short: ccol_unsigned_short,         \
    1386              :       const unsigned int: ccol_unsigned_int,             \
    1387              :       const unsigned long: ccol_unsigned_long,           \
    1388              :       const unsigned long long: ccol_unsigned_long_long, \
    1389              :       const float: ccol_float,                           \
    1390              :       const double: ccol_double,                         \
    1391              :       const long double: ccol_long_double,               \
    1392              :       default: ccol_other_types)
    1393              : #endif
    1394              : 
    1395              : // Evaluates to the ccol_data_type of the type of data: ccol_string for a
    1396              : // character array or pointer (signed and unsigned char too), ccol_pointer for
    1397              : // any other pointer, the matching scalar value for a standard integer or
    1398              : // floating type, and ccol_other_types for anything else, such as a struct.
    1399              : // chmap and cbmap choose how to store and compare keys from it. Only the type
    1400              : // of data counts; data is never evaluated.
    1401              : #define ccol_determine_ccol_data_type(data)                                 \
    1402              :   ({                                                                        \
    1403              :     ccol_data_type ccol__dcdt_r = ccol_other_types;                         \
    1404              :     if (ccol__is_char_array((data))) {                                      \
    1405              :       ccol__dcdt_r = ccol_string;                                           \
    1406              :     } else if (ccol__is_char_ptr((data))) {                                 \
    1407              :       ccol__dcdt_r = ccol_string;                                           \
    1408              :     } else {                                                                \
    1409              :       __typeof__(data) ccol__dcdt_type_probe __attribute__((unused)) = {0}; \
    1410              :       if (__builtin_classify_type(ccol__dcdt_type_probe) == 5 &&            \
    1411              :           sizeof(ccol__dcdt_type_probe) == sizeof(uintptr_t)) {             \
    1412              :         ccol__dcdt_r = ccol_pointer;                                        \
    1413              :       } else {                                                              \
    1414              :         ccol__dcdt_r =                                                      \
    1415              :             ccol__determine_non_special_data_type(ccol__dcdt_type_probe);   \
    1416              :       }                                                                     \
    1417              :     }                                                                       \
    1418              :     ccol__dcdt_r;                                                           \
    1419              :   })
    1420              : 
    1421              : // Internal: Evaluates to a constant 1 when lvalue has a character-pointer type,
    1422              : // else 0, so __builtin_choose_expr() can select on it where the statement
    1423              : // expression of ccol__is_char_ptr() can't be used. Its list must match
    1424              : // ccol__is_char_ptr(). lvalue is never evaluated.
    1425              : #define ccol__type_is_char_ptr(lvalue)                                      \
    1426              :   (__builtin_types_compatible_p(__typeof__(lvalue), char *) ||              \
    1427              :    __builtin_types_compatible_p(__typeof__(lvalue), const char *) ||        \
    1428              :    __builtin_types_compatible_p(__typeof__(lvalue), signed char *) ||       \
    1429              :    __builtin_types_compatible_p(__typeof__(lvalue), const signed char *) || \
    1430              :    __builtin_types_compatible_p(__typeof__(lvalue), unsigned char *) ||     \
    1431              :    __builtin_types_compatible_p(__typeof__(lvalue), const unsigned char *))
    1432              : 
    1433              : // Internal: Evaluates to a null pointer with the character-pointer type that
    1434              : // expr decays to (char * for anything else). ccol__declared_or_own_type and
    1435              : // ccol__type_is_array_of_char use only its type. Every arm is a cast this
    1436              : // header writes, so it's well formed for any expr in the unchosen arm of a
    1437              : // __builtin_choose_expr().
    1438              : #define ccol__char_ptr_flavour(expr)                   \
    1439              :   _Generic((expr),                                     \
    1440              :       char *: (char *)0,                               \
    1441              :       const char *: (const char *)0,                   \
    1442              :       signed char *: (signed char *)0,                 \
    1443              :       const signed char *: (const signed char *)0,     \
    1444              :       unsigned char *: (unsigned char *)0,             \
    1445              :       const unsigned char *: (const unsigned char *)0, \
    1446              :       default: (char *)0)
    1447              : 
    1448              : // Internal: Expands to the type a container macro gives its private copy of a
    1449              : // caller expression expr, so the copy has the right type and width.
    1450              : // type_var is the companion type variable, so *(type_var) has the declared
    1451              : // type. For a declared non-string type it's that type, so the copy converts
    1452              : // expr by the usual rules and a mismatched type fails to compile. For a
    1453              : // declared character-pointer type it's expr's own pointer flavour, because all
    1454              : // character pointers are one string type to the library and a map keyed on
    1455              : // unsigned char * must stay reachable through a char *. Arrays decay, and
    1456              : // top-level qualifiers go, so ccol__clear_padding() can write the copy. expr is
    1457              : // never evaluated.
    1458              : #define ccol__declared_or_own_type(type_var, expr)                             \
    1459              :   ccol__unqual_type(__builtin_choose_expr(ccol__type_is_char_ptr(*(type_var)), \
    1460              :                                           ccol__char_ptr_flavour(expr),        \
    1461              :                                           *(type_var)))
    1462              : 
    1463              : // Internal: Evaluates to a constant 1 when T (a type or an expression) is an
    1464              : // array type, else 0. ccol__refuse_array_types and ccol__unqual_type need it.
    1465              : // The comma decays an array and keeps any other type, so the two types differ
    1466              : // exactly for an array (a function type also gives 1). Nothing is evaluated.
    1467              : #define ccol__type_is_array(T)                  \
    1468              :   (!__builtin_types_compatible_p(__typeof__(T), \
    1469              :                                  __typeof__((void)0, *(__typeof__(T) *)0)))
    1470              : 
    1471              : // Internal: Refuses an array key type KeyT or value type ValT at compile time,
    1472              : // with a message that starts with the container name. The typed macros copy
    1473              : // through a temporary of the declared type, and an array would decay and store
    1474              : // the address of the caller's array. It's two static assertions, valid inside a
    1475              : // struct too, and the caller adds the semicolon.
    1476              : #define ccol__refuse_array_types(container, KeyT, ValT)              \
    1477              :   _Static_assert(!ccol__type_is_array(KeyT), container               \
    1478              :                  ": an array key type is not supported; wrap the "   \
    1479              :                  "array in a struct");                               \
    1480              :   _Static_assert(!ccol__type_is_array(ValT), container               \
    1481              :                  ": an array value type is not supported; wrap the " \
    1482              :                  "array in a struct")
    1483              : 
    1484              : // Internal: Evaluates to x (not an array) as an rvalue without top-level
    1485              : // qualifiers, for ccol__unqual_type; only its type is used. Clang drops them
    1486              : // with a comma, GCC before 11 doesn't, so GCC casts x to its own type (a GNU
    1487              : // extension for a struct, which Clang refuses).
    1488              : #if defined(__clang__)
    1489              : #define ccol__unqual_nonarray_rvalue(x) ((void)0, (x))
    1490              : #else
    1491              : #define ccol__unqual_nonarray_rvalue(x) (__extension__(__typeof__(x))(x))
    1492              : #endif
    1493              : 
    1494              : // Internal: Expands to the type of x without top-level qualifiers, for a
    1495              : // temporary that a macro writes to even when the declared type is const. An
    1496              : // array type keeps its type, since dropping qualifiers would decay it. The
    1497              : // unchosen arm sees 0 instead of x, so no cast meets an array. x is never
    1498              : // evaluated.
    1499              : #define ccol__unqual_type(x)        \
    1500              :   __typeof__(__builtin_choose_expr( \
    1501              :       ccol__type_is_array(x), (x),  \
    1502              :       ccol__unqual_nonarray_rvalue( \
    1503              :           __builtin_choose_expr(ccol__type_is_array(x), 0, (x)))))
    1504              : 
    1505              : // Internal: Zeroes the padding bytes of the object obj_ptr points to, where the
    1506              : // compiler has __builtin_clear_padding(), and does nothing elsewhere. A struct
    1507              : // copy may carry stack garbage in its padding, and the containers hash and
    1508              : // compare every byte of a key, so the typed macros clear their own copy of each
    1509              : // key. It's an expression with no useful value.
    1510              : #if defined(__has_builtin)
    1511              : #if __has_builtin(__builtin_clear_padding)
    1512              : #define ccol__clear_padding(obj_ptr) __builtin_clear_padding(obj_ptr)
    1513              : #endif
    1514              : #endif
    1515              : #ifndef ccol__clear_padding
    1516              : #define ccol__clear_padding(obj_ptr) ((void)0)
    1517              : #endif
    1518              : 
    1519              : // Map pair population
    1520              : //
    1521              : // Internal: Fills *pair from data of any type, so the typed macros can hand any
    1522              : // key or value to the raw cmap_pair layer. A character array gives its address
    1523              : // and strlen + 1. A character pointer gives the pointer and strlen + 1, or
    1524              : // {NULL, 0} for a NULL pointer, which the raw layers refuse; the pointer is
    1525              : // read through __builtin_choose_expr() so no other type is ever read as a
    1526              : // pointer, and through uintptr_t so the const goes without a -Wcast-qual. Any
    1527              : // other type gives &data and sizeof(data); the cast to void * lets a const key
    1528              : // through, and the raw layers only read it. It's a statement with no value.
    1529              : #define ccol__populate_cmap_pair(pair, data)                         \
    1530              :   do {                                                               \
    1531              :     if (ccol__is_char_array((data))) {                               \
    1532              :       (pair)->ptr = (char *)&(data);                                 \
    1533              :       (pair)->size = strlen((char *)(pair)->ptr) + 1;                \
    1534              :     } else if (ccol__is_char_ptr((data))) {                          \
    1535              :       (pair)->ptr = (void *)(uintptr_t)__builtin_choose_expr(        \
    1536              :           ccol__type_is_char_ptr(data), (data), (const char *)0);    \
    1537              :       (pair)->size =                                                 \
    1538              :           (pair)->ptr ? strlen((char *)(pair)->ptr) + 1 : (size_t)0; \
    1539              :     } else {                                                         \
    1540              :       (pair)->ptr = (void *)&(data);                                 \
    1541              :       (pair)->size = sizeof((data));                                 \
    1542              :     }                                                                \
    1543              :   } while (0)
    1544              : 
    1545              : // Utility macros
    1546              : //
    1547              : // Internal: Evaluate to the smaller or larger of a and b, for the size
    1548              : // arithmetic of the library and its inline code. They can evaluate an argument
    1549              : // twice.
    1550              : #define ccol__min(a, b) ((a) < (b) ? (a) : (b))
    1551              : 
    1552              : #define ccol__max(a, b) ((a) > (b) ? (a) : (b))
    1553              : 
    1554              : // Internal: Compares the two T values at ptr1 and ptr2 and evaluates to -1, 0
    1555              : // or 1 (negative, zero or positive in general). cbstmap and the default
    1556              : // comparators use it. Both are read with memcpy, because the bytes can come
    1557              : // from a hand-built cmap_pair with no alignment and no effective type of T, and
    1558              : // a load through a T * would be undefined. A constant-size memcpy compiles to
    1559              : // the same single load.
    1560              : #define ccol__typed_cmp(ptr1, ptr2, T)                                     \
    1561              :   ({                                                                       \
    1562              :     T ccol__tcmp_lhs;                                                      \
    1563              :     T ccol__tcmp_rhs;                                                      \
    1564              :     memcpy(&ccol__tcmp_lhs, (ptr1), sizeof(T));                            \
    1565              :     memcpy(&ccol__tcmp_rhs, (ptr2), sizeof(T));                            \
    1566              :     (ccol__tcmp_lhs > ccol__tcmp_rhs) - (ccol__tcmp_lhs < ccol__tcmp_rhs); \
    1567              :   })
    1568              : 
    1569              : #pragma GCC visibility pop
        

Generated by: LCOV version 2.0-1