LCOV - code coverage report
Current view: top level - src - cjson.c (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 95.9 % 1503 1442
Test Date: 2026-11-15 18:57:05 Functions: 100.0 % 87 87
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              : // The JSON parser, serializer and DOM of cjson.h. Lists are cvectors and
      26              : // dictionaries are chmaps keyed by string. Every string that a node can reach
      27              : // (a value or a key) is well-formed UTF-8; each place where bytes enter the DOM
      28              : // refuses anything else, which is what lets the serializer copy bytes >= 0x20
      29              : // straight through. Parse, clone and serialize walk the nesting with explicit
      30              : // stacks on the heap and destroy uses a worklist, so no function's native stack
      31              : // depends on how deep a tree is.
      32              : #include <chashmap.h>
      33              : #include <cjson.h>
      34              : #include <cvector.h>
      35              : #include <errno.h>
      36              : #include <float.h>
      37              : #include <internal/cgrowbuf.h>
      38              : #include <internal/chashinsert.h>
      39              : #include <internal/cnumlocale.h>
      40              : #include <internal/cprocsintern.h>
      41              : #include <internal/cstrutil.h>
      42              : #include <internal/ctlsmodel.h>
      43              : #include <internal/cutf8.h>
      44              : #include <internal/test_helpers/cjson.h>
      45              : #include <locale.h>
      46              : #include <math.h>
      47              : #include <stdarg.h>
      48              : #include <stdatomic.h>
      49              : 
      50              : // The node behind the opaque cjson handle. m_procs is NULL for the default
      51              : // allocator or an interned copy from ccol_procs_intern(), never the caller's
      52              : // pointer, and every node of a tree carries the same value. attached becomes
      53              : // true once a push or a set puts the node into a container and is never
      54              : // cleared; it's how cjson_list_push() and cjson_dictionary_set() refuse a child
      55              : // that already has a parent (two owners would mean a double free). A list or
      56              : // dictionary store stays NULL until the first child arrives, so "[]" and "{}"
      57              : // cost one node.
      58              : typedef struct cjson_node {
      59              :   cjson_node_type type;
      60              :   bool attached;
      61              :   ccol_memmgmt_procs *m_procs;
      62              :   union {
      63              :     bool boolean;
      64              :     long long integer;
      65              :     double number;
      66              :     char *string;
      67              :     cvec list;
      68              :     chmap dictionary;
      69              :   } value;
      70              : } cjson_node;
      71              : 
      72              : // The serializer's output buffer, a ccol_growbuf with short sb_* names. Every
      73              : // operation does nothing once oom is set, so a serialization checks for an
      74              : // error once, at the end.
      75              : typedef ccol_growbuf sbuf;
      76              : 
      77              : // The sb_* wrappers (init, append n bytes, append a byte, append a C string)
      78              : // forward to ccol_growbuf, so the serializer and the string decoder have a
      79              : // short vocabulary of their own.
      80        20405 : static inline void sb_init(sbuf *sb, ccol_memmgmt_procs *mp) {
      81        20405 :   ccol_growbuf_init(sb, mp);
      82              : }
      83              : 
      84        40496 : static inline void sb_append(sbuf *sb, const char *data, size_t n) {
      85        40496 :   ccol_growbuf_append(sb, data, n);
      86        11452 : }
      87              : 
      88        69524 : static inline void sb_append_c(sbuf *sb, char c) {
      89       139048 :   ccol_growbuf_append_c(sb, c);
      90        35373 : }
      91              : 
      92        20044 : static inline void sb_append_cstr(sbuf *sb, const char *s) {
      93        20044 :   ccol_growbuf_append_cstr(sb, s);
      94           11 : }
      95              : 
      96              : // Like sb_init(), with a starting capacity of at least 64 bytes; the string
      97              : // decoder uses it because it knows the length of the literal.
      98         1793 : static inline void sb_init_hint(sbuf *sb, ccol_memmgmt_procs *mp, size_t hint) {
      99         1793 :   ccol_growbuf_init_hint(sb, mp, hint);
     100         1793 : }
     101              : 
     102              : // Test counters: C strings checked by utf8_cstr_is_valid() and nodes that the
     103              : // cycle search of node_reaches() took off its stack, over all threads.
     104              : #ifdef RUNNING_UNIT_TESTS
     105              : atomic_ulong cjson__utf8_cstr_checks_for_tests;
     106              : 
     107              : atomic_ulong cjson__cycle_search_nodes_for_tests;
     108              : #endif
     109              : 
     110              : // Tells whether a NUL-terminated string is well-formed UTF-8. Every API call
     111              : // that takes a C string for the DOM (a string value, a key, a path leaf) uses
     112              : // it, so no ill-formed byte gets in. A NULL s passes, so a caller can check an
     113              : // optional string. Counts calls in cjson__utf8_cstr_checks_for_tests.
     114         3274 : static bool utf8_cstr_is_valid(const char *s) {
     115              : #ifdef RUNNING_UNIT_TESTS
     116         3274 :   atomic_fetch_add_explicit(&cjson__utf8_cstr_checks_for_tests, 1,
     117              :                             memory_order_relaxed);
     118              : #endif
     119         3274 :   return !s || ccol_utf8_is_valid(s, strlen(s));
     120              : }
     121              : 
     122              : // Converts nptr with strtod() in the "C" locale. The number parser needs it
     123              : // because JSON always writes '.' as the decimal point while strtod() follows
     124              : // the LC_NUMERIC of the calling thread.
     125           69 : static double cjson_strtod_c(const char *nptr) {
     126           69 :   ccol_c_locale_scope scope = ccol_c_locale_enter();
     127           69 :   double v = strtod(nptr, NULL);
     128           69 :   ccol_c_locale_leave(scope);
     129           69 :   return v;
     130              : }
     131              : 
     132              : // Writes into buf (cap bytes) the shortest "%.Ng" text that reads back as
     133              : // exactly val, in the "C" locale. The serializer uses it so a double round
     134              : // trips with no noise digits and '.' as the decimal point in every locale. A
     135              : // normal double tries 15, 16 and 17 digits (anything with at most DBL_DIG
     136              : // digits survives, so 1/3 is 0.3333333333333333); a subnormal has fewer bits
     137              : // and tries every precision from 1 upward (5e-324 stays 5e-324).
     138        20031 : static void cjson_format_shortest_c(char *buf, size_t cap, double val) {
     139        20031 :   ccol_c_locale_scope scope = ccol_c_locale_enter();
     140        20031 :   int prec = (val != 0.0 && fabs(val) < DBL_MIN) ? 1 : 15;
     141       183517 :   for (; prec < 17; prec++) {
     142       176211 :     snprintf(buf, cap, "%.*g", prec, val);
     143       176211 :     if (strtod(buf, NULL) == val) break;
     144              :   }
     145        20031 :   if (prec == 17) snprintf(buf, cap, "%.17g", val);
     146        20031 :   ccol_c_locale_leave(scope);
     147        20031 : }
     148              : 
     149              : // Reads the child pointer stored at src. Containers keep child pointers in
     150              : // cvector and chmap slots, and every read of one goes through here; the memcpy
     151              : // is a second line of defence against an unaligned slot.
     152        86123 : static inline cjson_node *cjson_read_child(const void *src) {
     153        86123 :   cjson_node *p;
     154        86123 :   memcpy(&p, src, sizeof(p));
     155          406 :   return p;
     156              : }
     157              : 
     158              : // Gives the number of elements of list n. This and the accessors below read a
     159              : // container's store, which stays NULL until the first child (so an empty
     160              : // container costs one node); they treat a NULL store as empty, and every insert
     161              : // goes through list_store() or dict_store() to create it.
     162       138232 : static inline size_t list_len_of(const cjson_node *n) {
     163       118167 :   return n->value.list ? cvector_size(n->value.list) : 0;
     164              : }
     165              : 
     166              : // Gives element index of list n, or NULL when index is out of range; used by
     167              : // the getters, the path walk and the clone.
     168          104 : static inline cjson_node *list_child_at(const cjson_node *n, size_t index) {
     169          104 :   if (!n->value.list) return NULL;
     170          101 :   void *slot = cvector_at(n->value.list, index);
     171          101 :   return slot ? *(cjson_node **)slot : NULL;
     172              : }
     173              : 
     174              : // Gives the number of members of dictionary n, for cjson_dictionary_size().
     175          438 : static inline size_t dict_size_of(const cjson_node *n) {
     176          427 :   return n->value.dictionary ? chashmap_size(n->value.dictionary) : 0;
     177              : }
     178              : 
     179              : // Looks key_pair up in dictionary n, for every read of a member by key. On
     180              : // ccol_success *vp describes the stored value; any other code means the key is
     181              : // absent (and *vp is cleared when there is no store).
     182         1971 : static inline ccol_retval dict_lookup(const cjson_node *n,
     183              :                                       const cmap_pair *key_pair,
     184              :                                       cmap_pair *vp) {
     185         1971 :   if (!n->value.dictionary) {
     186              :     vp->ptr = NULL;
     187              :     vp->size = 0;
     188              :     return ccol_key_not_found;
     189              :   }
     190         1959 :   return chashmap_get_elem_ref(n->value.dictionary, key_pair, vp);
     191              : }
     192              : 
     193              : // Gives the store of list n, creating it with n's allocator on the first call,
     194              : // so every insert has a store to push into. NULL when the creation fails, with
     195              : // n unchanged.
     196       179157 : static cvec list_store(cjson_node *n) {
     197       179157 :   if (!n->value.list)
     198       102062 :     n->value.list = cvector_create_full(sizeof(cjson_node *), n->m_procs, NULL);
     199       179157 :   return n->value.list;
     200              : }
     201              : 
     202              : // Gives the store of dictionary n, creating a compact chmap with n's allocator
     203              : // on the first call, so every insert has a store. NULL when the creation
     204              : // fails, with n unchanged.
     205        70295 : static chmap dict_store(cjson_node *n) {
     206        70295 :   if (!n->value.dictionary) {
     207        65629 :     char *err = NULL;
     208        65629 :     n->value.dictionary =
     209        65629 :         ccol_chmap_create_compact(ccol_string, ccol_pointer, n->m_procs, &err);
     210              :   }
     211        70295 :   return n->value.dictionary;
     212              : }
     213              : 
     214              : // Gives the oldest member of dictionary n, or NULL. Parse, clone, the
     215              : // serializers, the cycle check and the public iterator walk members from here
     216              : // in insertion order, without allocating. A new key goes last, a replace keeps
     217              : // its place and a delete takes it out.
     218        13082 : static inline const ccol_chmap_entry_ref *dict_first_entry(cjson_node *n) {
     219        13067 :   return n->value.dictionary ? ccol_chmap_oldest_entry(n->value.dictionary)
     220            8 :                              : NULL;
     221              : }
     222              : 
     223              : // A heap worklist that tears a subtree down without recursion. The public API
     224              : // can build a tree of any depth, and destruction can't fail, so a depth cap
     225              : // would only turn a crash into a silent leak.
     226              : typedef struct destroy_worklist {
     227              :   cjson_node **items;
     228              :   size_t cap;
     229              :   size_t len;
     230              : } destroy_worklist;
     231              : 
     232              : // Queues child on wl for destruction, so a teardown never recurses per level.
     233              : // A NULL child is ignored. The worklist grows with the default allocator,
     234              : // since it's scratch state unrelated to any node's m_procs. When it can't
     235              : // grow, the child is destroyed at once by a recursive cjson__destroy(): Stack
     236              : // use then follows the depth of that one subtree, but only when the tree is
     237              : // deep and memory has run out together.
     238       247846 : static void destroy_worklist_push(destroy_worklist *wl, cjson_node *child) {
     239       247846 :   if (!child) return;
     240       247846 :   if (wl->len == wl->cap) {
     241         2990 :     size_t new_cap = wl->cap == 0 ? 32 : wl->cap * 2;
     242         2990 :     cjson_node **grown =
     243         2990 :         ccol__default_mem_realloc(wl->items, new_cap * sizeof(*wl->items));
     244         2990 :     if (!grown) {
     245            0 :       cjson__destroy((cjson)child);
     246            0 :       return;
     247              :     }
     248         2990 :     wl->items = grown;
     249         2990 :     wl->cap = new_cap;
     250              :   }
     251       247846 :   wl->items[wl->len++] = child;
     252              : }
     253              : 
     254              : // Queues the child of one dictionary entry on the worklist in dtor_ctx. It's
     255              : // the value destructor that node_clear_value() hands to
     256              : // chashmap_destroy_with_dtor(), which walks the map's storage directly and so
     257              : // reaches every entry without an allocation that could fail and leak the rest.
     258        68701 : static void cjson_enqueue_dict_child(const cmap_pair *val_pair,
     259              :                                      void *dtor_ctx) {
     260        68701 :   cjson_node *child = cjson_read_child(val_pair->ptr);
     261        68701 :   destroy_worklist_push((destroy_worklist *)dtor_ctx, child);
     262        68701 : }
     263              : 
     264              : // Pushes item onto the search stack of node_reaches(). *stack starts at the
     265              : // caller's inline_stack (inline_cap entries) and moves to the default heap once
     266              : // it outgrows it, so attaching a small subtree allocates nothing. *cap and *len
     267              : // describe the stack. Returns false, with nothing changed, when the growth
     268              : // fails.
     269          513 : static bool cycle_stack_push(cjson_node ***stack, cjson_node **inline_stack,
     270              :                              size_t inline_cap, size_t *cap, size_t *len,
     271              :                              cjson_node *item) {
     272          513 :   if (*len == *cap) {
     273            4 :     size_t new_cap = *cap * 2;
     274            4 :     cjson_node **grown;
     275            4 :     if (*stack == inline_stack) {
     276            1 :       grown = ccol__default_mem_alloc(new_cap * sizeof(**stack));
     277            1 :       if (!grown) return false;
     278            1 :       memcpy(grown, inline_stack, inline_cap * sizeof(**stack));
     279              :     } else {
     280            3 :       grown = ccol__default_mem_realloc(*stack, new_cap * sizeof(**stack));
     281            3 :       if (!grown) return false;
     282              :     }
     283            4 :     *stack = grown;
     284            4 :     *cap = new_cap;
     285              :   }
     286          513 :   (*stack)[(*len)++] = item;
     287          513 :   return true;
     288              : }
     289              : 
     290              : // Tells whether needle is haystack or lies somewhere below it.
     291              : // cjson_list_push() and cjson_dictionary_set() use it to refuse a child whose
     292              : // subtree reaches the target: The attach would close a cycle, and the teardown
     293              : // would then free a node twice. A needle that was never attached has no parent,
     294              : // so nothing can reach it; that answer costs O(1) and keeps a tree built bottom
     295              : // up linear. The search uses an explicit stack, because the subtree can be
     296              : // deeper than the native stack allows. *incomplete is set when the stack can't
     297              : // grow before needle is found; the caller must treat that as out of memory,
     298              : // never as safe. Counts visited nodes in cjson__cycle_search_nodes_for_tests.
     299        45911 : static bool node_reaches(cjson_node *haystack, const cjson_node *needle,
     300              :                          bool *incomplete) {
     301        45911 :   *incomplete = false;
     302        45911 :   if ((const cjson_node *)haystack == needle) return true;
     303        45911 :   if (!needle->attached) return false;
     304            9 :   if (haystack->type != CJSON_LIST && haystack->type != CJSON_DICTIONARY)
     305              :     return false;
     306              : 
     307            6 :   cjson_node *inline_stack[32];
     308            6 :   cjson_node **stack = inline_stack;
     309            6 :   size_t cap = sizeof(inline_stack) / sizeof(inline_stack[0]);
     310            6 :   size_t len = 0;
     311            6 :   bool found = false;
     312              : 
     313            6 :   if (!cycle_stack_push(&stack, inline_stack, cap, &cap, &len, haystack)) {
     314            0 :     *incomplete = true;
     315            0 :     return false;
     316              :   }
     317              : 
     318          516 :   while (len > 0 && !found) {
     319          513 :     cjson_node *n = stack[--len];
     320              : #ifdef RUNNING_UNIT_TESTS
     321          513 :     atomic_fetch_add_explicit(&cjson__cycle_search_nodes_for_tests, 1,
     322              :                               memory_order_relaxed);
     323              : #endif
     324          513 :     if ((const cjson_node *)n == needle) {
     325              :       found = true;
     326              :       break;
     327              :     }
     328          510 :     if (n->type == CJSON_LIST) {
     329            6 :       size_t cnt = list_len_of(n);
     330          512 :       for (size_t i = 0; i < cnt; i++) {
     331          506 :         cjson_node *c = *(cjson_node **)cvector_at(n->value.list, i);
     332          506 :         if (!cycle_stack_push(&stack, inline_stack,
     333              :                               sizeof(inline_stack) / sizeof(*inline_stack),
     334              :                               &cap, &len, c)) {
     335            0 :           *incomplete = true;
     336            0 :           goto done;
     337              :         }
     338              :       }
     339          504 :     } else if (n->type == CJSON_DICTIONARY) {
     340            1 :       const cmap_pair *kp, *vp;
     341            3 :       for (const ccol_chmap_entry_ref *e = dict_first_entry(n); e;) {
     342            1 :         e = ccol_chmap_entry_read(e, &kp, &vp);
     343            1 :         cjson_node *c = cjson_read_child(vp->ptr);
     344            1 :         if (!cycle_stack_push(&stack, inline_stack,
     345              :                               sizeof(inline_stack) / sizeof(*inline_stack),
     346              :                               &cap, &len, c)) {
     347            0 :           *incomplete = true;
     348            0 :           goto done;
     349              :         }
     350              :       }
     351              :     }
     352              :   }
     353              : 
     354            3 : done:
     355            6 :   if (stack != inline_stack) ccol__default_mem_free(stack);
     356              :   return found;
     357              : }
     358              : 
     359              : // The thread-local node pool. It holds only nodes of the default allocator
     360              : // (m_procs == NULL), so node_pool_drain() frees them with plain free(). A
     361              : // pooled node keeps the next pointer of the free list in its own bytes, read
     362              : // back with memcpy. NODE_POOL_CAP bounds the list.
     363              : #define NODE_POOL_CAP 512U
     364              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     365              : // With CCOL__EMULATE_DARWIN_TLS, one thread's pool and error buffer live in a
     366              : // heap block whose pointer is the value of the pool key, so node_pool_drain()
     367              : // gets it as its argument and reads no __thread variable. A thread has a value
     368              : // on the key exactly as long as it has a block.
     369              : typedef struct {
     370              :   cjson_node *head;
     371              :   unsigned sz;
     372              :   char *err_buf;
     373              : } cjson_tls;
     374              : static cjson_tls *cjson_tls_peek(void);
     375              : static cjson_tls *cjson_tls_get(void);
     376              : #else
     377              : // Elsewhere the pool is plain __thread state. pool_key_armed records that this
     378              : // thread has set its value on the key, which needs to happen once per thread,
     379              : // so the lock is taken once per thread and not on every refill.
     380              : static __thread cjson_node *node_pool_head = NULL;
     381              : static __thread unsigned node_pool_sz = 0;
     382              : static __thread bool pool_key_armed = false;
     383              : #endif
     384              : // Test counters: Arms of the pool key that took the lock, and the nodes that
     385              : // the pools of all threads hold.
     386              : #ifdef RUNNING_UNIT_TESTS
     387              : atomic_ulong cjson__pool_key_lock_count_for_tests;
     388              : atomic_long cjson__pool_population_for_tests;
     389              : #endif
     390              : 
     391              : // Allocates a zeroed node of the given type with allocator mp; every node of
     392              : // the module is born here. With the default allocator (mp NULL) it reuses a
     393              : // node from this thread's pool when there is one, which saves a calloc and a
     394              : // free per node when documents are parsed and destroyed in a loop. Returns NULL
     395              : // when the allocation fails. Takes a node off the thread's pool and lowers
     396              : // cjson__pool_population_for_tests.
     397       279237 : static cjson_node *node_alloc(cjson_node_type type, ccol_memmgmt_procs *mp) {
     398       279237 :   cjson_node *n;
     399              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     400              :   cjson_tls *t = mp == NULL ? cjson_tls_peek() : NULL;
     401              :   if (t && t->head) {
     402              :     n = t->head;
     403              :     cjson_node *next;
     404              :     memcpy(&next, (cjson_node **)n, sizeof(next));
     405              :     t->head = next;
     406              :     t->sz--;
     407              : #else
     408       279237 :   if (mp == NULL && node_pool_head) {
     409        41466 :     n = node_pool_head;
     410        41466 :     cjson_node *next;
     411        41466 :     memcpy(&next, (cjson_node **)n, sizeof(next));
     412        41466 :     node_pool_head = next;
     413        41466 :     node_pool_sz--;
     414              : #endif
     415              : #ifdef RUNNING_UNIT_TESTS
     416        41466 :     atomic_fetch_sub_explicit(&cjson__pool_population_for_tests, 1,
     417              :                               memory_order_relaxed);
     418              : #endif
     419        41466 :     memset(n, 0, sizeof(*n));
     420              :   } else {
     421       237771 :     n = ccol__mem_calloc(mp, 1, sizeof(*n));
     422       237775 :     if (!n) return NULL;
     423              :   }
     424       279214 :   n->type = type;
     425       279214 :   n->attached = false;
     426       279214 :   n->m_procs = mp;
     427       279214 :   return n;
     428              : }
     429              : 
     430              : // The key whose destructor (node_pool_drain) empties a thread's pool and frees
     431              : // its error buffer at thread exit.
     432              : static ccol__thread_ls_key pool_pthread_key;
     433              : 
     434              : // True once do_pool_key_init() has created the key and the rwlock, false again
     435              : // after pool_key_fini() deletes the key. It stays false when either init call
     436              : // fails, so check it before using the key or the lock.
     437              : static atomic_bool pool_key_live = false;
     438              : 
     439              : // True once the shared object's destructor has run. A later first use (from an
     440              : // application destructor, say) must not create a key that nothing would delete
     441              : // or drain, so the pool stays unarmed and nodes go straight to the allocator.
     442              : static atomic_bool pool_key_finalized = false;
     443              : 
     444              : // Held around the check of pool_key_live and the ccol__thread_ls_set() that
     445              : // acts on it (read side), and around the delete of the key in pool_key_fini()
     446              : // (write side), so a set never runs on a key that is being deleted.
     447              : static ccol__rw_lock pool_key_rwlock;
     448              : 
     449              : static void node_pool_drain(void *);
     450              : 
     451              : // Runs do_pool_key_init() once, lazily, on the first node_free() or parse error
     452              : // that needs the pool key.
     453              : static ccol__once_flag pool_key_once = CCOL__ONCE_INIT;
     454              : 
     455              : // Creates pool_key_rwlock and pool_pthread_key, the two primitives the pool and
     456              : // the error buffer need, and only then sets pool_key_live. It runs once under
     457              : // pool_key_once and does nothing once pool_key_finalized is set.
     458            3 : static void do_pool_key_init(void) {
     459            3 :   if (atomic_load(&pool_key_finalized)) return;
     460            3 :   if (ccol__rw_lock_init(pool_key_rwlock) != 0) return;
     461            3 :   if (ccol__thread_ls_key_create(pool_pthread_key, node_pool_drain) != 0)
     462              :     return;
     463            2 :   atomic_store(&pool_key_live, true);
     464              : }
     465              : 
     466              : // Tears the pool key down when the shared object is unloaded (dlclose or exit),
     467              : // so repeated dlopen and dlclose cycles don't use up PTHREAD_KEYS_MAX and the
     468              : // calling thread's pool is freed while the code is still mapped. It sets
     469              : // pool_key_finalized, drains the calling thread's pool, and then clears
     470              : // pool_key_live and deletes the key under the write lock of pool_key_rwlock,
     471              : // so no node_free() can be inside ccol__thread_ls_set() on the key meanwhile.
     472              : // Without a live key it does nothing more (the lock was never initialized).
     473            4 : __attribute__((destructor)) static void pool_key_fini(void) {
     474            4 :   atomic_store(&pool_key_finalized, true);
     475            4 :   if (!atomic_load(&pool_key_live)) return;
     476              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     477              :   cjson_tls *t = cjson_tls_peek();
     478              :   if (t) {
     479              :     (void)ccol__thread_ls_set(pool_pthread_key, NULL);
     480              :     node_pool_drain(t);
     481              :   }
     482              : #else
     483            3 :   node_pool_drain(NULL);
     484              : #endif
     485            3 :   ccol__rw_lock_wrlock(pool_key_rwlock);
     486            3 :   atomic_store(&pool_key_live, false);
     487            3 :   ccol__thread_ls_key_delete(pool_pthread_key);
     488            3 :   ccol__rw_lock_unlock(pool_key_rwlock);
     489              : }
     490              : 
     491              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     492              : // Gives the calling thread's pool block, or NULL when it has none or the key
     493              : // isn't live; node_alloc() uses it because it must not create a block.
     494              : static cjson_tls *cjson_tls_peek(void) {
     495              :   if (!atomic_load_explicit(&pool_key_live, memory_order_acquire)) return NULL;
     496              :   return (cjson_tls *)ccol__thread_ls_get(pool_pthread_key);
     497              : }
     498              : 
     499              : // Gives the calling thread's pool block, creating it and setting it on the pool
     500              : // key when it has none; node_free() and cjson_report_err() need a block to keep
     501              : // nodes or a message in. NULL when the key isn't live, the set fails or memory
     502              : // runs out. Takes the read side of pool_key_rwlock for the set. The caller must
     503              : // have run the once-guard.
     504              : static cjson_tls *cjson_tls_get(void) {
     505              :   cjson_tls *t = cjson_tls_peek();
     506              :   if (t || !atomic_load(&pool_key_live)) return t;
     507              :   t = (cjson_tls *)calloc(1, sizeof(*t));
     508              :   if (!t) return NULL;
     509              :   bool set = false;
     510              :   ccol__rw_lock_rdlock(pool_key_rwlock);
     511              : #ifdef RUNNING_UNIT_TESTS
     512              :   atomic_fetch_add_explicit(&cjson__pool_key_lock_count_for_tests, 1,
     513              :                             memory_order_relaxed);
     514              : #endif
     515              :   if (atomic_load(&pool_key_live) &&
     516              :       ccol__thread_ls_set(pool_pthread_key, t) == 0)
     517              :     set = true;
     518              :   ccol__rw_lock_unlock(pool_key_rwlock);
     519              :   if (!set) {
     520              :     free(t);
     521              :     return NULL;
     522              :   }
     523              :   return t;
     524              : }
     525              : #else
     526              : // Sets this thread's value on the pool key, once per thread, so that
     527              : // node_pool_drain() runs at thread exit; node_free() and cjson_report_err()
     528              : // need that before they keep anything per thread. It takes the read side of
     529              : // pool_key_rwlock, checks pool_key_live again under it and sets pool_key_armed
     530              : // on success. The caller must have run the once-guard. Always inlined so
     531              : // node_free() keeps its shape.
     532         2250 : static inline __attribute__((always_inline)) void pool_key_arm(void) {
     533         2208 :   if (!pool_key_armed && atomic_load(&pool_key_live)) {
     534            8 :     ccol__rw_lock_rdlock(pool_key_rwlock);
     535              : #ifdef RUNNING_UNIT_TESTS
     536            8 :     atomic_fetch_add_explicit(&cjson__pool_key_lock_count_for_tests, 1,
     537              :                               memory_order_relaxed);
     538              : #endif
     539           16 :     if (atomic_load(&pool_key_live) &&
     540            8 :         ccol__thread_ls_set(pool_pthread_key, (void *)1) == 0)
     541            8 :       pool_key_armed = true;
     542            8 :     ccol__rw_lock_unlock(pool_key_rwlock);
     543              :   }
     544              : }
     545              : 
     546              : // This thread's message buffer for a failed parse (see cjson_report_err());
     547              : // node_pool_drain() frees it.
     548              : static __thread char *cjson_err_buf;
     549              : #endif
     550              : 
     551              : // Frees a node; every node of the module dies here. A custom allocator frees it
     552              : // directly. With the default allocator the node goes back on this thread's pool
     553              : // when the pool has room, so node_alloc() can reuse it. A thread whose key
     554              : // can't be armed (no key left, a failed set, or a call after pool_key_fini())
     555              : // pools nothing, because nothing would ever drain it. The unlocked check of
     556              : // pool_key_live only skips a rwlock that was never initialized; the check under
     557              : // the lock is what makes the race with pool_key_fini() safe. Changes the
     558              : // thread's pool and cjson__pool_population_for_tests.
     559       279210 : static void node_free(cjson_node *n) {
     560       279210 :   if (n->m_procs != NULL) {
     561       184903 :     ccol__mem_free(n->m_procs, n);
     562       184903 :     return;
     563              :   }
     564              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     565              :   ccol__call_once(pool_key_once, do_pool_key_init);
     566              :   cjson_tls *t = cjson_tls_get();
     567              :   if (!t || t->sz >= NODE_POOL_CAP) {
     568              :     free(n);
     569              :     return;
     570              :   }
     571              :   memcpy((cjson_node **)n, &t->head, sizeof(t->head));
     572              :   t->head = n;
     573              :   t->sz++;
     574              : #ifdef RUNNING_UNIT_TESTS
     575              :   atomic_fetch_add_explicit(&cjson__pool_population_for_tests, 1,
     576              :                             memory_order_relaxed);
     577              : #endif
     578              : #else
     579        94307 :   if (node_pool_sz >= NODE_POOL_CAP) {
     580        49587 :     free(n);
     581        49587 :     return;
     582              :   }
     583        44720 :   ccol__call_once(pool_key_once, do_pool_key_init);
     584        44721 :   if (node_pool_sz == 0) {
     585         2198 :     pool_key_arm();
     586         2198 :     if (!pool_key_armed) {
     587         2149 :       free(n);
     588         2149 :       return;
     589              :     }
     590              :   }
     591        42572 :   memcpy((cjson_node **)n, &node_pool_head, sizeof(node_pool_head));
     592        42572 :   node_pool_head = n;
     593        42572 :   node_pool_sz++;
     594              : #ifdef RUNNING_UNIT_TESTS
     595        42572 :   atomic_fetch_add_explicit(&cjson__pool_population_for_tests, 1,
     596              :                             memory_order_relaxed);
     597              : #endif
     598              : #endif
     599              : }
     600              : 
     601              : // Frees every pooled node of the calling thread and its error buffer. It's the
     602              : // destructor of the pool key, so a thread's pool doesn't leak at thread exit,
     603              : // and pool_key_fini() calls it for the unloading thread. With
     604              : // CCOL__EMULATE_DARWIN_TLS it frees the block that arg names. Otherwise it
     605              : // resets the __thread pool and clears pool_key_armed: The C library has already
     606              : // cleared the key's value, and if a later key destructor refills the pool, the
     607              : // refill must set the value again so the C library runs this destructor once
     608              : // more. Lowers cjson__pool_population_for_tests.
     609              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     610              : static void node_pool_drain(void *arg) {
     611              :   cjson_tls *t = (cjson_tls *)arg;
     612              :   if (!t) return;
     613              :   cjson_node *n = t->head;
     614              :   while (n) {
     615              :     cjson_node *next;
     616              :     memcpy(&next, (cjson_node **)n, sizeof(next));
     617              :     free(n);
     618              :     n = next;
     619              :   }
     620              : #ifdef RUNNING_UNIT_TESTS
     621              :   atomic_fetch_sub_explicit(&cjson__pool_population_for_tests, (long)t->sz,
     622              :                             memory_order_relaxed);
     623              : #endif
     624              :   free(t->err_buf);
     625              :   free(t);
     626              : }
     627              : #else
     628            9 : static void node_pool_drain(void *arg) {
     629            9 :   (void)arg;
     630            9 :   cjson_node *n = node_pool_head;
     631         1607 :   while (n) {
     632         1598 :     cjson_node *next;
     633         1598 :     memcpy(&next, (cjson_node **)n, sizeof(next));
     634         1598 :     free(n);
     635         1598 :     n = next;
     636              :   }
     637              : #ifdef RUNNING_UNIT_TESTS
     638            9 :   atomic_fetch_sub_explicit(&cjson__pool_population_for_tests,
     639              :                             (long)node_pool_sz, memory_order_relaxed);
     640              : #endif
     641            9 :   node_pool_head = NULL;
     642            9 :   node_pool_sz = 0;
     643            9 :   free(cjson_err_buf);
     644            9 :   cjson_err_buf = NULL;
     645            9 :   pool_key_armed = false;
     646            9 : }
     647              : #endif
     648              : 
     649              : // Gives the size of the calling thread's pool, so the white-box tests can check
     650              : // the cap and that threads don't share a pool.
     651              : #ifdef RUNNING_UNIT_TESTS
     652              : #if defined(CCOL__EMULATE_DARWIN_TLS)
     653              : size_t cjson_debug_pool_size(void) {
     654              :   cjson_tls *t = cjson_tls_peek();
     655              :   return t ? (size_t)t->sz : 0;
     656              : }
     657              : #else
     658           59 : size_t cjson_debug_pool_size(void) { return (size_t)node_pool_sz; }
     659              : #endif
     660              : #endif
     661              : 
     662              : // Frees the payload of n (string bytes or a container store) and pushes every
     663              : // direct child onto wl instead of recursing; node_clear(), cjson__destroy() and
     664              : // the worklist drain build every teardown on it. n->type and n itself stay.
     665       279300 : static void node_clear_value(cjson_node *n, destroy_worklist *wl) {
     666       279300 :   switch (n->type) {
     667        10493 :     case CJSON_STRING:
     668        10493 :       ccol__mem_free(n->m_procs, n->value.string);
     669        10493 :       n->value.string = NULL;
     670        10493 :       break;
     671              :     case CJSON_LIST: {
     672       122098 :       size_t cnt = list_len_of(n);
     673       301243 :       for (size_t i = 0; i < cnt; i++) {
     674       179145 :         cjson_node *child = *(cjson_node **)cvector_at(n->value.list, i);
     675       179144 :         destroy_worklist_push(wl, child);
     676              :       }
     677       122098 :       cvector__destroy(n->value.list);
     678       122098 :       n->value.list = NULL;
     679       122098 :       break;
     680              :     }
     681        81256 :     case CJSON_DICTIONARY: {
     682        81256 :       chashmap_destroy_with_dtor(n->value.dictionary, cjson_enqueue_dict_child,
     683              :                                  wl);
     684        81256 :       n->value.dictionary = NULL;
     685        81256 :       break;
     686              :     }
     687              :     default:
     688              :       break;
     689              :   }
     690       279300 : }
     691              : 
     692              : // Destroys every node on wl, structs included, to finish a teardown that
     693              : // node_clear_value() started. Each drained node adds its own children, so the
     694              : // loop ends when the whole subtree is gone.
     695        31455 : static void destroy_worklist_drain(destroy_worklist *wl) {
     696       279300 :   while (wl->len > 0) {
     697       247845 :     cjson_node *n = wl->items[--wl->len];
     698       247845 :     node_clear_value(n, wl);
     699       247844 :     node_free(n);
     700              :   }
     701        31455 : }
     702              : 
     703              : // Frees everything the value of n owns, without freeing n.
     704              : // node_reinit_scalar_checked() uses it to drop an old value before it writes a
     705              : // new scalar in place. The old value can be a tree of any depth, so it goes
     706              : // through the worklist.
     707           88 : static void node_clear(cjson_node *n) {
     708           88 :   destroy_worklist wl = {NULL, 0, 0};
     709           88 :   node_clear_value(n, &wl);
     710           88 :   destroy_worklist_drain(&wl);
     711           88 :   ccol__default_mem_free(wl.items);
     712           88 : }
     713              : 
     714              : // Checks a scalar payload (type, raw, raw_size) from cjson_set() or a direct
     715              : // cjson__set_typed() call, touching no node, so a set can refuse before
     716              : // anything changes. Gives ccol_invalid_args for a container or unknown type
     717              : // (which includes CJSON__TYPE_UNSUPPORTED), a NULL raw for anything but
     718              : // CJSON_NULL, a non-NULL void *, a raw_size that doesn't fit the type (a direct
     719              : // call can pass a narrower buffer), a non-finite float and a string that isn't
     720              : // UTF-8. After ccol_success the store can only fail for lack of memory.
     721          113 : static ccol_retval scalar_payload_check(cjson_node_type type, void *raw,
     722              :                                         size_t raw_size) {
     723          113 :   switch (type) {
     724              :     case CJSON_NULL:
     725              :     case CJSON_BOOL:
     726              :     case CJSON_INTEGER:
     727              :     case CJSON_FLOAT:
     728              :     case CJSON_STRING:
     729          110 :       break;
     730              :     default:
     731              :       return ccol_invalid_args;
     732              :   }
     733              : 
     734          110 :   if (type != CJSON_NULL && !raw) return ccol_invalid_args;
     735              : 
     736          106 :   if (type == CJSON_NULL && raw && raw_size == sizeof(void *) &&
     737            7 :       *(void **)raw != NULL)
     738              :     return ccol_invalid_args;
     739              : 
     740          104 :   double pre_d = 0.0;
     741          104 :   if (type == CJSON_FLOAT) {
     742           11 :     if (raw_size == sizeof(float))
     743            8 :       pre_d = (double)*(float *)raw;
     744            3 :     else if (raw_size == sizeof(double))
     745            3 :       pre_d = *(double *)raw;
     746              :     else
     747              :       return ccol_invalid_args;
     748           11 :     if (!isfinite(pre_d)) return ccol_invalid_args;
     749              :   }
     750              : 
     751           98 :   if (type == CJSON_INTEGER) {
     752           58 :     switch (raw_size) {
     753              :       case 1:
     754              :       case 2:
     755              :       case 4:
     756              :       case 8:
     757              :         break;
     758              :       default:
     759              :         return ccol_invalid_args;
     760              :     }
     761              :   }
     762              : 
     763           97 :   if (type == CJSON_BOOL && raw_size != sizeof(bool)) return ccol_invalid_args;
     764              : 
     765           94 :   if (type == CJSON_STRING && raw_size != sizeof(const char *))
     766              :     return ccol_invalid_args;
     767              : 
     768           92 :   if (type == CJSON_STRING && !utf8_cstr_is_valid(*(const char **)raw))
     769              :     return ccol_invalid_args;
     770              :   return ccol_success;
     771              : }
     772              : 
     773              : // Overwrites n with a scalar payload that scalar_payload_check() accepted and
     774              : // frees whatever the old value owned; cjson_set() uses it to update a leaf in
     775              : // place, so a borrowed handle to the leaf stays valid. is_signed says how to
     776              : // widen an integer. The string copy (with n->m_procs) happens first, so
     777              : // ccol_not_enough_memory leaves n intact; nothing after node_clear() can fail.
     778              : // Integers are read through memcpy into a fixed-width type, and an unsigned
     779              : // value above LLONG_MAX becomes the nearest CJSON_FLOAT, as the parser reads
     780              : // the same literal. A NULL C string becomes CJSON_NULL.
     781           89 : static ccol_retval node_reinit_scalar_checked(cjson_node *n,
     782              :                                               cjson_node_type type, void *raw,
     783              :                                               size_t raw_size, bool is_signed) {
     784           89 :   double pre_d = 0.0;
     785           89 :   if (type == CJSON_FLOAT)
     786            5 :     pre_d = raw_size == sizeof(float) ? (double)*(float *)raw : *(double *)raw;
     787              : 
     788           89 :   char *new_str = NULL;
     789           89 :   if (type == CJSON_STRING) {
     790           15 :     const char *s = *(const char **)raw;
     791           15 :     if (s) {
     792           14 :       new_str = ccol_strdup(n->m_procs, s);
     793           13 :       if (!new_str) return ccol_not_enough_memory;
     794              :     }
     795              :   }
     796              : 
     797           88 :   node_clear(n);
     798           88 :   memset(&n->value, 0, sizeof(n->value));
     799           88 :   n->type = type;
     800              : 
     801           88 :   switch (type) {
     802              :     case CJSON_NULL:
     803              :       break;
     804            6 :     case CJSON_BOOL:
     805            6 :       n->value.boolean = *(bool *)raw;
     806            6 :       break;
     807           57 :     case CJSON_INTEGER: {
     808           57 :       long long v = 0;
     809           57 :       if (is_signed) {
     810           30 :         switch (raw_size) {
     811              :           case 1: {
     812            4 :             int8_t x;
     813            4 :             memcpy(&x, raw, sizeof(x));
     814            4 :             v = x;
     815            4 :             break;
     816              :           }
     817              :           case 2: {
     818            2 :             int16_t x;
     819            2 :             memcpy(&x, raw, sizeof(x));
     820            2 :             v = x;
     821            2 :             break;
     822              :           }
     823              :           case 4: {
     824           24 :             int32_t x;
     825           24 :             memcpy(&x, raw, sizeof(x));
     826           24 :             v = x;
     827           24 :             break;
     828              :           }
     829              :           case 8: {
     830            0 :             int64_t x;
     831            0 :             memcpy(&x, raw, sizeof(x));
     832            0 :             v = x;
     833            0 :             break;
     834              :           }
     835              :         }
     836              :       } else {
     837           27 :         switch (raw_size) {
     838              :           case 1: {
     839            2 :             uint8_t x;
     840            2 :             memcpy(&x, raw, sizeof(x));
     841            2 :             v = (long long)x;
     842            2 :             break;
     843              :           }
     844              :           case 2: {
     845            1 :             uint16_t x;
     846            1 :             memcpy(&x, raw, sizeof(x));
     847            1 :             v = (long long)x;
     848            1 :             break;
     849              :           }
     850              :           case 4: {
     851            2 :             uint32_t x;
     852            2 :             memcpy(&x, raw, sizeof(x));
     853            2 :             v = (long long)x;
     854            2 :             break;
     855              :           }
     856              :           case 8: {
     857           22 :             unsigned long long u;
     858           22 :             memcpy(&u, raw, sizeof(u));
     859           22 :             if (u > (unsigned long long)LLONG_MAX) {
     860           20 :               n->type = CJSON_FLOAT;
     861           20 :               n->value.number = (double)u;
     862           20 :               return ccol_success;
     863              :             }
     864           37 :             v = (long long)u;
     865              :             break;
     866              :           }
     867              :         }
     868              :       }
     869           37 :       n->value.integer = v;
     870           37 :       break;
     871              :     }
     872            5 :     case CJSON_FLOAT:
     873            5 :       n->value.number = pre_d;
     874            5 :       break;
     875           14 :     case CJSON_STRING:
     876           14 :       if (!new_str)
     877            1 :         n->type = CJSON_NULL;
     878              :       else
     879           13 :         n->value.string = new_str;
     880              :       break;
     881              :     default:
     882              :       break;
     883              :   }
     884              :   return ccol_success;
     885              : }
     886              : 
     887              : // Checks a payload and then stores it in n, for a set of an existing list
     888              : // element. Every check runs before n changes, so any failure leaves n intact.
     889              : // Gives the codes of the two steps.
     890           12 : static ccol_retval node_reinit_scalar(cjson_node *n, cjson_node_type type,
     891              :                                       void *raw, size_t raw_size,
     892              :                                       bool is_signed) {
     893           12 :   ccol_retval r = scalar_payload_check(type, raw, raw_size);
     894           12 :   if (r != ccol_success) return r;
     895           11 :   return node_reinit_scalar_checked(n, type, raw, raw_size, is_signed);
     896              : }
     897              : 
     898              : // Allocates a scalar node with mp from a payload that scalar_payload_check()
     899              : // accepted, for a set that creates a new dictionary key. Gives ccol_success
     900              : // with the node in *out, or ccol_not_enough_memory with *out NULL.
     901           41 : static ccol_retval node_make_scalar(cjson_node_type type, void *raw,
     902              :                                     size_t raw_size, bool is_signed,
     903              :                                     ccol_memmgmt_procs *mp, cjson_node **out) {
     904           41 :   *out = NULL;
     905           41 :   cjson_node *n = node_alloc(CJSON_NULL, mp);
     906           41 :   if (!n) return ccol_not_enough_memory;
     907           40 :   ccol_retval r = node_reinit_scalar_checked(n, type, raw, raw_size, is_signed);
     908           40 :   if (r != ccol_success) {
     909            1 :     node_free(n);
     910            1 :     return r;
     911              :   }
     912           39 :   *out = n;
     913           39 :   return ccol_success;
     914              : }
     915              : 
     916              : // Replaces *mp with its interned copy, so no node keeps the caller's pointer
     917              : // and the caller may free its struct; every public entry point that takes an
     918              : // allocator calls it first. Gives false when the intern table is full.
     919        74193 : static inline bool cjson_intern_procs(ccol_memmgmt_procs **mp) {
     920        74193 :   if (*mp == NULL) return true;
     921          821 :   return ccol_procs_intern(*mp, mp) == ccol_success;
     922              : }
     923              : 
     924              : // The factories behind the public ones and the parser and clone, for an mp
     925              : // that is already interned (or NULL). Each gives a new node or NULL. A
     926              : // non-finite double gives NULL, a NULL string gives a CJSON_NULL node and a
     927              : // string that isn't UTF-8 gives NULL. A new container has no store yet.
     928          671 : static cjson cjson_create_null_interned(ccol_memmgmt_procs *mp) {
     929          671 :   return (cjson)node_alloc(CJSON_NULL, mp);
     930              : }
     931              : 
     932           11 : static cjson cjson_create_bool_interned(bool val, ccol_memmgmt_procs *mp) {
     933           22 :   cjson_node *n = node_alloc(CJSON_BOOL, mp);
     934           11 :   if (n) n->value.boolean = val;
     935              :   return (cjson)n;
     936              : }
     937              : 
     938         4208 : static cjson cjson_create_int_interned(long long val, ccol_memmgmt_procs *mp) {
     939         8416 :   cjson_node *n = node_alloc(CJSON_INTEGER, mp);
     940         4208 :   if (n) n->value.integer = val;
     941              :   return (cjson)n;
     942              : }
     943              : 
     944        20020 : static cjson cjson_create_double_interned(double val, ccol_memmgmt_procs *mp) {
     945        20020 :   if (!isfinite(val)) return NULL;
     946        20017 :   cjson_node *n = node_alloc(CJSON_FLOAT, mp);
     947        20017 :   if (n) n->value.number = val;
     948              :   return (cjson)n;
     949              : }
     950              : 
     951           31 : static cjson cjson_create_string_interned(const char *val,
     952              :                                           ccol_memmgmt_procs *mp) {
     953           31 :   if (!val) return cjson_create_null_interned(mp);
     954           30 :   if (!utf8_cstr_is_valid(val)) return NULL;
     955           29 :   cjson_node *n = node_alloc(CJSON_STRING, mp);
     956           29 :   if (!n) return NULL;
     957           29 :   n->value.string = ccol_strdup(mp, val);
     958           29 :   if (!n->value.string) {
     959            0 :     node_free(n);
     960            0 :     return NULL;
     961              :   }
     962              :   return (cjson)n;
     963              : }
     964              : 
     965       122100 : static cjson cjson_create_list_interned(ccol_memmgmt_procs *mp) {
     966       122100 :   return (cjson)node_alloc(CJSON_LIST, mp);
     967              : }
     968              : 
     969        81267 : static cjson cjson_create_dictionary_interned(ccol_memmgmt_procs *mp) {
     970        81267 :   return (cjson)node_alloc(CJSON_DICTIONARY, mp);
     971              : }
     972              : 
     973              : // The public factories: Each creates one node with allocator mp (NULL for the
     974              : // default) and gives it to the caller, or NULL. They intern mp first, because
     975              : // nodes must never point at the caller's struct, and fail with NULL when the
     976              : // intern table is full.
     977          669 : cjson cjson_create_null_mp(ccol_memmgmt_procs *mp) {
     978          670 :   if (!cjson_intern_procs(&mp)) return NULL;
     979          669 :   return cjson_create_null_interned(mp);
     980              : }
     981              : 
     982           10 : cjson cjson_create_bool_mp(bool val, ccol_memmgmt_procs *mp) {
     983           12 :   if (!cjson_intern_procs(&mp)) return NULL;
     984           10 :   return cjson_create_bool_interned(val, mp);
     985              : }
     986              : 
     987         3599 : cjson cjson_create_int_mp(long long val, ccol_memmgmt_procs *mp) {
     988         3607 :   if (!cjson_intern_procs(&mp)) return NULL;
     989         3598 :   return cjson_create_int_interned(val, mp);
     990              : }
     991              : 
     992        20020 : cjson cjson_create_double_mp(double val, ccol_memmgmt_procs *mp) {
     993        20021 :   if (!cjson_intern_procs(&mp)) return NULL;
     994        20020 :   return cjson_create_double_interned(val, mp);
     995              : }
     996              : 
     997           31 : cjson cjson_create_string_mp(const char *val, ccol_memmgmt_procs *mp) {
     998           36 :   if (!cjson_intern_procs(&mp)) return NULL;
     999           31 :   return cjson_create_string_interned(val, mp);
    1000              : }
    1001              : 
    1002        41748 : cjson cjson_create_list_mp(ccol_memmgmt_procs *mp) {
    1003        41752 :   if (!cjson_intern_procs(&mp)) return NULL;
    1004        41748 :   return cjson_create_list_interned(mp);
    1005              : }
    1006              : 
    1007           53 : cjson cjson_create_dictionary_mp(ccol_memmgmt_procs *mp) {
    1008           58 :   if (!cjson_intern_procs(&mp)) return NULL;
    1009           53 :   return cjson_create_dictionary_interned(mp);
    1010              : }
    1011              : 
    1012              : // Frees node and every descendant; it's the body of cjson_destroy(), and the
    1013              : // rest of the module uses it to drop subtrees. node itself is freed directly
    1014              : // and never pushed on the worklist: A push that can't grow falls back to
    1015              : // cjson__destroy() on what it pushes, which would be this same node.
    1016        31369 : void cjson__destroy(cjson node) {
    1017        31369 :   if (!node) return;
    1018        31367 :   cjson_node *n = (cjson_node *)node;
    1019              : 
    1020        31367 :   destroy_worklist wl = {NULL, 0, 0};
    1021        31367 :   node_clear_value(n, &wl);
    1022        31367 :   node_free(n);
    1023              : 
    1024        31367 :   destroy_worklist_drain(&wl);
    1025        31367 :   ccol__default_mem_free(wl.items);
    1026              : }
    1027              : 
    1028              : // Gives the type tag of node, or CJSON_NULL for a NULL handle, so a caller can
    1029              : // check a node before it calls a typed getter.
    1030          152 : cjson_node_type cjson_type(cjson node) {
    1031          152 :   if (!node) return CJSON_NULL;
    1032          150 :   return ((cjson_node *)node)->type;
    1033              : }
    1034              : 
    1035              : // The typed getters: Each gives the value of a leaf (or the length of a
    1036              : // container) for the caller. They call ccol__fatal_err() for a NULL node or
    1037              : // another type, because reading the wrong member of the value union is a bug.
    1038           14 : bool cjson_bool_val(cjson node) {
    1039           14 :   cjson_node *n = (cjson_node *)node;
    1040           14 :   if (!n || n->type != CJSON_BOOL)
    1041            0 :     ccol__fatal_err("cjson_bool_val: node is %s, expected CJSON_BOOL",
    1042              :                     n ? cjson_type_str((cjson)n) : "NULL");
    1043           14 :   return n->value.boolean;
    1044              : }
    1045              : 
    1046          105 : long long cjson_int_val(cjson node) {
    1047          105 :   cjson_node *n = (cjson_node *)node;
    1048          105 :   if (!n || n->type != CJSON_INTEGER)
    1049            0 :     ccol__fatal_err("cjson_int_val: node is %s, expected CJSON_INTEGER",
    1050              :                     n ? cjson_type_str((cjson)n) : "NULL");
    1051          105 :   return n->value.integer;
    1052              : }
    1053              : 
    1054           51 : double cjson_double_val(cjson node) {
    1055           51 :   cjson_node *n = (cjson_node *)node;
    1056           51 :   if (!n || n->type != CJSON_FLOAT)
    1057            0 :     ccol__fatal_err("cjson_double_val: node is %s, expected CJSON_FLOAT",
    1058              :                     n ? cjson_type_str((cjson)n) : "NULL");
    1059           51 :   return n->value.number;
    1060              : }
    1061              : 
    1062           55 : const char *cjson_str_val(cjson node) {
    1063           55 :   cjson_node *n = (cjson_node *)node;
    1064           55 :   if (!n || n->type != CJSON_STRING)
    1065            0 :     ccol__fatal_err("cjson_str_val: node is %s, expected CJSON_STRING",
    1066              :                     n ? cjson_type_str((cjson)n) : "NULL");
    1067           55 :   return n->value.string;
    1068              : }
    1069              : 
    1070           46 : size_t cjson_list_size(cjson node) {
    1071           46 :   cjson_node *n = (cjson_node *)node;
    1072           46 :   if (!n || n->type != CJSON_LIST)
    1073            0 :     ccol__fatal_err("cjson_list_size: node is %s, expected CJSON_LIST",
    1074              :                     n ? cjson_type_str((cjson)n) : "NULL");
    1075           46 :   return list_len_of(n);
    1076              : }
    1077              : 
    1078          438 : size_t cjson_dictionary_size(cjson node) {
    1079          438 :   cjson_node *n = (cjson_node *)node;
    1080          438 :   if (!n || n->type != CJSON_DICTIONARY)
    1081            0 :     ccol__fatal_err(
    1082              :         "cjson_dictionary_size: node is %s, expected CJSON_DICTIONARY",
    1083              :         n ? cjson_type_str((cjson)n) : "NULL");
    1084          438 :   return dict_size_of(n);
    1085              : }
    1086              : 
    1087              : // Appends child to the list arr, which takes ownership on success; it's how a
    1088              : // caller builds a list. The ownership split of the header holds on every path:
    1089              : // ccol_invalid_args touches nothing, every other failure destroys child. The
    1090              : // refusals that leave child alone (already attached, child == arr) are decided
    1091              : // before the type check of arr, so passing one non-list handle as both
    1092              : // arguments can't free a node the caller still owns. A cycle check that runs
    1093              : // out of memory moves ownership like a failed insert, so ccol_not_enough_memory
    1094              : // means one thing. Sets child->attached.
    1095        42877 : ccol_retval cjson_list_push(cjson arr, cjson child) {
    1096        42877 :   if (!child) return ccol_invalid_args;
    1097        42876 :   cjson_node *c = (cjson_node *)child;
    1098              : 
    1099        42876 :   if (c->attached || (const void *)c == (const void *)arr) {
    1100              :     return ccol_invalid_args;
    1101              :   }
    1102              : 
    1103        42879 :   cjson_node *n = (arr && ((cjson_node *)arr)->type == CJSON_LIST)
    1104              :                       ? (cjson_node *)arr
    1105        42867 :                       : NULL;
    1106        42862 :   if (!n) {
    1107              :     return ccol_invalid_args;
    1108              :   }
    1109        42862 :   bool cycle_incomplete;
    1110        42862 :   if (node_reaches(c, (const cjson_node *)n, &cycle_incomplete)) {
    1111              :     return ccol_invalid_args;
    1112              :   }
    1113        42860 :   if (cycle_incomplete) {
    1114            0 :     cjson__destroy(child);
    1115            0 :     return ccol_not_enough_memory;
    1116              :   }
    1117        42860 :   cvec store = list_store(n);
    1118        42860 :   ccol_retval r = store ? cvector_push_back(store, &c) : ccol_not_enough_memory;
    1119        42859 :   if (r != ccol_success) {
    1120            1 :     cjson__destroy(child);
    1121            1 :     return r;
    1122              :   }
    1123        42859 :   c->attached = true;
    1124        42859 :   return ccol_success;
    1125              : }
    1126              : 
    1127              : // Gives element index of list arr as a borrowed reference, for a caller that
    1128              : // reads a list; NULL for a bad index, a NULL arr or a non-list.
    1129           45 : cjson cjson_list_get(cjson arr, size_t index) {
    1130           45 :   if (!arr) return NULL;
    1131           44 :   cjson_node *n = (cjson_node *)arr;
    1132           44 :   if (n->type != CJSON_LIST) return NULL;
    1133           43 :   return (cjson)list_child_at(n, index);
    1134              : }
    1135              : 
    1136              : // Destroys the old child of a dictionary slot and stores child there, for a set
    1137              : // or a parsed duplicate key that replaces a value. slot_vp is the slot that
    1138              : // ccol_chmap_insert_or_get_elem() found. Freeing the old child doesn't change
    1139              : // the map, so slot_vp stays valid. Sets child->attached.
    1140           16 : static void dict_slot_replace_child(const cmap_pair *slot_vp,
    1141              :                                     cjson_node *child) {
    1142           16 :   cjson_node *old_child = cjson_read_child(slot_vp->ptr);
    1143           16 :   cjson__destroy((cjson)old_child);
    1144           16 :   memcpy((void *)slot_vp->ptr, &child, sizeof(child));
    1145           16 :   child->attached = true;
    1146           16 : }
    1147              : 
    1148              : // Inserts key with child in obj, or replaces its value; it's how a caller fills
    1149              : // a dictionary. Ownership splits as in cjson_list_push(). Only the self-attach
    1150              : // is decided before the type check; the refusal of an attached child comes
    1151              : // after the lookup, because an attached child may be the value key already
    1152              : // holds, which is a no-op. A replace frees the old child and stores the new one
    1153              : // with nothing in between that can fail. Sets child->attached.
    1154         3067 : ccol_retval cjson_dictionary_set(cjson obj, const char *key, cjson child) {
    1155         3067 :   if (!child) return ccol_invalid_args;
    1156         3067 :   cjson_node *c = (cjson_node *)child;
    1157              : 
    1158         3067 :   if ((const void *)c == (const void *)obj) return ccol_invalid_args;
    1159              : 
    1160         3061 :   cjson_node *n = (obj && ((cjson_node *)obj)->type == CJSON_DICTIONARY)
    1161              :                       ? (cjson_node *)obj
    1162         3064 :                       : NULL;
    1163         3064 :   if (!n || !key || !utf8_cstr_is_valid(key)) {
    1164           10 :     return ccol_invalid_args;
    1165              :   }
    1166              : 
    1167         3054 :   cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
    1168              : 
    1169         3054 :   if (c->attached) {
    1170            5 :     cmap_pair held_vp;
    1171            9 :     if (dict_lookup(n, &kp, &held_vp) == ccol_success &&
    1172            3 :         cjson_read_child(held_vp.ptr) == c)
    1173              :       return ccol_success;
    1174            3 :     return ccol_invalid_args;
    1175              :   }
    1176              : 
    1177         3049 :   bool cycle_incomplete;
    1178         3049 :   if (node_reaches(c, (const cjson_node *)n, &cycle_incomplete)) {
    1179              :     return ccol_invalid_args;
    1180              :   }
    1181         3048 :   if (cycle_incomplete) {
    1182            0 :     cjson__destroy(child);
    1183            0 :     return ccol_not_enough_memory;
    1184              :   }
    1185              : 
    1186         3048 :   cmap_pair vp = {.ptr = &c, .size = sizeof(c)};
    1187         3048 :   cmap_pair old_vp;
    1188         3048 :   chmap store = dict_store(n);
    1189         6105 :   ccol_retval r = store
    1190         3047 :                       ? ccol_chmap_insert_or_get_elem(store, &kp, &vp, &old_vp)
    1191         3048 :                       : ccol_not_enough_memory;
    1192         3047 :   if (r == ccol_success) {
    1193         3038 :     c->attached = true;
    1194         3038 :     return ccol_success;
    1195              :   }
    1196           10 :   if (r == ccol_key_already_present) {
    1197            9 :     dict_slot_replace_child(&old_vp, c);
    1198            9 :     return ccol_success;
    1199              :   }
    1200            1 :   cjson__destroy((cjson)child);
    1201            1 :   return r;
    1202              : }
    1203              : 
    1204              : // Gives the value of key in obj as a borrowed reference, for a caller that
    1205              : // reads a dictionary; NULL for a missing key or bad arguments.
    1206           84 : cjson cjson_dictionary_get(cjson obj, const char *key) {
    1207           84 :   if (!obj || !key) return NULL;
    1208           82 :   cjson_node *n = (cjson_node *)obj;
    1209           82 :   if (n->type != CJSON_DICTIONARY) return NULL;
    1210           81 :   cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
    1211           81 :   cmap_pair vp;
    1212          161 :   if (dict_lookup(n, &kp, &vp) != ccol_success) return NULL;
    1213           77 :   return cjson_read_child(vp.ptr);
    1214              : }
    1215              : 
    1216              : // Removes and destroys element index of arr, for callers and for
    1217              : // cjson__remove(). The later elements move left, O(n) in the elements after
    1218              : // index. ccol_invalid_args for a NULL or non-list arr or a bad index.
    1219           12 : ccol_retval cjson_list_remove(cjson arr, size_t index) {
    1220           12 :   if (!arr) return ccol_invalid_args;
    1221           11 :   cjson_node *n = (cjson_node *)arr;
    1222           11 :   if (n->type != CJSON_LIST) return ccol_invalid_args;
    1223           10 :   size_t cnt = list_len_of(n);
    1224           10 :   if (index >= cnt) return ccol_invalid_args;
    1225              : 
    1226            7 :   cjson_node *child = *(cjson_node **)cvector_at(n->value.list, index);
    1227            7 :   cjson__destroy((cjson)child);
    1228              : 
    1229           14 :   for (size_t i = index; i + 1 < cnt; i++) {
    1230            7 :     cjson_node **dst = (cjson_node **)cvector_at(n->value.list, i);
    1231            7 :     cjson_node **src = (cjson_node **)cvector_at(n->value.list, i + 1);
    1232            7 :     *dst = *src;
    1233              :   }
    1234            7 :   cjson_node *tmp = NULL;
    1235            7 :   cvector_pop_back(n->value.list, &tmp);
    1236            7 :   return ccol_success;
    1237              : }
    1238              : 
    1239              : // Removes the entry of key from obj and destroys its value, for callers and for
    1240              : // cjson__remove(). It reads the child before the delete and frees it only
    1241              : // after, so the map never points at freed memory. ccol_invalid_args for bad
    1242              : // arguments, ccol_key_not_found when the key is absent.
    1243         1520 : ccol_retval cjson_dictionary_remove(cjson obj, const char *key) {
    1244         1520 :   if (!obj || !key) return ccol_invalid_args;
    1245         1518 :   cjson_node *n = (cjson_node *)obj;
    1246         1518 :   if (n->type != CJSON_DICTIONARY) return ccol_invalid_args;
    1247         1517 :   cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
    1248         1517 :   cmap_pair vp;
    1249         3032 :   if (dict_lookup(n, &kp, &vp) != ccol_success) return ccol_key_not_found;
    1250         1512 :   cjson_node *child = cjson_read_child(vp.ptr);
    1251         1512 :   ccol_retval r = chashmap_remove_elem(n->value.dictionary, &kp);
    1252         1512 :   if (r == ccol_success) cjson__destroy((cjson)child);
    1253              :   return r;
    1254              : }
    1255              : 
    1256              : // Steps the cursor it onto the member it holds, so a caller can walk a
    1257              : // dictionary in insertion order, and stores that member's successor. Gives
    1258              : // false, with key and value cleared, at the end. Because the successor is read
    1259              : // on each step, removing the current member leaves the cursor valid.
    1260           34 : bool cjson_dictionary_next(cjson_dictionary_iter *it) {
    1261           34 :   if (!it) return false;
    1262           33 :   const ccol_chmap_entry_ref *e = (const ccol_chmap_entry_ref *)it->cjson__next;
    1263           33 :   if (!e) {
    1264           12 :     it->key = NULL;
    1265           12 :     it->value = NULL;
    1266           12 :     return false;
    1267              :   }
    1268           21 :   const cmap_pair *kp, *vp;
    1269           21 :   it->cjson__next = ccol_chmap_entry_read(e, &kp, &vp);
    1270           21 :   it->key = (const char *)kp->ptr;
    1271           21 :   it->value = (cjson)cjson_read_child(vp->ptr);
    1272           21 :   return true;
    1273              : }
    1274              : 
    1275              : // Starts the cursor it on dict and steps onto the oldest member. Gives false
    1276              : // for an empty, NULL or non-dictionary dict.
    1277           12 : bool cjson_dictionary_first(cjson dict, cjson_dictionary_iter *it) {
    1278           12 :   if (!it) return false;
    1279           11 :   cjson_node *n = (cjson_node *)dict;
    1280           22 :   it->cjson__next =
    1281           11 :       (n && n->type == CJSON_DICTIONARY) ? dict_first_entry(n) : NULL;
    1282           11 :   return cjson_dictionary_next(it);
    1283              : }
    1284              : 
    1285              : // The deepest nesting cjson_clone() accepts, in containers. A tree from
    1286              : // cjson_list_push() and cjson_dictionary_set() can be of any depth; this has
    1287              : // the parser's value, so whatever parses can be cloned. The clone walks with a
    1288              : // heap stack, so the limit is a policy, not a stack bound.
    1289              : #define CJSON_CLONE_MAX_DEPTH 500
    1290              : 
    1291              : // One container on the explicit stack of clone_tree(). dst is the copy, already
    1292              : // attached to its parent; depth is its nesting level. taken counts the copied
    1293              : // elements of a list, and next is the next member of a dictionary to copy, in
    1294              : // insertion order.
    1295              : typedef struct {
    1296              :   cjson_node *src;
    1297              :   cjson_node *dst;
    1298              :   unsigned int depth;
    1299              :   size_t taken;
    1300              :   const ccol_chmap_entry_ref *next;
    1301              : } clone_frame;
    1302              : 
    1303              : // Pushes a frame onto the stack of clone_tree(), growing it like
    1304              : // serialize_stack_push() does. Gives false when the growth fails.
    1305         8218 : static bool clone_stack_push(clone_frame **frames, clone_frame *inline_frames,
    1306              :                              size_t inline_cap, size_t *cap, size_t *len,
    1307              :                              const clone_frame *frame) {
    1308         8218 :   if (*len == *cap) {
    1309           64 :     size_t new_cap = *cap * 2;
    1310           64 :     clone_frame *grown;
    1311           64 :     if (*frames == inline_frames) {
    1312           16 :       grown = ccol__default_mem_alloc(new_cap * sizeof(**frames));
    1313           16 :       if (!grown) return false;
    1314           16 :       memcpy(grown, inline_frames, inline_cap * sizeof(**frames));
    1315              :     } else {
    1316           48 :       grown = ccol__default_mem_realloc(*frames, new_cap * sizeof(**frames));
    1317           48 :       if (!grown) return false;
    1318              :     }
    1319           64 :     *frames = grown;
    1320           64 :     *cap = new_cap;
    1321              :   }
    1322         8218 :   (*frames)[(*len)++] = *frame;
    1323         8218 :   return true;
    1324              : }
    1325              : 
    1326              : // Copies one node without its children, a scalar whole and a container empty;
    1327              : // clone_tree() builds every node of the copy with it. Gives NULL when an
    1328              : // allocation fails. The source string is already valid UTF-8, so the copy
    1329              : // needs no check.
    1330         8843 : static cjson_node *clone_shallow(cjson_node *src) {
    1331         8843 :   ccol_memmgmt_procs *mp = src->m_procs;
    1332         8843 :   switch (src->type) {
    1333              :     case CJSON_NULL:
    1334            1 :       return (cjson_node *)cjson_create_null_interned(mp);
    1335            1 :     case CJSON_BOOL:
    1336            1 :       return (cjson_node *)cjson_create_bool_interned(src->value.boolean, mp);
    1337          610 :     case CJSON_INTEGER:
    1338          610 :       return (cjson_node *)cjson_create_int_interned(src->value.integer, mp);
    1339            0 :     case CJSON_FLOAT:
    1340            0 :       return (cjson_node *)cjson_create_double_interned(src->value.number, mp);
    1341           11 :     case CJSON_STRING: {
    1342           11 :       cjson_node *n = node_alloc(CJSON_STRING, mp);
    1343           11 :       if (!n) return NULL;
    1344           11 :       size_t slen = strlen(src->value.string);
    1345           11 :       n->value.string = ccol__mem_alloc(mp, slen + 1);
    1346           11 :       if (!n->value.string) {
    1347            0 :         node_free(n);
    1348            0 :         return NULL;
    1349              :       }
    1350           11 :       memcpy(n->value.string, src->value.string, slen + 1);
    1351           11 :       return n;
    1352              :     }
    1353              :     case CJSON_LIST:
    1354         4509 :       return (cjson_node *)cjson_create_list_interned(mp);
    1355              :     case CJSON_DICTIONARY:
    1356         3711 :       return (cjson_node *)cjson_create_dictionary_interned(mp);
    1357              :   }
    1358              :   return NULL;
    1359              : }
    1360              : 
    1361              : // Makes a deep copy of src with the same allocator, for cjson_clone(). Gives
    1362              : // NULL (after destroying the half-built copy) when an allocation fails or the
    1363              : // depth passes CJSON_CLONE_MAX_DEPTH. Each container is created empty, attached
    1364              : // to its parent and only then filled, which is what lets the walk be a loop
    1365              : // over an explicit stack. Children go straight into the store without the
    1366              : // checks of cjson_list_push() and cjson_dictionary_set(): The copy is new, and
    1367              : // each key comes from the source map, so it's unique and valid UTF-8. Members
    1368              : // keep their insertion order.
    1369          228 : static cjson_node *clone_tree(cjson_node *src) {
    1370          228 :   clone_frame inline_frames[32];
    1371          228 :   clone_frame *frames = inline_frames;
    1372          228 :   size_t cap = sizeof(inline_frames) / sizeof(inline_frames[0]);
    1373          228 :   size_t len = 0;
    1374              : 
    1375          228 :   cjson_node *root = NULL;
    1376          228 :   cjson_node *cur = src;
    1377          228 :   cjson_node *parent_dst = NULL;
    1378          228 :   const char *parent_key = NULL;
    1379          228 :   size_t parent_key_size = 0;
    1380          228 :   unsigned int cur_depth = 0;
    1381              : 
    1382         8622 :   for (;;) {
    1383         8850 :     if (cur_depth >= CJSON_CLONE_MAX_DEPTH &&
    1384           12 :         (cur->type == CJSON_LIST || cur->type == CJSON_DICTIONARY))
    1385            7 :       goto fail;
    1386              : 
    1387         8843 :     cjson_node *copy = (cjson_node *)clone_shallow(cur);
    1388         8843 :     if (!copy) goto fail;
    1389              : 
    1390         8838 :     if (!parent_dst) {
    1391              :       root = copy;
    1392         8612 :     } else if (parent_key) {
    1393         4103 :       cmap_pair kp = {.ptr = (void *)parent_key, .size = parent_key_size};
    1394         4103 :       cmap_pair vp = {.ptr = &copy, .size = sizeof(copy)};
    1395         4103 :       chmap store = dict_store(parent_dst);
    1396         4103 :       if (!store || chashmap_insert_elem(store, &kp, &vp) != ccol_success) {
    1397            4 :         cjson__destroy((cjson)copy);
    1398            4 :         goto fail;
    1399              :       }
    1400         4099 :       copy->attached = true;
    1401              :     } else {
    1402         4509 :       cvec store = list_store(parent_dst);
    1403         4509 :       if (!store || cvector_push_back(store, &copy) != ccol_success) {
    1404            0 :         cjson__destroy((cjson)copy);
    1405            0 :         goto fail;
    1406              :       }
    1407         4509 :       copy->attached = true;
    1408              :     }
    1409              : 
    1410         8834 :     if (cur->type == CJSON_LIST || cur->type == CJSON_DICTIONARY) {
    1411         8218 :       clone_frame f = {.src = cur,
    1412              :                        .dst = copy,
    1413              : 
    1414              :                        .depth = cur_depth,
    1415              :                        .taken = 0,
    1416              :                        .next = NULL};
    1417         8218 :       if (cur->type == CJSON_DICTIONARY) {
    1418         7415 :         f.next = dict_first_entry(cur);
    1419              :       }
    1420         8218 :       if (!clone_stack_push(&frames, inline_frames,
    1421              :                             sizeof(inline_frames) / sizeof(*inline_frames),
    1422              :                             &cap, &len, &f)) {
    1423            0 :         goto fail;
    1424              :       }
    1425              :     }
    1426              : 
    1427        13545 :     for (;;) {
    1428        13545 :       if (len == 0) goto done;
    1429        13333 :       clone_frame *f = &frames[len - 1];
    1430              : 
    1431        13333 :       if (f->src->type == CJSON_LIST) {
    1432        14040 :         if (f->taken < list_len_of(f->src)) {
    1433         4514 :           cur = *(cjson_node **)cvector_at(f->src->value.list, f->taken);
    1434         4514 :           f->taken++;
    1435         4514 :           parent_dst = f->dst;
    1436         4514 :           parent_key = NULL;
    1437         4514 :           cur_depth = f->depth + 1;
    1438         4514 :           break;
    1439              :         }
    1440         2507 :         len--;
    1441         2507 :         continue;
    1442              :       }
    1443              : 
    1444         6312 :       if (f->next) {
    1445         4108 :         const cmap_pair *kp, *vp;
    1446         4108 :         f->next = ccol_chmap_entry_read(f->next, &kp, &vp);
    1447         4108 :         cur = cjson_read_child(vp->ptr);
    1448         4108 :         parent_dst = f->dst;
    1449         4108 :         parent_key = (const char *)kp->ptr;
    1450         4108 :         parent_key_size = kp->size;
    1451         4108 :         cur_depth = f->depth + 1;
    1452         4108 :         break;
    1453              :       }
    1454         2204 :       len--;
    1455              :     }
    1456              :   }
    1457              : 
    1458           16 : fail:
    1459           16 :   if (frames != inline_frames) ccol__default_mem_free(frames);
    1460           16 :   cjson__destroy((cjson)root);
    1461           16 :   return NULL;
    1462              : 
    1463          212 : done:
    1464          212 :   if (frames != inline_frames) ccol__default_mem_free(frames);
    1465              :   return root;
    1466              : }
    1467              : 
    1468              : // Gives the caller a deep copy of node through clone_tree(), or NULL for a NULL
    1469              : // node or a failure.
    1470          229 : cjson cjson_clone(cjson node) {
    1471          229 :   if (!node) return NULL;
    1472          228 :   return (cjson)clone_tree((cjson_node *)node);
    1473              : }
    1474              : 
    1475              : // The state every parse function receives: The input and the current offset,
    1476              : // the message that parse_err() fills (meaningful only after a failure), and
    1477              : // the allocator for every node and string. The parser reads src directly, with
    1478              : // no token stream.
    1479              : typedef struct {
    1480              :   const char *src;
    1481              :   size_t pos;
    1482              :   size_t len;
    1483              :   char error[512];
    1484              :   ccol_memmgmt_procs *mp;
    1485              : } parse_ctx;
    1486              : 
    1487              : // The deepest nesting a parse accepts, in containers; one more container is a
    1488              : // parse error that names the limit. parse_value() walks with a heap stack, so
    1489              : // the limit doesn't depend on the native stack.
    1490              : #define CJSON_MAX_PARSE_DEPTH 500
    1491              : 
    1492              : static void parse_err(parse_ctx *ctx, const char *fmt, ...)
    1493              :     __attribute__((format(printf, 2, 3)));
    1494              : // Formats a parse error into ctx->error, replacing any earlier one; every
    1495              : // syntax error of the parser reports through it. The format attribute on the
    1496              : // declaration lets the compiler check every call site.
    1497         6164 : static void parse_err(parse_ctx *ctx, const char *fmt, ...) {
    1498         6164 :   va_list ap;
    1499         6164 :   va_start(ap, fmt);
    1500         6164 :   vsnprintf(ctx->error, sizeof(ctx->error), fmt, ap);
    1501         6164 :   va_end(ap);
    1502         6164 : }
    1503              : 
    1504              : // Tells whether an input byte may appear as it is in an error message. The
    1505              : // messages print any other byte as 0xNN, so they stay printable ASCII whatever
    1506              : // the input holds.
    1507         2369 : static bool parse_err_byte_is_printable(unsigned char b) {
    1508         2369 :   return b >= 0x20 && b <= 0x7E;
    1509              : }
    1510              : 
    1511              : // Moves ctx->pos past JSON whitespace (space, tab, CR, LF) between tokens.
    1512       892767 : static void skip_ws(parse_ctx *ctx) {
    1513       892912 :   while (ctx->pos < ctx->len) {
    1514       891110 :     char c = ctx->src[ctx->pos];
    1515       891110 :     if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
    1516          145 :       ctx->pos++;
    1517              :     else
    1518              :       break;
    1519              :   }
    1520       892767 : }
    1521              : 
    1522              : // Skips whitespace and stores the next byte in *out without consuming it, so
    1523              : // the parser can pick what comes next. Gives false at the end of the input.
    1524       557105 : static bool peek(parse_ctx *ctx, char *out) {
    1525       557105 :   skip_ws(ctx);
    1526       557106 :   if (ctx->pos >= ctx->len) return false;
    1527       556968 :   *out = ctx->src[ctx->pos];
    1528       556968 :   return true;
    1529              : }
    1530              : 
    1531              : // Consumes the next non-whitespace byte when it is expected (a ':' after a
    1532              : // key); otherwise reports an error and gives false.
    1533        66026 : static bool expect_char(parse_ctx *ctx, char expected) {
    1534        66026 :   skip_ws(ctx);
    1535        66026 :   if (ctx->pos >= ctx->len || ctx->src[ctx->pos] != expected) {
    1536          255 :     parse_err(ctx, "expected '%c' at position %zu", expected, ctx->pos);
    1537          255 :     return false;
    1538              :   }
    1539        65771 :   ctx->pos++;
    1540        65771 :   return true;
    1541              : }
    1542              : 
    1543              : // Parses the literal null into a node; NULL with an error otherwise.
    1544          471 : static cjson_node *parse_null(parse_ctx *ctx) {
    1545          471 :   if (ctx->pos + 4 > ctx->len || memcmp(ctx->src + ctx->pos, "null", 4) != 0) {
    1546          260 :     parse_err(ctx, "expected 'null' at position %zu", ctx->pos);
    1547          260 :     return NULL;
    1548              :   }
    1549          211 :   ctx->pos += 4;
    1550          211 :   return node_alloc(CJSON_NULL, ctx->mp);
    1551              : }
    1552              : 
    1553              : // Parses true or false into a node; NULL with an error otherwise.
    1554          479 : static cjson_node *parse_bool(parse_ctx *ctx) {
    1555          479 :   if (ctx->pos + 4 <= ctx->len && memcmp(ctx->src + ctx->pos, "true", 4) == 0) {
    1556          214 :     ctx->pos += 4;
    1557          214 :     cjson_node *n = node_alloc(CJSON_BOOL, ctx->mp);
    1558          214 :     if (n) n->value.boolean = true;
    1559          214 :     return n;
    1560              :   }
    1561          265 :   if (ctx->pos + 5 <= ctx->len &&
    1562            2 :       memcmp(ctx->src + ctx->pos, "false", 5) == 0) {
    1563            2 :     ctx->pos += 5;
    1564            2 :     cjson_node *n = node_alloc(CJSON_BOOL, ctx->mp);
    1565            2 :     if (n) n->value.boolean = false;
    1566            2 :     return n;
    1567              :   }
    1568          263 :   parse_err(ctx, "expected 'true' or 'false' at position %zu", ctx->pos);
    1569          263 :   return NULL;
    1570              : }
    1571              : 
    1572              : // Parses a number at ctx->pos into a node, with the grammar of RFC 8259 sec. 6
    1573              : // (no digits after a leading zero). An integer that fits a long long is a
    1574              : // CJSON_INTEGER; everything else, an overflowing integer included, is a
    1575              : // CJSON_FLOAT, and a value that would be infinite is refused. The token is
    1576              : // copied into a 360-byte stack buffer, enough for any real number, or into an
    1577              : // exact heap buffer for a longer (still valid) literal. NULL on an error.
    1578        40776 : static cjson_node *parse_number(parse_ctx *ctx) {
    1579        40776 :   size_t start = ctx->pos;
    1580        40776 :   bool is_float = false;
    1581              : 
    1582        40776 :   if (ctx->pos < ctx->len && ctx->src[ctx->pos] == '-') ctx->pos++;
    1583              : 
    1584        40776 :   if (ctx->pos >= ctx->len) {
    1585            5 :     parse_err(ctx, "unexpected end of number at position %zu", ctx->pos);
    1586            5 :     return NULL;
    1587              :   }
    1588              : 
    1589        40771 :   if (ctx->src[ctx->pos] == '0') {
    1590        35124 :     ctx->pos++;
    1591        35124 :     if (ctx->pos < ctx->len && ctx->src[ctx->pos] >= '0' &&
    1592              :         ctx->src[ctx->pos] <= '9') {
    1593            4 :       parse_err(ctx, "invalid leading zero in number at position %zu", start);
    1594            4 :       return NULL;
    1595              :     }
    1596         5647 :   } else if (ctx->src[ctx->pos] >= '1' && ctx->src[ctx->pos] <= '9') {
    1597        11737 :     while (ctx->pos < ctx->len && ctx->src[ctx->pos] >= '0' &&
    1598              :            ctx->src[ctx->pos] <= '9')
    1599         6336 :       ctx->pos++;
    1600              :   } else {
    1601          246 :     parse_err(ctx, "invalid number at position %zu", ctx->pos);
    1602          246 :     return NULL;
    1603              :   }
    1604              : 
    1605        40521 :   if (ctx->pos < ctx->len && ctx->src[ctx->pos] == '.') {
    1606          292 :     is_float = true;
    1607          292 :     ctx->pos++;
    1608          292 :     if (ctx->pos >= ctx->len || ctx->src[ctx->pos] < '0' ||
    1609              :         ctx->src[ctx->pos] > '9') {
    1610          248 :       parse_err(ctx, "expected digit after '.' at position %zu", ctx->pos);
    1611          248 :       return NULL;
    1612              :     }
    1613         1372 :     while (ctx->pos < ctx->len && ctx->src[ctx->pos] >= '0' &&
    1614              :            ctx->src[ctx->pos] <= '9')
    1615         1328 :       ctx->pos++;
    1616              :   }
    1617              : 
    1618        40273 :   if (ctx->pos < ctx->len &&
    1619        40181 :       (ctx->src[ctx->pos] == 'e' || ctx->src[ctx->pos] == 'E')) {
    1620          284 :     is_float = true;
    1621          284 :     ctx->pos++;
    1622          284 :     if (ctx->pos < ctx->len &&
    1623          281 :         (ctx->src[ctx->pos] == '+' || ctx->src[ctx->pos] == '-'))
    1624           24 :       ctx->pos++;
    1625          284 :     if (ctx->pos >= ctx->len || ctx->src[ctx->pos] < '0' ||
    1626              :         ctx->src[ctx->pos] > '9') {
    1627          251 :       parse_err(ctx, "expected digit in exponent at position %zu", ctx->pos);
    1628          251 :       return NULL;
    1629              :     }
    1630           90 :     while (ctx->pos < ctx->len && ctx->src[ctx->pos] >= '0' &&
    1631              :            ctx->src[ctx->pos] <= '9')
    1632           57 :       ctx->pos++;
    1633              :   }
    1634              : 
    1635        40022 :   size_t tok_len = ctx->pos - start;
    1636        40022 :   char stack_tok[360];
    1637        40022 :   char *tok = stack_tok;
    1638        40022 :   char *heap_tok = NULL;
    1639        40022 :   if (tok_len >= sizeof(stack_tok)) {
    1640            3 :     heap_tok = ccol__mem_alloc(ctx->mp, tok_len + 1);
    1641            3 :     if (!heap_tok) return NULL;
    1642              :     tok = heap_tok;
    1643              :   }
    1644        40022 :   memcpy(tok, ctx->src + start, tok_len);
    1645        40022 :   tok[tok_len] = '\0';
    1646              : 
    1647        40022 :   cjson_node *result = NULL;
    1648        40022 :   if (is_float) {
    1649           57 :     double dval = cjson_strtod_c(tok);
    1650           57 :     if (isinf(dval)) {
    1651            2 :       parse_err(ctx, "number out of range at position %zu", start);
    1652              :     } else {
    1653           55 :       cjson_node *n = node_alloc(CJSON_FLOAT, ctx->mp);
    1654           55 :       if (n) n->value.number = dval;
    1655              :       result = n;
    1656              :     }
    1657              :   } else {
    1658        39965 :     char *endp;
    1659        39965 :     errno = 0;
    1660        39965 :     long long ival = strtoll(tok, &endp, 10);
    1661        39965 :     if (*endp == '\0' && errno != ERANGE) {
    1662        39953 :       cjson_node *n = node_alloc(CJSON_INTEGER, ctx->mp);
    1663        39953 :       if (n) n->value.integer = ival;
    1664              :       result = n;
    1665              :     } else {
    1666           12 :       double dval = cjson_strtod_c(tok);
    1667           12 :       if (isinf(dval)) {
    1668            1 :         parse_err(ctx, "number out of range at position %zu", start);
    1669              :       } else {
    1670           11 :         cjson_node *n = node_alloc(CJSON_FLOAT, ctx->mp);
    1671           11 :         if (n) n->value.number = dval;
    1672              :         result = n;
    1673              :       }
    1674              :     }
    1675              :   }
    1676        40022 :   ccol__mem_free(ctx->mp, heap_tok);
    1677              :   return result;
    1678              : }
    1679              : 
    1680              : // Appends code point cp to sb as UTF-8, for a decoded \uXXXX escape.
    1681           92 : static void encode_utf8(sbuf *sb, uint32_t cp) {
    1682           92 :   char buf[4];
    1683           92 :   int n;
    1684           92 :   if (cp <= 0x7F) {
    1685           30 :     buf[0] = (char)cp;
    1686           30 :     n = 1;
    1687           62 :   } else if (cp <= 0x7FF) {
    1688           22 :     buf[0] = (char)(0xC0 | (cp >> 6));
    1689           22 :     buf[1] = (char)(0x80 | (cp & 0x3F));
    1690           22 :     n = 2;
    1691           40 :   } else if (cp <= 0xFFFF) {
    1692           36 :     buf[0] = (char)(0xE0 | (cp >> 12));
    1693           36 :     buf[1] = (char)(0x80 | ((cp >> 6) & 0x3F));
    1694           36 :     buf[2] = (char)(0x80 | (cp & 0x3F));
    1695           36 :     n = 3;
    1696              :   } else {
    1697            4 :     buf[0] = (char)(0xF0 | (cp >> 18));
    1698            4 :     buf[1] = (char)(0x80 | ((cp >> 12) & 0x3F));
    1699            4 :     buf[2] = (char)(0x80 | ((cp >> 6) & 0x3F));
    1700            4 :     buf[3] = (char)(0x80 | (cp & 0x3F));
    1701            4 :     n = 4;
    1702              :   }
    1703           92 :   sb_append(sb, buf, (size_t)n);
    1704           92 : }
    1705              : 
    1706              : // Reads the 4 hex digits of a \uXXXX escape into *out and moves past them;
    1707              : // reports an error and gives false for a short or bad escape.
    1708         1567 : static bool parse_hex4(parse_ctx *ctx, uint32_t *out) {
    1709         1567 :   if (ctx->pos + 4 > ctx->len) {
    1710            1 :     parse_err(ctx, "incomplete \\uXXXX escape at position %zu", ctx->pos);
    1711            1 :     return false;
    1712              :   }
    1713              :   uint32_t v = 0;
    1714         4551 :   for (int i = 0; i < 4; i++) {
    1715         4156 :     char c = ctx->src[ctx->pos + i];
    1716         4156 :     uint32_t d;
    1717         4156 :     if (c >= '0' && c <= '9')
    1718         2621 :       d = (uint32_t)(c - '0');
    1719         1535 :     else if (c >= 'a' && c <= 'f')
    1720          295 :       d = (uint32_t)(c - 'a' + 10);
    1721         1240 :     else if (c >= 'A' && c <= 'F')
    1722           69 :       d = (uint32_t)(c - 'A' + 10);
    1723              :     else {
    1724         1171 :       if (parse_err_byte_is_printable((unsigned char)c))
    1725          365 :         parse_err(ctx, "invalid hex digit '%c' in \\uXXXX at position %zu", c,
    1726              :                   ctx->pos + i);
    1727              :       else
    1728          806 :         parse_err(ctx,
    1729              :                   "invalid hex digit byte 0x%02X in \\uXXXX at position %zu",
    1730              :                   (unsigned char)c, ctx->pos + i);
    1731         1171 :       return false;
    1732              :     }
    1733         2985 :     v = (v << 4) | d;
    1734              :   }
    1735          395 :   ctx->pos += 4;
    1736          395 :   *out = v;
    1737          395 :   return true;
    1738              : }
    1739              : 
    1740              : // Checks that src[start..end) of a string literal is well-formed UTF-8, so the
    1741              : // parser never stores ill-formed bytes. On a defect it reports the bytes and
    1742              : // their position and gives false.
    1743         1038 : static bool string_bytes_are_utf8(parse_ctx *ctx, size_t start, size_t end) {
    1744         2076 :   size_t bad =
    1745         1038 :       start + ccol_utf8_first_ill_formed(ctx->src + start, end - start);
    1746         1038 :   if (bad == end) return true;
    1747         1034 :   char detail[96];
    1748         1034 :   const char *what = ccol_utf8_describe_ill_formed(
    1749              :       (const unsigned char *)ctx->src, ctx->len, bad, detail, sizeof(detail));
    1750         1034 :   parse_err(ctx, "invalid UTF-8 in string at position %zu: %s (%s)", bad, what,
    1751              :             detail);
    1752         1034 :   return false;
    1753              : }
    1754              : 
    1755              : // Makes the first pass over a string literal, so the common literal can be
    1756              : // copied without decoding. ctx->pos must be at the opening quote; it moves past
    1757              : // it. *end gets the position of the closing quote, *need_slow_out whether the
    1758              : // literal holds an escape or a control byte, and *has_non_ascii_out whether it
    1759              : // holds a byte above 0x7F (an ASCII literal then skips the UTF-8 check). An
    1760              : // unterminated literal is an error.
    1761        79264 : static bool parse_string_scan(parse_ctx *ctx, size_t *end, bool *need_slow_out,
    1762              :                               bool *has_non_ascii_out) {
    1763        79264 :   if (ctx->pos >= ctx->len || ctx->src[ctx->pos] != '"') {
    1764            1 :     parse_err(ctx, "expected '\"' at position %zu", ctx->pos);
    1765            1 :     return false;
    1766              :   }
    1767        79263 :   ctx->pos++;
    1768              : 
    1769        79263 :   size_t scan = ctx->pos;
    1770        79263 :   bool need_slow = false;
    1771        79263 :   bool has_non_ascii = false;
    1772       119959 :   while (scan < ctx->len) {
    1773       119694 :     unsigned char sc = (unsigned char)ctx->src[scan];
    1774       119694 :     if (sc == '"') break;
    1775        40696 :     if (sc == '\\') {
    1776         1980 :       need_slow = true;
    1777         1980 :       scan += 2;
    1778         1980 :       continue;
    1779              :     }
    1780        38716 :     if (sc < 0x20) {
    1781              :       need_slow = true;
    1782        38430 :     } else if (sc >= 0x80) {
    1783         2354 :       has_non_ascii = true;
    1784              :     }
    1785        38716 :     scan++;
    1786              :   }
    1787              : 
    1788        79263 :   if (scan >= ctx->len) {
    1789          266 :     parse_err(ctx, "unterminated string starting before position %zu",
    1790              :               ctx->pos - 1);
    1791          266 :     return false;
    1792              :   }
    1793        78997 :   *end = scan;
    1794        78997 :   *need_slow_out = need_slow;
    1795        78997 :   *has_non_ascii_out = has_non_ascii;
    1796        78997 :   return true;
    1797              : }
    1798              : 
    1799              : // Decodes a string literal that holds an escape or a control byte, from
    1800              : // ctx->pos up to the closing quote at scan, into a heap string (ctx->mp) in
    1801              : // *out with its length in *out_len. Plain runs are copied in one go and checked
    1802              : // for UTF-8 in order, so the first defect is the one reported. A surrogate
    1803              : // escape that isn't half of a high-low pair, \u0000 (a C string can't hold it),
    1804              : // an unknown escape and a raw control byte are errors.
    1805         1793 : static bool parse_string_slow(parse_ctx *ctx, size_t scan, bool has_non_ascii,
    1806              :                               char **out, size_t *out_len) {
    1807         1793 :   sbuf sb;
    1808         1793 :   sb_init_hint(&sb, ctx->mp, scan - ctx->pos);
    1809              : 
    1810         3695 :   while (ctx->pos < ctx->len) {
    1811              :     size_t chunk_start = ctx->pos;
    1812         2283 :     while (ctx->pos < ctx->len) {
    1813         2283 :       unsigned char c2 = (unsigned char)ctx->src[ctx->pos];
    1814         2283 :       if (c2 == '"' || c2 == '\\' || c2 < 0x20) break;
    1815          381 :       ctx->pos++;
    1816              :     }
    1817         1902 :     if (ctx->pos > chunk_start) {
    1818          210 :       if (has_non_ascii && !string_bytes_are_utf8(ctx, chunk_start, ctx->pos)) {
    1819          194 :         ccol__mem_free(sb.m_procs, sb.buf);
    1820          194 :         return false;
    1821              :       }
    1822           16 :       sb_append(&sb, ctx->src + chunk_start, ctx->pos - chunk_start);
    1823              :     }
    1824              : 
    1825         1708 :     if (ctx->pos >= ctx->len) break;
    1826         1708 :     char c = ctx->src[ctx->pos];
    1827              : 
    1828         1708 :     if (c == '"') {
    1829          102 :       ctx->pos++;
    1830          102 :       if (sb.oom) {
    1831            0 :         ccol__mem_free(sb.m_procs, sb.buf);
    1832            0 :         return false;
    1833              :       }
    1834          102 :       *out = sb.buf;
    1835          102 :       *out_len = sb.len;
    1836          102 :       return true;
    1837              :     }
    1838              : 
    1839         1606 :     if (c == '\\') {
    1840         1574 :       ctx->pos++;
    1841         1574 :       if (ctx->pos >= ctx->len) break;
    1842         1574 :       char esc = ctx->src[ctx->pos++];
    1843         1574 :       switch (esc) {
    1844              :         case '"':
    1845            2 :           sb_append_c(&sb, '"');
    1846            2 :           break;
    1847              :         case '\\':
    1848            3 :           sb_append_c(&sb, '\\');
    1849            3 :           break;
    1850              :         case '/':
    1851            1 :           sb_append_c(&sb, '/');
    1852            1 :           break;
    1853              :         case 'b':
    1854            1 :           sb_append_c(&sb, '\b');
    1855            1 :           break;
    1856              :         case 'f':
    1857            1 :           sb_append_c(&sb, '\f');
    1858            1 :           break;
    1859              :         case 'n':
    1860            4 :           sb_append_c(&sb, '\n');
    1861            4 :           break;
    1862              :         case 'r':
    1863            1 :           sb_append_c(&sb, '\r');
    1864            1 :           break;
    1865              :         case 't':
    1866            4 :           sb_append_c(&sb, '\t');
    1867            4 :           break;
    1868         1304 :         case 'u': {
    1869         1304 :           uint32_t cp;
    1870         1304 :           if (!parse_hex4(ctx, &cp)) {
    1871          938 :             ccol__mem_free(sb.m_procs, sb.buf);
    1872         1212 :             return false;
    1873              :           }
    1874          366 :           size_t esc_pos = ctx->pos - 6;
    1875          366 :           if (cp >= 0xD800 && cp <= 0xDBFF) {
    1876          268 :             uint32_t low = 0;
    1877          268 :             if (ctx->pos + 1 < ctx->len && ctx->src[ctx->pos] == '\\' &&
    1878          264 :                 ctx->src[ctx->pos + 1] == 'u') {
    1879          263 :               ctx->pos += 2;
    1880          263 :               if (!parse_hex4(ctx, &low)) {
    1881          234 :                 ccol__mem_free(sb.m_procs, sb.buf);
    1882          264 :                 return false;
    1883              :               }
    1884              :             }
    1885           34 :             if (low < 0xDC00 || low > 0xDFFF) {
    1886           30 :               parse_err(ctx,
    1887              :                         "high surrogate escape \\u%04X at position %zu is "
    1888              :                         "not followed by a low surrogate escape",
    1889              :                         (unsigned)cp, esc_pos);
    1890           30 :               ccol__mem_free(sb.m_procs, sb.buf);
    1891           30 :               return false;
    1892              :             }
    1893            4 :             cp = 0x10000u + ((cp - 0xD800u) << 10) + (low - 0xDC00u);
    1894           98 :           } else if (cp >= 0xDC00 && cp <= 0xDFFF) {
    1895            4 :             parse_err(ctx,
    1896              :                       "low surrogate escape \\u%04X at position %zu does not "
    1897              :                       "follow a high surrogate escape",
    1898              :                       (unsigned)cp, esc_pos);
    1899            4 :             ccol__mem_free(sb.m_procs, sb.buf);
    1900            4 :             return false;
    1901              :           }
    1902           98 :           if (cp == 0) {
    1903            6 :             parse_err(ctx, "\\u0000 not supported at position %zu", esc_pos);
    1904            6 :             ccol__mem_free(sb.m_procs, sb.buf);
    1905            6 :             return false;
    1906              :           }
    1907           92 :           encode_utf8(&sb, cp);
    1908           92 :           break;
    1909              :         }
    1910          253 :         default:
    1911          253 :           if (parse_err_byte_is_printable((unsigned char)esc))
    1912           91 :             parse_err(ctx, "unknown escape '\\%c' at position %zu", esc,
    1913              :                       ctx->pos - 1);
    1914              :           else
    1915          162 :             parse_err(ctx,
    1916              :                       "unknown escape: '\\' followed by byte 0x%02X at "
    1917              :                       "position %zu",
    1918              :                       (unsigned char)esc, ctx->pos - 1);
    1919          253 :           ccol__mem_free(sb.m_procs, sb.buf);
    1920          253 :           return false;
    1921              :       }
    1922              :     } else {
    1923           32 :       parse_err(ctx,
    1924              :                 "unescaped control character 0x%02x in string at position %zu",
    1925           32 :                 (unsigned char)c, ctx->pos);
    1926           32 :       ccol__mem_free(sb.m_procs, sb.buf);
    1927           32 :       return false;
    1928              :     }
    1929              :   }
    1930              : 
    1931            0 :   parse_err(ctx, "unterminated string starting before position %zu", ctx->pos);
    1932            0 :   ccol__mem_free(sb.m_procs, sb.buf);
    1933              :   return false;
    1934              : }
    1935              : 
    1936              : // Parses a string literal into a heap string (ctx->mp) in *out, for string
    1937              : // values. Without escapes or control bytes the string is its raw bytes, so one
    1938              : // UTF-8 check, one allocation and one memcpy are enough.
    1939        12848 : static bool parse_string_raw(parse_ctx *ctx, char **out) {
    1940        12848 :   *out = NULL;
    1941        12848 :   size_t scan;
    1942        12848 :   bool need_slow, has_non_ascii;
    1943        12848 :   if (!parse_string_scan(ctx, &scan, &need_slow, &has_non_ascii)) return false;
    1944              : 
    1945        12584 :   if (!need_slow) {
    1946        10956 :     size_t slen = scan - ctx->pos;
    1947        10956 :     if (has_non_ascii && !string_bytes_are_utf8(ctx, ctx->pos, scan))
    1948              :       return false;
    1949        10341 :     char *s = ccol__mem_alloc(ctx->mp, slen + 1);
    1950        10341 :     if (!s) return false;
    1951        10341 :     memcpy(s, ctx->src + ctx->pos, slen);
    1952        10341 :     s[slen] = '\0';
    1953        10341 :     ctx->pos = scan + 1;
    1954        10341 :     *out = s;
    1955        10341 :     return true;
    1956              :   }
    1957              : 
    1958         1628 :   size_t slen;
    1959         1628 :   return parse_string_slow(ctx, scan, has_non_ascii, out, &slen);
    1960              : }
    1961              : 
    1962              : // The keys of the dictionaries that parse_value() has open, back to back, each
    1963              : // with its '\0'. A key lives only while its value is parsed and nested values
    1964              : // end first, so keys come and go in LIFO order. The buffer starts inline on
    1965              : // the stack and moves to ctx->mp's heap, doubling, only for a longer total.
    1966              : #define CJSON_PARSE_KEY_INLINE 256
    1967              : typedef struct {
    1968              :   char *buf;
    1969              :   size_t len;
    1970              :   size_t cap;
    1971              :   char inline_buf[CJSON_PARSE_KEY_INLINE];
    1972              : } parse_keys;
    1973              : 
    1974              : // Makes room for n more bytes in the key buffer, moving it to the heap the
    1975              : // first time it outgrows the inline array. Gives false when that fails.
    1976        66026 : static bool parse_keys_reserve(parse_ctx *ctx, parse_keys *keys, size_t n) {
    1977        66026 :   if (n <= keys->cap - keys->len) return true;
    1978           29 :   if (n > SIZE_MAX / 2 - keys->len) return false;
    1979           29 :   size_t new_cap = keys->cap * 2;
    1980           29 :   if (new_cap < keys->len + n) new_cap = keys->len + n;
    1981           29 :   char *grown;
    1982           29 :   if (keys->buf == keys->inline_buf) {
    1983           16 :     grown = ccol__mem_alloc(ctx->mp, new_cap);
    1984           16 :     if (!grown) return false;
    1985           16 :     memcpy(grown, keys->inline_buf, keys->len);
    1986              :   } else {
    1987           13 :     grown = ccol__mem_realloc(ctx->mp, keys->buf, new_cap);
    1988           13 :     if (!grown) return false;
    1989              :   }
    1990           29 :   keys->buf = grown;
    1991           29 :   keys->cap = new_cap;
    1992           29 :   return true;
    1993              : }
    1994              : 
    1995              : // Parses a dictionary key and pushes it, '\0' included, onto the key buffer, so
    1996              : // a key costs no allocation of its own. *off gets its offset and *klen its
    1997              : // length. A key without escapes is copied straight from the input; one with
    1998              : // escapes is decoded on the heap first.
    1999        66416 : static bool parse_key(parse_ctx *ctx, parse_keys *keys, size_t *off,
    2000              :                       size_t *klen) {
    2001        66416 :   size_t scan;
    2002        66416 :   bool need_slow, has_non_ascii;
    2003        66416 :   if (!parse_string_scan(ctx, &scan, &need_slow, &has_non_ascii)) return false;
    2004              : 
    2005        66413 :   const char *bytes;
    2006        66413 :   size_t slen;
    2007        66413 :   char *decoded = NULL;
    2008        66413 :   if (!need_slow) {
    2009        66248 :     slen = scan - ctx->pos;
    2010        66248 :     if (has_non_ascii && !string_bytes_are_utf8(ctx, ctx->pos, scan))
    2011              :       return false;
    2012        66023 :     bytes = ctx->src + ctx->pos;
    2013              :   } else {
    2014          165 :     if (!parse_string_slow(ctx, scan, has_non_ascii, &decoded, &slen))
    2015              :       return false;
    2016            3 :     bytes = decoded;
    2017              :   }
    2018        66026 :   bool ok = parse_keys_reserve(ctx, keys, slen + 1);
    2019        66026 :   if (ok) {
    2020        66026 :     memcpy(keys->buf + keys->len, bytes, slen);
    2021        66026 :     keys->buf[keys->len + slen] = '\0';
    2022        66026 :     *off = keys->len;
    2023        66026 :     *klen = slen;
    2024        66026 :     keys->len += slen + 1;
    2025              :   }
    2026        66026 :   if (decoded) {
    2027            3 :     ccol__mem_free(ctx->mp, decoded);
    2028              :   } else {
    2029        66023 :     ctx->pos = scan + 1;
    2030              :   }
    2031              :   return ok;
    2032              : }
    2033              : 
    2034              : // Parses a string literal into a CJSON_STRING node that owns it, for a string
    2035              : // value; NULL on an error.
    2036        12848 : static cjson_node *parse_string(parse_ctx *ctx) {
    2037        12848 :   char *s = NULL;
    2038        12848 :   if (!parse_string_raw(ctx, &s)) return NULL;
    2039        10440 :   cjson_node *n = node_alloc(CJSON_STRING, ctx->mp);
    2040        10440 :   if (!n) {
    2041            0 :     ccol__mem_free(ctx->mp, s);
    2042            0 :     return NULL;
    2043              :   }
    2044        10440 :   n->value.string = s;
    2045        10440 :   return n;
    2046              : }
    2047              : 
    2048              : // One open '[' or '{' on the explicit stack of parse_value(). key_off and
    2049              : // key_len locate, in the key buffer, the key whose value is being read.
    2050              : // started tells "a value may follow the bracket" apart from "a ',' must come
    2051              : // first". A recursive descent would let the sender of a document pick the
    2052              : // stack depth, which crashes a small thread stack long before the depth cap.
    2053              : typedef struct {
    2054              :   cjson_node *node;
    2055              :   size_t key_off;
    2056              :   size_t key_len;
    2057              :   bool is_dict;
    2058              :   bool started;
    2059              : } parse_frame;
    2060              : 
    2061              : // Pushes a frame onto the stack of parse_value(), growing it like
    2062              : // serialize_stack_push() does. Gives false when the growth fails.
    2063       153335 : static bool parse_stack_push(parse_frame **frames, parse_frame *inline_frames,
    2064              :                              size_t inline_cap, size_t *cap, size_t *len,
    2065              :                              const parse_frame *frame) {
    2066       153335 :   if (*len == *cap) {
    2067          105 :     size_t new_cap = *cap * 2;
    2068          105 :     parse_frame *grown;
    2069          105 :     if (*frames == inline_frames) {
    2070           27 :       grown = ccol__default_mem_alloc(new_cap * sizeof(**frames));
    2071           27 :       if (!grown) return false;
    2072           27 :       memcpy(grown, inline_frames, inline_cap * sizeof(**frames));
    2073              :     } else {
    2074           78 :       grown = ccol__default_mem_realloc(*frames, new_cap * sizeof(**frames));
    2075           78 :       if (!grown) return false;
    2076              :     }
    2077          105 :     *frames = grown;
    2078          105 :     *cap = new_cap;
    2079              :   }
    2080       153335 :   (*frames)[(*len)++] = *frame;
    2081       153335 :   return true;
    2082              : }
    2083              : 
    2084              : // Parses a value that isn't a container, picking the sub-parser from its first
    2085              : // byte c (which peek() already found); parse_value() takes containers itself.
    2086        55519 : static cjson_node *parse_scalar_value(parse_ctx *ctx, char c) {
    2087        55519 :   switch (c) {
    2088          471 :     case 'n':
    2089          471 :       return parse_null(ctx);
    2090          479 :     case 't':
    2091              :     case 'f':
    2092          479 :       return parse_bool(ctx);
    2093        12848 :     case '"':
    2094        12848 :       return parse_string(ctx);
    2095        40776 :     case '-':
    2096              :     case '0':
    2097              :     case '1':
    2098              :     case '2':
    2099              :     case '3':
    2100              :     case '4':
    2101              :     case '5':
    2102              :     case '6':
    2103              :     case '7':
    2104              :     case '8':
    2105              :     case '9':
    2106        40776 :       return parse_number(ctx);
    2107          945 :     default:
    2108          945 :       if (parse_err_byte_is_printable((unsigned char)c))
    2109          310 :         parse_err(ctx, "unexpected character '%c' at position %zu", c,
    2110              :                   ctx->pos);
    2111              :       else
    2112          635 :         parse_err(ctx, "unexpected byte 0x%02X at position %zu",
    2113              :                   (unsigned char)c, ctx->pos);
    2114              :       return NULL;
    2115              :   }
    2116              : }
    2117              : 
    2118              : // Parses one complete value and everything inside it, for parse_common().
    2119              : // Gives the root, or NULL with ctx->error set and every node built so far
    2120              : // freed. It walks with an explicit stack in four steps: Parse a value, hand a
    2121              : // complete value to the innermost open container, decide what comes next in
    2122              : // that container, and read a key. A container goes to its parent only after
    2123              : // its closing bracket, so on failure every frame still owns its container and
    2124              : // each one is destroyed. A repeated key keeps its first place and the last
    2125              : // value (RFC 8259 sec. 4 allows it).
    2126         8062 : static cjson_node *parse_value(parse_ctx *ctx) {
    2127         8062 :   parse_frame inline_frames[32];
    2128         8062 :   parse_frame *frames = inline_frames;
    2129         8062 :   size_t cap = sizeof(inline_frames) / sizeof(inline_frames[0]);
    2130         8062 :   size_t len = 0;
    2131         8062 :   cjson_node *pending = NULL;
    2132         8062 :   char c;
    2133         8062 :   parse_keys keys;
    2134         8062 :   keys.buf = keys.inline_buf;
    2135         8062 :   keys.len = 0;
    2136         8062 :   keys.cap = sizeof(keys.inline_buf);
    2137              : 
    2138              : value_step:
    2139       417887 :   if (!peek(ctx, &c)) {
    2140           71 :     parse_err(ctx, "unexpected end of input at position %zu", ctx->pos);
    2141           71 :     goto fail;
    2142              :   }
    2143       208873 :   if (c == '[' || c == '{') {
    2144       153355 :     if (len >= CJSON_MAX_PARSE_DEPTH) {
    2145            9 :       parse_err(ctx, "maximum nesting depth (%u) exceeded at position %zu",
    2146              :                 CJSON_MAX_PARSE_DEPTH, ctx->pos);
    2147           20 :       goto fail;
    2148              :     }
    2149       153346 :     parse_frame f = {.node = NULL,
    2150              :                      .key_off = 0,
    2151              :                      .key_len = 0,
    2152              :                      .is_dict = (c == '{'),
    2153              :                      .started = false};
    2154       153346 :     ctx->pos++;
    2155        77503 :     f.node = f.is_dict ? (cjson_node *)cjson_create_dictionary_interned(ctx->mp)
    2156       153346 :                        : (cjson_node *)cjson_create_list_interned(ctx->mp);
    2157       153346 :     if (!f.node) goto fail;
    2158       153335 :     if (!parse_stack_push(&frames, inline_frames,
    2159              :                           sizeof(inline_frames) / sizeof(*inline_frames), &cap,
    2160              :                           &len, &f)) {
    2161            0 :       cjson__destroy((cjson)f.node);
    2162            0 :       goto fail;
    2163              :     }
    2164       153335 :     goto next_step;
    2165              :   }
    2166        55518 :   pending = parse_scalar_value(ctx, c);
    2167        55519 :   if (!pending) goto fail;
    2168              : 
    2169        50876 : deliver_step:
    2170       196705 :   if (len == 0) goto done;
    2171              :   {
    2172       194852 :     parse_frame *f = &frames[len - 1];
    2173       194852 :     if (f->is_dict) {
    2174        63064 :       cmap_pair kp = {.ptr = keys.buf + f->key_off, .size = f->key_len + 1};
    2175              : 
    2176        63064 :       cmap_pair vp = {.ptr = &pending, .size = sizeof(pending)};
    2177        63064 :       cmap_pair existing_vp;
    2178        63064 :       chmap store = dict_store(f->node);
    2179       126128 :       ccol_retval r =
    2180        63055 :           store ? ccol_chmap_insert_or_get_elem(store, &kp, &vp, &existing_vp)
    2181        63064 :                 : ccol_not_enough_memory;
    2182        63064 :       keys.len = f->key_off;
    2183        63064 :       if (r == ccol_key_already_present) {
    2184            7 :         dict_slot_replace_child(&existing_vp, pending);
    2185        63057 :       } else if (r != ccol_success) {
    2186           20 :         cjson__destroy((cjson)pending);
    2187           20 :         goto fail;
    2188              :       } else {
    2189        63037 :         pending->attached = true;
    2190              :       }
    2191              :     } else {
    2192       131788 :       cvec store = list_store(f->node);
    2193       131788 :       if (!store || cvector_push_back(store, &pending) != ccol_success) {
    2194            4 :         cjson__destroy((cjson)pending);
    2195            4 :         goto fail;
    2196              :       }
    2197       131783 :       pending->attached = true;
    2198              :     }
    2199              :   }
    2200              : 
    2201       348162 : next_step: {
    2202       348162 :   parse_frame *f = &frames[len - 1];
    2203       696324 :   if (!peek(ctx, &c)) {
    2204           64 :     if (f->is_dict)
    2205           19 :       parse_err(ctx, "unterminated dictionary");
    2206              :     else
    2207           45 :       parse_err(ctx, "unterminated list");
    2208           64 :     goto fail;
    2209              :   }
    2210       555677 :   if (c == (f->is_dict ? '}' : ']')) {
    2211       145829 :     ctx->pos++;
    2212       145829 :     pending = f->node;
    2213       145829 :     len--;
    2214       145829 :     goto deliver_step;
    2215              :   }
    2216       202269 :   if (f->started) {
    2217        77975 :     if (c != ',') {
    2218          238 :       if (f->is_dict)
    2219            1 :         parse_err(ctx, "expected ',' or '}' in dictionary at position %zu",
    2220              :                   ctx->pos);
    2221              :       else
    2222          237 :         parse_err(ctx, "expected ',' or ']' in list at position %zu", ctx->pos);
    2223          238 :       goto fail;
    2224              :     }
    2225        77737 :     ctx->pos++;
    2226              :   }
    2227       202031 :   f->started = true;
    2228       202031 :   if (!f->is_dict) {
    2229       135110 :     skip_ws(ctx);
    2230       135110 :     goto value_step;
    2231              :   }
    2232        66921 :   goto key_step;
    2233              : }
    2234              : 
    2235        66921 : key_step: {
    2236        66921 :   parse_frame *f = &frames[len - 1];
    2237        66921 :   skip_ws(ctx);
    2238        66921 :   if (ctx->pos >= ctx->len || ctx->src[ctx->pos] != '"') {
    2239          505 :     parse_err(ctx, "expected string key at position %zu", ctx->pos);
    2240          505 :     goto fail;
    2241              :   }
    2242        66416 :   if (!parse_key(ctx, &keys, &f->key_off, &f->key_len)) goto fail;
    2243        66026 :   if (!expect_char(ctx, ':')) goto fail;
    2244        65771 :   skip_ws(ctx);
    2245        65771 :   goto value_step;
    2246              : }
    2247              : 
    2248              : fail:
    2249        13715 :   for (size_t i = 0; i < len; i++) {
    2250         7506 :     cjson__destroy((cjson)frames[i].node);
    2251              :   }
    2252         6209 :   pending = NULL;
    2253              : 
    2254         8062 : done:
    2255         8062 :   if (frames != inline_frames) ccol__default_mem_free(frames);
    2256         8062 :   if (keys.buf != keys.inline_buf) ccol__mem_free(ctx->mp, keys.buf);
    2257         8062 :   return pending;
    2258              : }
    2259              : 
    2260              : // The per-thread buffer behind err_str. The message names a position, so it
    2261              : // can't be a literal, and a heap string the caller frees would give err_str a
    2262              : // rule opposite to every other module's. So the library owns it, and it lives
    2263              : // until the next failing parse on the same thread. The buffer is on the heap,
    2264              : // allocated by the thread's first failing parse and freed by the thread-exit
    2265              : // drain; a thread-local array would take room in the TLS block that dlopen()
    2266              : // must fit. 512 is the size of parse_ctx.error.
    2267              : #define CJSON_ERR_BUF_LEN 512
    2268              : // The message a failed parse reports when the thread can't keep a buffer.
    2269              : static const char cjson_err_unstored[] =
    2270              :     "parse failed; the error message could not be stored";
    2271              : 
    2272              : // Copies msg into this thread's message buffer and points *err_str at it, so a
    2273              : // failed parse can hand out a message the caller never frees. Does nothing for
    2274              : // a NULL err_str. It allocates the buffer on first use and arms the pool key,
    2275              : // whose drain frees it at thread exit; a thread whose key can't be armed keeps
    2276              : // no buffer and gets cjson_err_unstored. Changes cjson_err_buf (or the thread's
    2277              : // block).
    2278         5730 : static void cjson_report_err(char **err_str, const char *msg) {
    2279         5730 :   if (!err_str) return;
    2280              : #if defined(CCOL__EMULATE_DARWIN_TLS)
    2281              :   ccol__call_once(pool_key_once, do_pool_key_init);
    2282              :   cjson_tls *t = cjson_tls_get();
    2283              :   if (t && !t->err_buf) t->err_buf = malloc(CJSON_ERR_BUF_LEN);
    2284              :   if (!t || !t->err_buf) {
    2285              :     *err_str = (char *)cjson_err_unstored;
    2286              :     return;
    2287              :   }
    2288              :   snprintf(t->err_buf, CJSON_ERR_BUF_LEN, "%s", msg);
    2289              :   *err_str = t->err_buf;
    2290              : #else
    2291         5729 :   if (!cjson_err_buf) {
    2292           52 :     char *buf = malloc(CJSON_ERR_BUF_LEN);
    2293           52 :     if (!buf) {
    2294            0 :       *err_str = (char *)cjson_err_unstored;
    2295            0 :       return;
    2296              :     }
    2297           52 :     ccol__call_once(pool_key_once, do_pool_key_init);
    2298           52 :     pool_key_arm();
    2299           52 :     if (!pool_key_armed) {
    2300           51 :       free(buf);
    2301           51 :       *err_str = (char *)cjson_err_unstored;
    2302           51 :       return;
    2303              :     }
    2304            1 :     cjson_err_buf = buf;
    2305              :   }
    2306         5678 :   snprintf(cjson_err_buf, CJSON_ERR_BUF_LEN, "%s", msg);
    2307         5678 :   *err_str = cjson_err_buf;
    2308              : #endif
    2309              : }
    2310              : 
    2311              : // Parses len bytes of src with allocator mp; both public parse functions share
    2312              : // it. It interns mp and refuses anything but whitespace after the root value.
    2313              : // Gives the root, or NULL. On success *err_str becomes NULL; on failure it
    2314              : // points at the per-thread message of cjson_report_err(). Every syntax error
    2315              : // sets its own message, so an empty ctx.error can only mean an allocation
    2316              : // failed, and the message says so.
    2317         8065 : static cjson parse_common(const char *src, size_t len, char **err_str,
    2318              :                           ccol_memmgmt_procs *mp) {
    2319         8065 :   if (!src) {
    2320            2 :     cjson_report_err(err_str, "null input");
    2321            2 :     return NULL;
    2322              :   }
    2323         8858 :   if (!cjson_intern_procs(&mp)) {
    2324            1 :     cjson_report_err(err_str,
    2325              :                      "too many distinct allocator procs in this process");
    2326            1 :     return NULL;
    2327              :   }
    2328         8062 :   parse_ctx ctx = {.src = src, .pos = 0, .len = len, .error = "", .mp = mp};
    2329         8062 :   cjson_node *root = parse_value(&ctx);
    2330         8062 :   if (!root) {
    2331         6209 :     if (err_str) {
    2332         5474 :       const char *msg;
    2333         5474 :       char oom_buf[80];
    2334         5474 :       if (ctx.error[0]) {
    2335              :         msg = ctx.error;
    2336              :       } else {
    2337            1 :         snprintf(oom_buf, sizeof(oom_buf),
    2338              :                  "out of memory (unreported allocation failure) at position "
    2339              :                  "%zu",
    2340              :                  ctx.pos);
    2341            1 :         msg = oom_buf;
    2342              :       }
    2343         5474 :       cjson_report_err(err_str, msg);
    2344              :     }
    2345         6209 :     return NULL;
    2346              :   }
    2347         1853 :   skip_ws(&ctx);
    2348         1853 :   if (ctx.pos != ctx.len) {
    2349          254 :     if (err_str) {
    2350          253 :       char buf[64];
    2351          253 :       snprintf(buf, sizeof(buf), "trailing garbage at position %zu", ctx.pos);
    2352          253 :       cjson_report_err(err_str, buf);
    2353              :     }
    2354          254 :     cjson__destroy((cjson)root);
    2355          254 :     return NULL;
    2356              :   }
    2357         1599 :   if (err_str) *err_str = NULL;
    2358              :   return (cjson)root;
    2359              : }
    2360              : 
    2361              : // Parses a NUL-terminated JSON string for the caller through parse_common();
    2362              : // a NULL json_str is reported as an error.
    2363         2257 : cjson cjson_parse_mp(const char *json_str, char **err_str,
    2364              :                      ccol_memmgmt_procs *mp) {
    2365         2257 :   if (!json_str) return parse_common(NULL, 0, err_str, mp);
    2366         2255 :   return parse_common(json_str, strlen(json_str), err_str, mp);
    2367              : }
    2368              : 
    2369              : // Parses len bytes of json_str, which needn't be NUL-terminated, for a caller
    2370              : // whose JSON sits inside a larger buffer.
    2371         5808 : cjson cjson_parse_n_mp(const char *json_str, size_t len, char **err_str,
    2372              :                        ccol_memmgmt_procs *mp) {
    2373         5808 :   return parse_common(json_str, len, err_str, mp);
    2374              : }
    2375              : 
    2376              : // Writes val into buf (cap bytes) in the shortest form that reads back the
    2377              : // same, for the serializer. It adds ".0" to a whole number so it parses back as
    2378              : // a CJSON_FLOAT; the longest such case, a signed 17-digit number, fits the
    2379              : // caller's 32 bytes. A non-finite value (which the API never stores) gives
    2380              : // null.
    2381        20031 : static void format_double(char *buf, size_t cap, double val) {
    2382        20031 :   if (!isfinite(val)) {
    2383            0 :     snprintf(buf, cap, "null");
    2384            0 :     return;
    2385              :   }
    2386        20031 :   cjson_format_shortest_c(buf, cap, val);
    2387        20031 :   if (!strchr(buf, '.') && !strchr(buf, 'e') && !strchr(buf, 'E')) {
    2388           20 :     size_t len = strlen(buf);
    2389           20 :     if (len + 2 < cap) {
    2390           20 :       buf[len] = '.';
    2391           20 :       buf[len + 1] = '0';
    2392           20 :       buf[len + 2] = '\0';
    2393              :     }
    2394              :   }
    2395              : }
    2396              : 
    2397              : // Appends a newline and depth * indent spaces, for the pretty serializer. It
    2398              : // copies from a constant block, one append per 128 spaces, and does nothing in
    2399              : // compact mode (indent 0). A width that doesn't fit a size_t sets sb->oom.
    2400        10108 : static void sb_append_indent(sbuf *sb, unsigned int indent,
    2401              :                              unsigned int depth) {
    2402        10108 :   static const char nl_spaces[130] =
    2403              :       "\n"
    2404              :       "                                                                "
    2405              :       "                                                                ";
    2406        10108 :   if (!indent) return;
    2407        10108 :   if (depth != 0 && indent > SIZE_MAX / depth) {
    2408              :     sb->oom = true;
    2409              :     return;
    2410              :   }
    2411        10108 :   size_t width = (size_t)depth * indent;
    2412        10108 :   size_t chunk = width < 128 ? width : 128;
    2413        10108 :   sb_append(sb, nl_spaces, chunk + 1);
    2414        10108 :   width -= chunk;
    2415        26747 :   while (width > 0) {
    2416        16639 :     chunk = width < 128 ? width : 128;
    2417        16639 :     sb_append(sb, nl_spaces + 1, chunk);
    2418        16639 :     width -= chunk;
    2419              :   }
    2420              : }
    2421              : 
    2422              : // Appends s as a quoted JSON string with escapes, for string values and keys.
    2423              : // Bytes >= 0x20 other than '"' and '\\' are copied as they are, which is
    2424              : // correct because every DOM string is valid UTF-8.
    2425        11428 : static void sb_append_json_str(sbuf *sb, const char *s) {
    2426        11428 :   sb_append_c(sb, '"');
    2427        11428 :   if (!s) {
    2428            0 :     sb_append_c(sb, '"');
    2429            0 :     return;
    2430              :   }
    2431              : 
    2432              :   const char *p = s;
    2433        11432 :   while (*p) {
    2434              :     const char *start = p;
    2435        28460 :     while (*p) {
    2436        17032 :       unsigned char c = (unsigned char)*p;
    2437        17032 :       if (c == '"' || c == '\\' || c < 0x20) break;
    2438        17028 :       p++;
    2439              :     }
    2440        11432 :     if (p > start) sb_append(sb, start, (size_t)(p - start));
    2441              : 
    2442        11432 :     if (!*p) break;
    2443              : 
    2444            4 :     unsigned char c = (unsigned char)*p++;
    2445            4 :     switch (c) {
    2446              :       case '"':
    2447            1 :         sb_append(sb, "\\\"", 2);
    2448            1 :         break;
    2449              :       case '\\':
    2450            1 :         sb_append(sb, "\\\\", 2);
    2451            1 :         break;
    2452              :       case '\b':
    2453            0 :         sb_append(sb, "\\b", 2);
    2454            0 :         break;
    2455              :       case '\f':
    2456            0 :         sb_append(sb, "\\f", 2);
    2457            0 :         break;
    2458              :       case '\n':
    2459            1 :         sb_append(sb, "\\n", 2);
    2460            1 :         break;
    2461              :       case '\r':
    2462            0 :         sb_append(sb, "\\r", 2);
    2463            0 :         break;
    2464              :       case '\t':
    2465            1 :         sb_append(sb, "\\t", 2);
    2466            1 :         break;
    2467            0 :       default: {
    2468            0 :         char esc[7];
    2469            0 :         snprintf(esc, sizeof(esc), "\\u%04x", c);
    2470            0 :         sb_append_cstr(sb, esc);
    2471              :       }
    2472              :     }
    2473              :   }
    2474        11428 :   sb_append_c(sb, '"');
    2475              : }
    2476              : 
    2477              : // Writes v in decimal into buf (at least 21 bytes) and gives its length, for
    2478              : // integer values; it's cheaper than snprintf.
    2479         2205 : static int lltoa(char *buf, long long v) {
    2480         2205 :   char tmp[22];
    2481         2205 :   unsigned long long u;
    2482         2205 :   int neg = (v < 0);
    2483         2205 :   int i = 0;
    2484         2205 :   u = neg ? (unsigned long long)(-(v + 1)) + 1ULL : (unsigned long long)v;
    2485         6748 :   do {
    2486         6748 :     tmp[i++] = '0' + (char)(u % 10);
    2487         6748 :     u /= 10;
    2488         6748 :   } while (u);
    2489         2205 :   if (neg) tmp[i++] = '-';
    2490         2205 :   int len = i;
    2491         8955 :   for (int j = 0; j < len; j++) buf[j] = tmp[len - 1 - j];
    2492         2205 :   buf[len] = '\0';
    2493         2205 :   return len;
    2494              : }
    2495              : 
    2496              : // The deepest nesting the serializers accept, in containers. A tree from the
    2497              : // public API can be of any depth; this has the parser's value, so whatever
    2498              : // parses can be written. serialize_node() uses a heap stack, so the limit is a
    2499              : // policy, not a stack bound.
    2500              : #define CJSON_MAX_SERIALIZE_DEPTH 500
    2501              : 
    2502              : // One open container on the explicit stack of serialize_node(). emitted counts
    2503              : // the children written (for the commas and the closing indent), count is the
    2504              : // length of a list, next is the next member of a dictionary in insertion
    2505              : // order, and depth gives the indent of the children.
    2506              : typedef struct {
    2507              :   cjson_node *node;
    2508              :   size_t emitted;
    2509              :   size_t count;
    2510              :   const ccol_chmap_entry_ref *next;
    2511              :   unsigned int depth;
    2512              :   bool is_dict;
    2513              : } serialize_frame;
    2514              : 
    2515              : // Pushes a frame onto the stack of serialize_node(), growing it when it's full.
    2516              : // *frames starts at the caller's inline_frames, so an ordinary document needs
    2517              : // no scratch allocation; *cap and *len describe the stack. Gives false, with
    2518              : // the stack unchanged, when the growth fails.
    2519        18406 : static bool serialize_stack_push(serialize_frame **frames,
    2520              :                                  serialize_frame *inline_frames,
    2521              :                                  size_t inline_cap, size_t *cap, size_t *len,
    2522              :                                  const serialize_frame *frame) {
    2523        18406 :   if (*len == *cap) {
    2524          144 :     size_t new_cap = *cap * 2;
    2525          144 :     serialize_frame *grown;
    2526          144 :     if (*frames == inline_frames) {
    2527           36 :       grown = ccol__default_mem_alloc(new_cap * sizeof(**frames));
    2528           36 :       if (!grown) return false;
    2529           36 :       memcpy(grown, inline_frames, inline_cap * sizeof(**frames));
    2530              :     } else {
    2531          108 :       grown = ccol__default_mem_realloc(*frames, new_cap * sizeof(**frames));
    2532          108 :       if (!grown) return false;
    2533              :     }
    2534          144 :     *frames = grown;
    2535          144 :     *cap = new_cap;
    2536              :   }
    2537        18406 :   (*frames)[(*len)++] = *frame;
    2538        18406 :   return true;
    2539              : }
    2540              : 
    2541              : // Writes a node that isn't a container into sb, for serialize_node(); a NULL
    2542              : // node is written as null. Each case is listed so -Wswitch reports a new node
    2543              : // kind.
    2544        22360 : static void serialize_scalar(sbuf *sb, cjson_node *n) {
    2545        22360 :   if (!n) {
    2546            2 :     sb_append_cstr(sb, "null");
    2547            2 :     return;
    2548              :   }
    2549        22358 :   switch (n->type) {
    2550            6 :     case CJSON_BOOL:
    2551            6 :       sb_append_cstr(sb, n->value.boolean ? "true" : "false");
    2552            6 :       break;
    2553         2205 :     case CJSON_INTEGER: {
    2554         2205 :       char buf[24];
    2555         2205 :       int len = lltoa(buf, n->value.integer);
    2556         2205 :       sb_append(sb, buf, (size_t)len);
    2557         2205 :       break;
    2558              :     }
    2559        20031 :     case CJSON_FLOAT: {
    2560        20031 :       char buf[32];
    2561        20031 :       format_double(buf, sizeof(buf), n->value.number);
    2562        20031 :       sb_append_cstr(sb, buf);
    2563        20031 :       break;
    2564              :     }
    2565          111 :     case CJSON_STRING:
    2566          111 :       sb_append_json_str(sb, n->value.string);
    2567          111 :       break;
    2568              :     case CJSON_NULL:
    2569              :     case CJSON_LIST:
    2570              :     case CJSON_DICTIONARY:
    2571            5 :       sb_append_cstr(sb, "null");
    2572            5 :       break;
    2573              :   }
    2574              : }
    2575              : 
    2576              : // Writes the subtree at n into sb, for both public serializers, with indent
    2577              : // spaces per level (0 for compact) from nesting level depth. It walks with an
    2578              : // explicit stack, and every failure, the depth cap included, sets sb->oom.
    2579        20405 : static void serialize_node(sbuf *sb, cjson_node *n, unsigned int indent,
    2580              :                            unsigned int depth) {
    2581        20405 :   serialize_frame inline_frames[32];
    2582        20405 :   serialize_frame *frames = inline_frames;
    2583        20405 :   size_t cap = sizeof(inline_frames) / sizeof(inline_frames[0]);
    2584        20405 :   size_t len = 0;
    2585              : 
    2586        20405 :   cjson_node *cur = n;
    2587        20405 :   unsigned int cur_depth = depth;
    2588              : 
    2589        40782 :   for (;;) {
    2590        40782 :     if (sb->oom) goto done;
    2591        59186 :     if (cur && (cur->type == CJSON_LIST || cur->type == CJSON_DICTIONARY)) {
    2592        18420 :       if (cur_depth >= CJSON_MAX_SERIALIZE_DEPTH) {
    2593           14 :         sb->oom = true;
    2594           14 :         goto done;
    2595              :       }
    2596        18406 :       serialize_frame f = {.node = cur,
    2597              :                            .emitted = 0,
    2598              :                            .count = 0,
    2599              :                            .next = NULL,
    2600              :                            .depth = cur_depth,
    2601        18406 :                            .is_dict = (cur->type == CJSON_DICTIONARY)};
    2602        18406 :       if (cur->type == CJSON_LIST) {
    2603         9042 :         f.count = list_len_of(cur);
    2604         9042 :         sb_append_c(sb, '[');
    2605              :       } else {
    2606         9364 :         f.next = dict_first_entry(cur);
    2607         9364 :         sb_append_c(sb, '{');
    2608              :       }
    2609        18406 :       if (!serialize_stack_push(&frames, inline_frames,
    2610              :                                 sizeof(inline_frames) / sizeof(*inline_frames),
    2611              :                                 &cap, &len, &f)) {
    2612            0 :         sb->oom = true;
    2613            0 :         goto done;
    2614              :       }
    2615              :     } else {
    2616        22360 :       serialize_scalar(sb, cur);
    2617              :     }
    2618              : 
    2619        52172 :     for (;;) {
    2620        52172 :       if (len == 0) goto done;
    2621        31783 :       serialize_frame *f = &frames[len - 1];
    2622              : 
    2623        31783 :       if (!f->is_dict) {
    2624        14098 :         if (f->emitted < f->count) {
    2625         9060 :           if (f->emitted > 0) sb_append_c(sb, ',');
    2626         9060 :           if (indent) sb_append_indent(sb, indent, f->depth + 1);
    2627         9060 :           cur = *(cjson_node **)cvector_at(f->node->value.list, f->emitted);
    2628         9060 :           f->emitted++;
    2629         9060 :           cur_depth = f->depth + 1;
    2630         9060 :           break;
    2631              :         }
    2632         5038 :         if (indent && f->count > 0) sb_append_indent(sb, indent, f->depth);
    2633         5038 :         sb_append_c(sb, ']');
    2634         5038 :         len--;
    2635         5038 :         continue;
    2636              :       }
    2637              : 
    2638        17685 :       if (f->next) {
    2639        11317 :         const cmap_pair *kp, *vp;
    2640        11317 :         f->next = ccol_chmap_entry_read(f->next, &kp, &vp);
    2641        11317 :         if (f->emitted > 0) sb_append_c(sb, ',');
    2642        11317 :         if (indent) sb_append_indent(sb, indent, f->depth + 1);
    2643        11317 :         sb_append_json_str(sb, (const char *)kp->ptr);
    2644        11317 :         sb_append_c(sb, ':');
    2645        11317 :         if (indent) sb_append_c(sb, ' ');
    2646        11317 :         cur = cjson_read_child(vp->ptr);
    2647        11317 :         f->emitted++;
    2648        11317 :         cur_depth = f->depth + 1;
    2649        11317 :         break;
    2650              :       }
    2651         6368 :       if (indent && f->emitted > 0) sb_append_indent(sb, indent, f->depth);
    2652         6368 :       sb_append_c(sb, '}');
    2653         6368 :       len--;
    2654              :     }
    2655              :   }
    2656              : 
    2657        20405 : done:
    2658        20405 :   if (frames != inline_frames) ccol__default_mem_free(frames);
    2659        20405 : }
    2660              : 
    2661              : // Writes node as compact JSON for the caller, into a buffer from node's
    2662              : // allocator. Gives NULL when an allocation fails or the tree is too deep.
    2663        20373 : char *cjson_serialize(cjson node) {
    2664        20373 :   cjson_node *n = (cjson_node *)node;
    2665        20373 :   ccol_memmgmt_procs *mp = n ? n->m_procs : NULL;
    2666        20373 :   sbuf sb;
    2667        20373 :   sb_init(&sb, mp);
    2668        20373 :   serialize_node(&sb, n, 0, 0);
    2669        20373 :   if (sb.oom) {
    2670           10 :     ccol__mem_free(sb.m_procs, sb.buf);
    2671           10 :     return NULL;
    2672              :   }
    2673        20363 :   return sb.buf;
    2674              : }
    2675              : 
    2676              : // Writes node as indented JSON for the caller (indent 0 means 4), into a
    2677              : // buffer from node's allocator. Gives NULL on failure.
    2678           32 : char *cjson_serialize_pretty(cjson node, unsigned int indent) {
    2679           32 :   cjson_node *n = (cjson_node *)node;
    2680           32 :   ccol_memmgmt_procs *mp = n ? n->m_procs : NULL;
    2681           32 :   sbuf sb;
    2682           32 :   sb_init(&sb, mp);
    2683           33 :   serialize_node(&sb, n, indent ? indent : 4, 0);
    2684           32 :   if (sb.oom) {
    2685            6 :     ccol__mem_free(sb.m_procs, sb.buf);
    2686            6 :     return NULL;
    2687              :   }
    2688           26 :   return sb.buf;
    2689              : }
    2690              : 
    2691              : // Frees a serializer buffer with mp (NULL for the default allocator), since
    2692              : // only the caller knows which allocator built the tree.
    2693        20402 : void cjson_serialize_free_mp(char *s, ccol_memmgmt_procs *mp) {
    2694        20402 :   ccol__mem_free(mp, s);
    2695        20402 : }
    2696              : 
    2697              : // Gives the first unescaped '.' in s, or NULL, so navigate() can split a path
    2698              : // into components. In a path "\." is a literal dot and "\\" a literal
    2699              : // backslash; a backslash before anything else is kept. A component's escapes
    2700              : // are resolved after the path is split.
    2701          481 : static char *path_find_unescaped_dot(char *s) {
    2702          481 :   char *p = s;
    2703         1801 :   while (*p) {
    2704         1476 :     if (*p == '\\' && (*(p + 1) == '.' || *(p + 1) == '\\')) {
    2705           10 :       p += 2;
    2706         1466 :     } else if (*p == '.') {
    2707              :       return p;
    2708              :     } else {
    2709         1310 :       p++;
    2710              :     }
    2711              :   }
    2712              :   return NULL;
    2713              : }
    2714              : 
    2715              : // Gives the last unescaped '.' in s, or NULL, so a set or a delete can split a
    2716              : // path into the parent path and the leaf.
    2717              : static char *path_find_last_unescaped_dot(char *s) {
    2718              :   char *last = NULL;
    2719              :   char *p = s;
    2720         1104 :   while (*p) {
    2721          901 :     if (*p == '\\' && (*(p + 1) == '.' || *(p + 1) == '\\')) {
    2722            5 :       p += 2;
    2723          896 :     } else if (*p == '.') {
    2724          142 :       last = p;
    2725          142 :       p++;
    2726              :     } else {
    2727          754 :       p++;
    2728              :     }
    2729              :   }
    2730          203 :   return last;
    2731              : }
    2732              : 
    2733              : // Resolves the escapes of a path component s in place before it's used as a
    2734              : // key; s never gets longer.
    2735          675 : static void path_unescape_component(char *s) {
    2736          675 :   char *r = s, *w = s;
    2737         2478 :   while (*r) {
    2738         1803 :     if (*r == '\\' && (*(r + 1) == '.' || *(r + 1) == '\\')) {
    2739           15 :       *w++ = *(r + 1);
    2740           15 :       r += 2;
    2741              :     } else {
    2742         1788 :       *w++ = *r++;
    2743              :     }
    2744              :   }
    2745          675 :   *w = '\0';
    2746          675 : }
    2747              : 
    2748              : // Parses the digits after the '#' of a "#N" component into *out, for every
    2749              : // path function that indexes a list. Only one or more ASCII digits are
    2750              : // accepted (no sign, no whitespace, no bare '#'), so it gives false for
    2751              : // anything else. The digits are read by hand rather than with strtol(), and a
    2752              : // value too big for size_t saturates at SIZE_MAX, so an index of any length is
    2753              : // just "not found".
    2754           93 : static bool parse_list_index_component(const char *digits, size_t *out) {
    2755           93 :   if (digits[0] < '0' || digits[0] > '9') return false;
    2756              :   size_t idx = 0;
    2757              :   const char *p = digits;
    2758          338 :   for (; *p >= '0' && *p <= '9'; p++) {
    2759          268 :     size_t d = (size_t)(*p - '0');
    2760          268 :     idx = (idx > (SIZE_MAX - d) / 10) ? SIZE_MAX : idx * 10 + d;
    2761              :   }
    2762           70 :   if (*p != '\0') return false;
    2763           93 :   *out = idx;
    2764              :   return true;
    2765              : }
    2766              : 
    2767              : // Walks a dot-separated path from root and gives the node at its end, or NULL;
    2768              : // cjson__get() and the parent walk of set and delete use it. path_copy must be
    2769              : // writable: Each separator becomes a '\0' in turn and each component is
    2770              : // unescaped in place. When invalid isn't NULL it is set for an error in the
    2771              : // path, at any position: An empty component, a component that isn't UTF-8, a
    2772              : // malformed #N on a list, or a shape that can't apply (a scalar in the middle,
    2773              : // a name on a list). It stays false when a well-formed component is simply
    2774              : // absent, which lets the callers tell ccol_invalid_args from
    2775              : // ccol_key_not_found. The scan goes on past an absent component, so a later
    2776              : // syntax error is still reported; the UTF-8 test runs only for a component
    2777              : // that doesn't resolve, so a lookup that succeeds pays nothing.
    2778          329 : static cjson navigate(cjson root, char *path_copy, bool *invalid) {
    2779          329 :   if (invalid) *invalid = false;
    2780              :   cjson cur = root;
    2781              :   char *p = path_copy;
    2782              : 
    2783          633 :   while (1) {
    2784          481 :     char *dot = path_find_unescaped_dot(p);
    2785          481 :     if (dot) *dot = '\0';
    2786              : 
    2787          481 :     if (p[0] == '\0') {
    2788            7 :       if (invalid) *invalid = true;
    2789              :       cur = NULL;
    2790              :       break;
    2791              :     }
    2792              : 
    2793          474 :     path_unescape_component(p);
    2794              : 
    2795          474 :     if (cur) {
    2796          453 :       cjson_node *n = (cjson_node *)cur;
    2797              : 
    2798          453 :       if (n->type == CJSON_LIST && p[0] == '#') {
    2799           59 :         size_t idx;
    2800          118 :         if (!parse_list_index_component(p + 1, &idx)) {
    2801           16 :           if (invalid) {
    2802            8 :             *invalid = true;
    2803            8 :             cur = NULL;
    2804            8 :             break;
    2805              :           }
    2806              :           cur = NULL;
    2807              :         } else {
    2808           43 :           cur = (cjson)list_child_at(n, idx);
    2809              :         }
    2810          394 :       } else if (n->type == CJSON_DICTIONARY) {
    2811          368 :         cmap_pair kp = {.ptr = p, .size = strlen(p) + 1};
    2812          368 :         cmap_pair vp;
    2813          728 :         if (dict_lookup(n, &kp, &vp) != ccol_success)
    2814              :           cur = NULL;
    2815              :         else
    2816          329 :           cur = cjson_read_child(vp.ptr);
    2817              :       } else {
    2818           26 :         if (invalid) {
    2819           12 :           *invalid = true;
    2820           12 :           cur = NULL;
    2821           12 :           break;
    2822              :         }
    2823              :         cur = NULL;
    2824              :       }
    2825              :     }
    2826              : 
    2827          454 :     if (!cur && invalid && !utf8_cstr_is_valid(p)) {
    2828            6 :       *invalid = true;
    2829            6 :       break;
    2830              :     }
    2831              : 
    2832          448 :     if (!dot) break;
    2833          152 :     p = dot + 1;
    2834              :   }
    2835              : 
    2836          329 :   return cur;
    2837              : }
    2838              : 
    2839              : // Paths shorter than this are copied to the stack, so cjson_get() of such a
    2840              : // path allocates nothing.
    2841              : #define CJSON_GET_STACK_PATH 256
    2842              : // Gives the node at path, root for an empty path, or NULL; it's the body of
    2843              : // cjson_get(). It copies the path (to the stack or, when long, with root's
    2844              : // allocator) so navigate() can write into it and the caller's string stays
    2845              : // unchanged.
    2846          238 : cjson cjson__get(cjson root, const char *path) {
    2847          238 :   if (!root) return NULL;
    2848          238 :   if (!path || path[0] == '\0') return root;
    2849              : 
    2850          237 :   ccol_memmgmt_procs *mp = ((cjson_node *)root)->m_procs;
    2851          237 :   char stack_copy[CJSON_GET_STACK_PATH];
    2852          237 :   size_t len = strlen(path);
    2853          237 :   char *copy = stack_copy;
    2854          237 :   if (len < sizeof(stack_copy)) {
    2855          236 :     memcpy(stack_copy, path, len + 1);
    2856              :   } else {
    2857            1 :     copy = ccol_strdup(mp, path);
    2858            1 :     if (!copy) return NULL;
    2859              :   }
    2860          237 :   cjson result = navigate(root, copy, NULL);
    2861          237 :   if (copy != stack_copy) ccol__mem_free(mp, copy);
    2862              :   return result;
    2863              : }
    2864              : 
    2865              : // Writes a scalar to the leaf at path; it's the body of cjson_set(). type, raw,
    2866              : // raw_size and is_signed describe the C value. The path is split on its last
    2867              : // unescaped dot into the parent path and the leaf, and the leaf is checked (not
    2868              : // empty, valid UTF-8, since it may become a key) before the parent is walked,
    2869              : // so a syntax error never hides behind a missing parent. The payload is
    2870              : // checked before the map changes. On a dictionary one insert either finds the
    2871              : // leaf, which is updated in place so a borrowed handle stays valid, or adds the
    2872              : // key with a NULL placeholder that is filled (or removed again when building
    2873              : // the child fails). On a list the leaf must be an existing #N; an out-of-range
    2874              : // index is ccol_key_not_found, since a list can't grow to fit.
    2875          158 : ccol_retval cjson__set_typed(cjson root, const char *path, cjson_node_type type,
    2876              :                              void *raw, size_t raw_size, bool is_signed) {
    2877          158 :   if (!root || !path || path[0] == '\0') return ccol_invalid_args;
    2878              : 
    2879          157 :   ccol_memmgmt_procs *mp = ((cjson_node *)root)->m_procs;
    2880              : 
    2881          159 :   char *copy = ccol_strdup(mp, path);
    2882          155 :   if (!copy) return ccol_not_enough_memory;
    2883              : 
    2884          155 :   char *last_dot = path_find_last_unescaped_dot(copy);
    2885          155 :   char *leaf_copy;
    2886              : 
    2887          155 :   if (!last_dot) {
    2888              :     leaf_copy = copy;
    2889              :   } else {
    2890           56 :     *last_dot = '\0';
    2891           56 :     if (copy[0] == '\0') {
    2892            1 :       ccol__mem_free(mp, copy);
    2893            1 :       return ccol_invalid_args;
    2894              :     }
    2895           55 :     leaf_copy = ccol_strdup(mp, last_dot + 1);
    2896           55 :     if (!leaf_copy) {
    2897            0 :       ccol__mem_free(mp, copy);
    2898            0 :       return ccol_not_enough_memory;
    2899              :     }
    2900              :   }
    2901              : 
    2902          154 :   path_unescape_component(leaf_copy);
    2903          154 :   if (leaf_copy[0] == '\0' || !utf8_cstr_is_valid(leaf_copy)) {
    2904            3 :     if (leaf_copy != copy) ccol__mem_free(mp, leaf_copy);
    2905            3 :     ccol__mem_free(mp, copy);
    2906            3 :     return ccol_invalid_args;
    2907              :   }
    2908          151 :   const char *leaf_comp = leaf_copy;
    2909              : 
    2910          151 :   cjson parent;
    2911          151 :   if (!last_dot) {
    2912              :     parent = root;
    2913              :   } else {
    2914           53 :     bool invalid = false;
    2915           53 :     parent = navigate(root, copy, &invalid);
    2916           53 :     ccol__mem_free(mp, copy);
    2917           53 :     if (!parent) {
    2918           19 :       ccol__mem_free(mp, leaf_copy);
    2919           23 :       return invalid ? ccol_invalid_args : ccol_key_not_found;
    2920              :     }
    2921              :   }
    2922              : 
    2923          132 :   cjson_node *pn = (cjson_node *)parent;
    2924          132 :   ccol_retval ret;
    2925              : 
    2926          132 :   if (pn->type == CJSON_DICTIONARY) {
    2927          101 :     cmap_pair kp = {.ptr = (void *)leaf_comp, .size = strlen(leaf_comp) + 1};
    2928          101 :     ret = scalar_payload_check(type, raw, raw_size);
    2929          101 :     if (ret == ccol_success) {
    2930           80 :       cjson_node *placeholder = NULL;
    2931           80 :       cmap_pair vp = {.ptr = &placeholder, .size = sizeof(placeholder)};
    2932           80 :       cmap_pair slot;
    2933           80 :       chmap store = dict_store(pn);
    2934          202 :       ccol_retval r =
    2935           80 :           store ? ccol_chmap_insert_or_get_elem(store, &kp, &vp, &slot)
    2936           80 :                 : ccol_not_enough_memory;
    2937           80 :       if (r == ccol_key_already_present) {
    2938           38 :         cjson_node *existing = cjson_read_child(slot.ptr);
    2939           38 :         ret = node_reinit_scalar_checked(existing, type, raw, raw_size,
    2940              :                                          is_signed);
    2941           42 :       } else if (r == ccol_success) {
    2942           41 :         cjson_node *new_node;
    2943           41 :         ret = node_make_scalar(type, raw, raw_size, is_signed, pn->m_procs,
    2944              :                                &new_node);
    2945           41 :         if (ret == ccol_success) {
    2946           39 :           memcpy(slot.ptr, &new_node, sizeof(new_node));
    2947           39 :           new_node->attached = true;
    2948              :         } else {
    2949            2 :           chashmap_remove_elem(pn->value.dictionary, &kp);
    2950              :         }
    2951              :       } else {
    2952              :         ret = r;
    2953              :       }
    2954              :     }
    2955           31 :   } else if (pn->type == CJSON_LIST) {
    2956           24 :     if (leaf_comp[0] != '#') {
    2957              :       ret = ccol_invalid_args;
    2958              :     } else {
    2959           23 :       size_t idx;
    2960           46 :       if (!parse_list_index_component(leaf_comp + 1, &idx)) {
    2961              :         ret = ccol_invalid_args;
    2962              :       } else {
    2963           18 :         cjson_node *existing = list_child_at(pn, idx);
    2964           12 :         if (!existing) {
    2965              :           ret = ccol_key_not_found;
    2966              :         } else {
    2967           12 :           ret = node_reinit_scalar(existing, type, raw, raw_size, is_signed);
    2968              :         }
    2969              :       }
    2970              :     }
    2971              :   } else {
    2972              :     ret = ccol_invalid_args;
    2973              :   }
    2974              : 
    2975          132 :   ccol__mem_free(mp, leaf_copy);
    2976              :   return ret;
    2977              : }
    2978              : 
    2979              : // Removes and destroys the node at path; it's the body of cjson_remove(). It
    2980              : // splits the path like cjson__set_typed(), checks the leaf before walking the
    2981              : // parent, and then removes through cjson_dictionary_remove() or
    2982              : // cjson_list_remove(). An absent list index is checked here, so it gives
    2983              : // ccol_key_not_found and not the ccol_invalid_args that cjson_list_remove()
    2984              : // would.
    2985           51 : ccol_retval cjson__remove(cjson root, const char *path) {
    2986           51 :   if (!root || !path || path[0] == '\0') return ccol_invalid_args;
    2987              : 
    2988           48 :   ccol_memmgmt_procs *mp = ((cjson_node *)root)->m_procs;
    2989           48 :   char *copy = ccol_strdup(mp, path);
    2990           48 :   if (!copy) return ccol_not_enough_memory;
    2991              : 
    2992           48 :   char *last_dot = path_find_last_unescaped_dot(copy);
    2993           48 :   char *leaf_copy;
    2994              : 
    2995           48 :   if (!last_dot) {
    2996              :     leaf_copy = copy;
    2997              :   } else {
    2998           42 :     *last_dot = '\0';
    2999           42 :     if (copy[0] == '\0') {
    3000            1 :       ccol__mem_free(mp, copy);
    3001            1 :       return ccol_invalid_args;
    3002              :     }
    3003           41 :     leaf_copy = ccol_strdup(mp, last_dot + 1);
    3004           41 :     if (!leaf_copy) {
    3005            0 :       ccol__mem_free(mp, copy);
    3006            0 :       return ccol_not_enough_memory;
    3007              :     }
    3008              :   }
    3009              : 
    3010           47 :   path_unescape_component(leaf_copy);
    3011           47 :   if (leaf_copy[0] == '\0') {
    3012            2 :     if (leaf_copy != copy) ccol__mem_free(mp, leaf_copy);
    3013            2 :     ccol__mem_free(mp, copy);
    3014            2 :     return ccol_invalid_args;
    3015              :   }
    3016           45 :   const char *leaf_comp = leaf_copy;
    3017              : 
    3018           45 :   cjson parent;
    3019           45 :   if (!last_dot) {
    3020              :     parent = root;
    3021              :   } else {
    3022           39 :     bool invalid = false;
    3023           39 :     parent = navigate(root, copy, &invalid);
    3024           39 :     ccol__mem_free(mp, copy);
    3025           39 :     if (!parent) {
    3026           19 :       ccol__mem_free(mp, leaf_copy);
    3027           23 :       return invalid ? ccol_invalid_args : ccol_key_not_found;
    3028              :     }
    3029              :   }
    3030              : 
    3031           26 :   cjson_node *pn = (cjson_node *)parent;
    3032           26 :   ccol_retval ret;
    3033              : 
    3034           26 :   if (pn->type == CJSON_DICTIONARY) {
    3035            6 :     ret = cjson_dictionary_remove(parent, leaf_comp);
    3036           20 :   } else if (pn->type == CJSON_LIST) {
    3037           13 :     if (leaf_comp[0] != '#') {
    3038              :       ret = ccol_invalid_args;
    3039              :     } else {
    3040           11 :       size_t idx;
    3041           22 :       if (!parse_list_index_component(leaf_comp + 1, &idx)) {
    3042              :         ret = ccol_invalid_args;
    3043           17 :       } else if (idx >= list_len_of(pn)) {
    3044              :         ret = ccol_key_not_found;
    3045              :       } else {
    3046            2 :         ret = cjson_list_remove(parent, idx);
    3047              :       }
    3048              :     }
    3049              :   } else {
    3050              :     ret = ccol_invalid_args;
    3051              :   }
    3052              : 
    3053           26 :   ccol__mem_free(mp, leaf_copy);
    3054              :   return ret;
    3055              : }
        

Generated by: LCOV version 2.0-1