LCOV - code coverage report
Current view: top level - include - cjson.h (source / functions) Coverage Total Hit
Test: c_collections 2.0.0 Lines: 94.6 % 37 35
Test Date: 2026-11-15 18:57:05 Functions: 100.0 % 1 1
Legend: Lines: hit not hit

            Line data    Source code
       1              : /*
       2              : MIT License
       3              : 
       4              : Copyright (c) 2026 - A bunch of nerds
       5              : 
       6              : Permission is hereby granted, free of charge, to any person obtaining a copy
       7              : of this software and associated documentation files (the "Software"), to deal
       8              : in the Software without restriction, including without limitation the rights
       9              : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      10              : copies of the Software, and to permit persons to whom the Software is
      11              : furnished to do so, subject to the following conditions:
      12              : 
      13              : The above copyright notice and this permission notice shall be included in all
      14              : copies or substantial portions of the Software.
      15              : 
      16              : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      17              : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      18              : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      19              : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      20              : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      21              : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
      22              : SOFTWARE.
      23              : */
      24              : 
      25              : #pragma once
      26              : 
      27              : // A JSON parser, serializer and mutable DOM. Lists are cvectors, dictionaries
      28              : // are chmaps, and every node is an opaque heap-allocated cjson_node.
      29              : //
      30              : // Allocator: Every factory and parse function takes a ccol_memmgmt_procs *mp
      31              : // (NULL for the default allocator). The library keeps its own process-lifetime
      32              : // copy of the struct, one per distinct set of four functions, at most 64 of
      33              : // them; a call that would need a 65th fails with NULL. So your struct may go
      34              : // away, but its functions must stay callable until the last node built with
      35              : // them is destroyed. All nodes of one tree carry the same allocator, which
      36              : // serves the nodes, owned strings, list and dictionary stores, path copies and
      37              : // the serializer buffers. With the default allocator a thread-local pool of up
      38              : // to 512 nodes speeds up allocation; it's drained when the thread exits.
      39              : //
      40              : // Text: Every string in a tree (value or key) is well-formed UTF-8. The parser
      41              : // refuses ill-formed bytes and lone surrogate escapes with a printable-ASCII
      42              : // message that names the bytes as 0xNN and the byte offset, and
      43              : // cjson_create_string(), cjson_set() and cjson_dictionary_set() refuse a C
      44              : // string that isn't UTF-8. Nothing is repaired.
      45              : //
      46              : // Nesting: Parse, clone and serialize accept at most 500 nested containers and
      47              : // report a deeper document as an error. They walk with a heap worklist, so the
      48              : // limit doesn't depend on the thread's stack. cjson_destroy() has no limit.
      49              : //
      50              : // Memory: A parsed tree is linear in its input, at most about 65 bytes of tree
      51              : // per input byte on a 64-bit target, so bounding the input bounds a parse.
      52              : //
      53              : // Paths (cjson_get, cjson_set, cjson_remove): Dot-separated components such as
      54              : // "users.#0.address.city". A plain component is a dictionary key; "#N" is a
      55              : // zero-based index, but only on a list (elsewhere it's a literal key). "\." and
      56              : // "\\" escape a dot and a backslash. An empty path gives the root for
      57              : // cjson_get and is an error for the others. A malformed component (empty, not
      58              : // UTF-8, a bad #N on a list) or a path whose shape can't apply to the tree
      59              : // (descending into a scalar, a name on a list) is ccol_invalid_args at any
      60              : // position; ccol_key_not_found means only that a well-formed name or index is
      61              : // absent. cjson_get() gives NULL in all these cases.
      62              : //
      63              : // Ownership: Create, parse and clone return trees the caller owns. A
      64              : // successful cjson_list_push() or cjson_dictionary_set() moves the child to the
      65              : // parent. On failure ccol_invalid_args always means the child is untouched and
      66              : // yours, and every other error code means the call already destroyed it.
      67              : // Everything that cjson_get() and the other getters return is borrowed and
      68              : // valid until the tree changes. cjson_destroy() frees a whole subtree.
      69              : 
      70              : #include "common.h"
      71              : 
      72              : // Everything from here to the end of the header is the public ABI and the
      73              : // shared library exports it. The library is built with -fvisibility=hidden, so
      74              : // anything outside such a block stays internal.
      75              : #pragma GCC visibility push(default)
      76              : 
      77              : // The tag of a node: One of the seven JSON value kinds.
      78              : typedef enum cjson_node_type {
      79              :   CJSON_NULL = 0,
      80              :   CJSON_BOOL,
      81              :   CJSON_INTEGER,
      82              :   CJSON_FLOAT,
      83              :   CJSON_STRING,
      84              :   CJSON_LIST,
      85              :   CJSON_DICTIONARY,
      86              : } cjson_node_type;
      87              : 
      88              : // The opaque node; cjson.c defines it.
      89              : typedef struct cjson_node cjson_node;
      90              : 
      91              : // The public handle.
      92              : typedef cjson_node *cjson;
      93              : 
      94              : // Creates a node that holds the JSON value null, for building a tree by hand.
      95              : // mp is the allocator of the node (NULL for the default allocator). Gives the
      96              : // new node, which the caller owns: Free it with cjson_destroy() or hand it to a
      97              : // parent with cjson_list_push() or cjson_dictionary_set(). NULL when the
      98              : // allocation fails or a 65th distinct allocator would be needed.
      99              : cjson cjson_create_null_mp(ccol_memmgmt_procs *mp);
     100              : 
     101              : // Creates a node that holds the JSON value null, with the default allocator.
     102              : // Gives the new node, which the caller owns: Free it with cjson_destroy() or
     103              : // hand it to a parent with cjson_list_push() or cjson_dictionary_set(). NULL
     104              : // when the allocation fails.
     105          668 : static inline cjson cjson_create_null(void) {
     106          668 :   return cjson_create_null_mp(NULL);
     107              : }
     108              : 
     109              : // Creates a CJSON_BOOL node that holds val. mp is the allocator of the node
     110              : // (NULL for the default allocator). The caller owns the new node and frees it
     111              : // with cjson_destroy(), unless a parent takes it through cjson_list_push() or
     112              : // cjson_dictionary_set(). Gives NULL when the allocation fails or a 65th
     113              : // distinct allocator would be needed.
     114              : cjson cjson_create_bool_mp(bool val, ccol_memmgmt_procs *mp);
     115              : 
     116              : // Creates a CJSON_BOOL node that holds val, with the default allocator. The
     117              : // caller owns the new node and frees it with cjson_destroy(), unless a parent
     118              : // takes it through cjson_list_push() or cjson_dictionary_set(). Gives NULL
     119              : // when the allocation fails.
     120            8 : static inline cjson cjson_create_bool(bool val) {
     121            7 :   return cjson_create_bool_mp(val, NULL);
     122              : }
     123              : 
     124              : // Creates a CJSON_INTEGER node that holds val. mp is the allocator of the node
     125              : // (NULL for the default allocator). The new node belongs to the caller, who
     126              : // frees it with cjson_destroy() or attaches it to a list or dictionary. NULL
     127              : // when the allocation fails or a 65th distinct allocator would be needed.
     128              : cjson cjson_create_int_mp(long long val, ccol_memmgmt_procs *mp);
     129              : 
     130              : // Creates a CJSON_INTEGER node that holds val, with the default allocator. The
     131              : // new node belongs to the caller, who frees it with cjson_destroy() or
     132              : // attaches it to a list or dictionary. NULL when the allocation fails.
     133         3591 : static inline cjson cjson_create_int(long long val) {
     134         3591 :   return cjson_create_int_mp(val, NULL);
     135              : }
     136              : 
     137              : // Creates a CJSON_FLOAT node that holds val. mp is the allocator of the node
     138              : // (NULL for the default allocator). Gives the new node, which the caller frees
     139              : // with cjson_destroy() or attaches to a parent. Gives NULL for Inf or NaN,
     140              : // which JSON can't write, when the allocation fails, or when a 65th distinct
     141              : // allocator would be needed.
     142              : cjson cjson_create_double_mp(double val, ccol_memmgmt_procs *mp);
     143              : 
     144              : // Creates a CJSON_FLOAT node that holds val, with the default allocator. Gives
     145              : // the new node, which the caller frees with cjson_destroy() or attaches to a
     146              : // parent. Gives NULL for Inf or NaN, which JSON can't write, and when the
     147              : // allocation fails.
     148        20019 : static inline cjson cjson_create_double(double val) {
     149        20019 :   return cjson_create_double_mp(val, NULL);
     150              : }
     151              : 
     152              : // Creates a CJSON_STRING node that holds its own copy of val; a NULL val gives
     153              : // a CJSON_NULL node. mp is the allocator of the node (NULL for the default
     154              : // allocator). The caller owns the new node and frees it with cjson_destroy(),
     155              : // unless a parent takes it. Gives NULL when val isn't valid UTF-8, when the
     156              : // allocation fails, or when a 65th distinct allocator would be needed.
     157              : cjson cjson_create_string_mp(const char *val, ccol_memmgmt_procs *mp);
     158              : 
     159              : // Creates a CJSON_STRING node that holds its own copy of val, with the default
     160              : // allocator; a NULL val gives a CJSON_NULL node. The caller owns the new node
     161              : // and frees it with cjson_destroy(), unless a parent takes it. Gives NULL when
     162              : // val isn't valid UTF-8 or the allocation fails.
     163           26 : static inline cjson cjson_create_string(const char *val) {
     164           26 :   return cjson_create_string_mp(val, NULL);
     165              : }
     166              : 
     167              : // Creates an empty CJSON_LIST node; fill it with cjson_list_push(). mp is the
     168              : // allocator of the list and of what it stores (NULL for the default
     169              : // allocator). The caller owns the list and frees it, children included, with
     170              : // cjson_destroy(). NULL when the allocation fails or a 65th distinct
     171              : // allocator would be needed.
     172              : cjson cjson_create_list_mp(ccol_memmgmt_procs *mp);
     173              : 
     174              : // Creates an empty CJSON_LIST node with the default allocator; fill it with
     175              : // cjson_list_push(). The caller owns the list and frees it, children included,
     176              : // with cjson_destroy(). NULL when the allocation fails.
     177        41744 : static inline cjson cjson_create_list(void) {
     178        41738 :   return cjson_create_list_mp(NULL);
     179              : }
     180              : 
     181              : // Creates an empty CJSON_DICTIONARY node; fill it with cjson_dictionary_set().
     182              : // mp is the allocator of the dictionary and of what it stores (NULL for the
     183              : // default allocator). The caller owns it and frees it, values included, with
     184              : // cjson_destroy(). NULL when the allocation fails or a 65th distinct
     185              : // allocator would be needed.
     186              : cjson cjson_create_dictionary_mp(ccol_memmgmt_procs *mp);
     187              : 
     188              : // Creates an empty CJSON_DICTIONARY node with the default allocator; fill it
     189              : // with cjson_dictionary_set(). The caller owns it and frees it, values
     190              : // included, with cjson_destroy(). NULL when the allocation fails.
     191           48 : static inline cjson cjson_create_dictionary(void) {
     192           48 :   return cjson_create_dictionary_mp(NULL);
     193              : }
     194              : 
     195              : // Parses the NUL-terminated JSON text json_str into a tree, for a caller that
     196              : // reads JSON. mp is the allocator of every node (NULL for the default). Gives
     197              : // the root, which the caller owns and frees with cjson_destroy(), or NULL when
     198              : // the text isn't valid JSON (ill-formed UTF-8 included), nests more than 500
     199              : // containers, or memory runs out. On success *err_str becomes NULL.
     200              : // On failure it points at a printable ASCII message (input bytes outside
     201              : // printable ASCII appear as 0xNN) that the library owns in per-thread storage:
     202              : // never free it, and copy it if you need it past the next failing parse on the
     203              : // same thread. When the thread can't keep a buffer the message is a fixed
     204              : // text. err_str may be NULL. Numbers always use '.' whatever the LC_NUMERIC
     205              : // locale.
     206              : cjson cjson_parse_mp(const char *json_str, char **err_str,
     207              :                      ccol_memmgmt_procs *mp);
     208              : 
     209              : // Parses the NUL-terminated JSON text json_str into a tree, with the default
     210              : // allocator. Gives the root, which the caller owns and frees with
     211              : // cjson_destroy(), or NULL when the text isn't valid JSON (ill-formed UTF-8
     212              : // included), nests more than 500 containers, or memory runs out. On success
     213              : // *err_str becomes NULL; on failure it points at a printable ASCII message
     214              : // that the library owns per thread: Never free it, and copy it to keep it past
     215              : // the next failing parse on the same thread. err_str may be NULL. Numbers
     216              : // always use '.' whatever the LC_NUMERIC locale.
     217         1470 : static inline cjson cjson_parse(const char *json_str, char **err_str) {
     218         1461 :   return cjson_parse_mp(json_str, err_str, NULL);
     219              : }
     220              : 
     221              : // Parses exactly len bytes of JSON text at json_str, which needn't end with a
     222              : // NUL, into a tree. mp is the allocator of every node (NULL for the default).
     223              : // Gives the root, which the caller owns and frees with cjson_destroy(), or NULL
     224              : // when the text isn't valid JSON (ill-formed UTF-8 included), nests more than
     225              : // 500 containers, or memory runs out. On success *err_str becomes NULL; on
     226              : // failure it points at a printable ASCII message that the library owns per
     227              : // thread: Never free it, and copy it to keep it past the next failing parse on
     228              : // the same thread. err_str may be NULL.
     229              : cjson cjson_parse_n_mp(const char *json_str, size_t len, char **err_str,
     230              :                        ccol_memmgmt_procs *mp);
     231              : 
     232              : // Parses exactly len bytes of JSON text at json_str, which needn't end with a
     233              : // NUL, into a tree with the default allocator. Gives the root, which the caller
     234              : // owns and frees with cjson_destroy(), or NULL when the text isn't valid JSON
     235              : // (ill-formed UTF-8 included), nests more than 500 containers, or memory runs
     236              : // out. On success *err_str becomes NULL; on failure it points at a printable
     237              : // ASCII message that the library owns per thread: Never free it, and copy it
     238              : // to keep it past the next failing parse on the same thread. err_str may be
     239              : // NULL.
     240         5789 : static inline cjson cjson_parse_n(const char *json_str, size_t len,
     241              :                                   char **err_str) {
     242         5789 :   return cjson_parse_n_mp(json_str, len, err_str, NULL);
     243              : }
     244              : 
     245              : // Writes the subtree at node as compact JSON text, for a caller that stores or
     246              : // sends a tree; a NULL node gives "null". Members come out in insertion order,
     247              : // and the text is valid UTF-8 with '.' as the decimal point in every locale.
     248              : // The buffer comes from the allocator of node: Free it with
     249              : // cjson_serialize_free() for the default allocator and with
     250              : // cjson_serialize_free_mp() and the same mp otherwise. Gives NULL when an
     251              : // allocation fails or the subtree is nested deeper than 500 levels.
     252              : char *cjson_serialize(cjson node);
     253              : 
     254              : // Writes the subtree at node as JSON text for a person to read, one member or
     255              : // element per line, indented by indent spaces per level (0 means 4); a NULL
     256              : // node gives "null". Members come out in insertion order, and the decimal point
     257              : // is '.' in every locale. The buffer comes from the allocator of node: Free it
     258              : // with cjson_serialize_free() for the default allocator and with
     259              : // cjson_serialize_free_mp() and the same mp otherwise. Gives NULL when an
     260              : // allocation fails or the subtree is nested deeper than 500 levels.
     261              : char *cjson_serialize_pretty(cjson node, unsigned int indent);
     262              : 
     263              : // Frees a buffer that cjson_serialize() or cjson_serialize_pretty() gave. mp
     264              : // must be the allocator the tree was built with (NULL for the default). s may
     265              : // be NULL, and the call then does nothing.
     266              : void cjson_serialize_free_mp(char *s, ccol_memmgmt_procs *mp);
     267              : 
     268              : // Frees a buffer that cjson_serialize() or cjson_serialize_pretty() gave for a
     269              : // tree built with the default allocator; a tree with its own allocator needs
     270              : // cjson_serialize_free_mp(). s may be NULL, and the call then does nothing.
     271        20201 : static inline void cjson_serialize_free(char *s) {
     272        20173 :   cjson_serialize_free_mp(s, NULL);
     273            2 : }
     274              : 
     275              : // Gives the type tag of node (CJSON_NULL for a NULL node), so a caller can
     276              : // check a node before it reads it.
     277              : cjson_node_type cjson_type(cjson node);
     278              : 
     279              : // Gives the name of the type of node, such as "CJSON_LIST", for an error
     280              : // message; a NULL node gives "CJSON_NULL". The string is a literal that lives
     281              : // as long as the program: Never free or change it.
     282            8 : static inline const char *cjson_type_str(cjson node) {
     283            8 :   switch (cjson_type(node)) {
     284              :     case CJSON_NULL:
     285              :       return "CJSON_NULL";
     286            1 :     case CJSON_BOOL:
     287            1 :       return "CJSON_BOOL";
     288            1 :     case CJSON_INTEGER:
     289            1 :       return "CJSON_INTEGER";
     290            1 :     case CJSON_FLOAT:
     291            1 :       return "CJSON_FLOAT";
     292            1 :     case CJSON_STRING:
     293            1 :       return "CJSON_STRING";
     294            1 :     case CJSON_LIST:
     295            1 :       return "CJSON_LIST";
     296            1 :     case CJSON_DICTIONARY:
     297            1 :       return "CJSON_DICTIONARY";
     298            0 :     default:
     299            0 :       return "CJSON_UNKNOWN";
     300              :   }
     301              : }
     302              : 
     303              : // Gives the value of a CJSON_BOOL node. Ends the program with a fatal error
     304              : // when node is NULL or of another type, so check cjson_type() first when the
     305              : // type isn't known.
     306              : bool cjson_bool_val(cjson node);
     307              : 
     308              : // Gives the value of a CJSON_INTEGER node. A NULL node or a node of another
     309              : // type is a fatal error that ends the program; check cjson_type() first when
     310              : // you aren't sure.
     311              : long long cjson_int_val(cjson node);
     312              : 
     313              : // Gives the value of a CJSON_FLOAT node. For a NULL node or a node of another
     314              : // type it ends the program with a fatal error, so check cjson_type() first
     315              : // when the type isn't known.
     316              : double cjson_double_val(cjson node);
     317              : 
     318              : // Gives the text of a CJSON_STRING node, always valid UTF-8. The string stays
     319              : // owned by the node: Don't free it. It's valid until the node gets a new value
     320              : // or is removed, replaced or destroyed. A NULL node or a node of another type
     321              : // is a fatal error that ends the program; check cjson_type() first when needed.
     322              : const char *cjson_str_val(cjson node);
     323              : 
     324              : // Gives the number of elements of a CJSON_LIST node, for a caller that walks it
     325              : // by index. Ends the program with a fatal error when node is NULL or isn't a
     326              : // list.
     327              : size_t cjson_list_size(cjson node);
     328              : 
     329              : // Gives the number of keys of a CJSON_DICTIONARY node. Ends the program with a
     330              : // fatal error when node is NULL or isn't a dictionary.
     331              : size_t cjson_dictionary_size(cjson node);
     332              : 
     333              : // Appends child to the list arr, which takes ownership on success; it's how a
     334              : // caller fills a list. child must be a new node or a new clone; a borrowed
     335              : // reference, a node already attached somewhere, arr itself or an ancestor of
     336              : // arr is refused. Those refusals, a NULL argument and a wrong type return
     337              : // ccol_invalid_args and leave child untouched. ccol_not_enough_memory (also
     338              : // when the cycle check runs out of memory) and ccol_container_full mean
     339              : // ownership moved and child is destroyed.
     340              : ccol_retval cjson_list_push(cjson arr, cjson child);
     341              : 
     342              : // Gives element index of the list arr, for a caller that reads a list; NULL
     343              : // when arr is NULL or not a list, or index is out of range. The node is
     344              : // borrowed: The list keeps owning it, and it stays valid until the tree
     345              : // changes. Never destroy it or attach it elsewhere; cjson_clone() it instead.
     346              : cjson cjson_list_get(cjson arr, size_t index);
     347              : 
     348              : // Inserts key with child in obj, or replaces its value; it's how a caller fills
     349              : // a dictionary. On success obj owns child, and the dictionary stores its own
     350              : // copy of key. A replace deep-frees the old value and keeps the key's place in
     351              : // the insertion order; passing back the node that key already holds does
     352              : // nothing and succeeds. ccol_invalid_args (a NULL argument, obj not a
     353              : // dictionary, a key that isn't UTF-8, child already attached somewhere or
     354              : // borrowed from a tree, child == obj, or obj inside the subtree of child)
     355              : // leaves child untouched and with the caller. ccol_not_enough_memory (also
     356              : // when the cycle check runs out of memory) and ccol_container_full mean
     357              : // ownership moved and child is destroyed.
     358              : ccol_retval cjson_dictionary_set(cjson obj, const char *key, cjson child);
     359              : 
     360              : // Gives the value of key in the dictionary obj, for a caller that reads a
     361              : // dictionary; NULL when the key is absent, obj or key is NULL, or obj isn't a
     362              : // dictionary. The node is borrowed: The dictionary keeps owning it, and it
     363              : // stays valid until the tree changes. Never destroy it or attach it elsewhere.
     364              : cjson cjson_dictionary_get(cjson obj, const char *key);
     365              : 
     366              : // Removes element index from the list arr and deep-frees it; the later
     367              : // elements move left. Returns ccol_success, or ccol_invalid_args for a NULL or
     368              : // non-list arr or an index out of range.
     369              : ccol_retval cjson_list_remove(cjson arr, size_t index);
     370              : 
     371              : // Removes the entry of key from the dictionary obj and deep-frees its value;
     372              : // the other members keep their order. Returns ccol_success, ccol_invalid_args
     373              : // when obj or key is NULL or obj isn't a dictionary, and ccol_key_not_found
     374              : // when the key is absent.
     375              : ccol_retval cjson_dictionary_remove(cjson obj, const char *key);
     376              : 
     377              : // A cursor over a dictionary in insertion order, which the caller owns; it
     378              : // allocates nothing and can't fail. A key keeps the place where it first
     379              : // entered (a repeated key in parsed text keeps its first place and its last
     380              : // value). The cursor holds the successor of the current member and stays valid
     381              : // across any change that leaves that successor in place: Replacing values,
     382              : // removing other members, inserting (whether this iteration sees a new key is
     383              : // unspecified). Removing the successor or destroying the dictionary invalidates
     384              : // it. After cjson_dictionary_set() replaces the current value, value names
     385              : // freed memory; cjson_set() updates the node in place.
     386              : typedef struct cjson_dictionary_iter {
     387              :   // The current member; both NULL once the iteration is over.
     388              :   const char *key;
     389              :   cjson value;
     390              :   // Private: The member that the next step reads.
     391              :   const void *cjson__next;
     392              : } cjson_dictionary_iter;
     393              : 
     394              : // Starts the cursor it on dict and steps onto its first member, so a caller can
     395              : // walk a dictionary in insertion order. Gives false (with key and value NULL)
     396              : // for an empty, NULL or non-dictionary dict, and false for a NULL it.
     397              : //
     398              : //   cjson_dictionary_iter it;
     399              : //   for (bool ok = cjson_dictionary_first(obj, &it); ok;
     400              : //        ok = cjson_dictionary_next(&it))
     401              : //     printf("%s: %s\n", it.key, cjson_type_str(it.value));
     402              : bool cjson_dictionary_first(cjson dict, cjson_dictionary_iter *it);
     403              : 
     404              : // Steps the cursor it, which cjson_dictionary_first() started, onto the next
     405              : // member in insertion order and gives true, with it->key and it->value
     406              : // borrowed from the dictionary. Gives false (key and value NULL) after the
     407              : // last member or for a NULL it. Removing the member that the cursor reads next,
     408              : // or destroying the dictionary, invalidates the cursor.
     409              : bool cjson_dictionary_next(cjson_dictionary_iter *it);
     410              : 
     411              : // Makes a deep copy of the subtree at node with node's allocator, for a caller
     412              : // that wants an independent tree (for example to attach a copy of a borrowed
     413              : // node). Dictionaries keep their member order. Gives the copy, which the
     414              : // caller owns and frees with cjson_destroy(), or NULL for a NULL node, when an
     415              : // allocation fails, or when the subtree is nested deeper than 500 levels.
     416              : cjson cjson_clone(cjson node);
     417              : 
     418              : // Declares an uninitialized cjson named var_name; assign it, for example from
     419              : // cjson_parse() or a cjson_create_*() call, before you use it. It exists so
     420              : // cjson follows the naming convention of the other containers.
     421              : #define cjson_declare(var_name) cjson var_name
     422              : 
     423              : // Declares a cjson named var_name, set to NULL, whose tree is destroyed at the
     424              : // end of its scope on every way out, so a function with several exits can't
     425              : // leak its tree. Store only a tree the caller owns in it, never a borrowed
     426              : // node from cjson_get() or another getter. Needs GCC or Clang.
     427              : #define cjson_declare_scoped(var_name) \
     428              :   cjson var_name ccol__destructor(cjson__destroy_cleanup) = NULL
     429              : 
     430              : // Internal: Frees the tree at node. It's the body of cjson_destroy(); use the
     431              : // macro.
     432              : void cjson__destroy(cjson node);
     433              : 
     434              : // Internal: Destroys *node and sets it to NULL. It's the cleanup function that
     435              : // cjson_declare_scoped() attaches.
     436              : static inline void cjson__destroy_cleanup(cjson *node) {
     437              :   if (node && *node) {
     438              :     cjson__destroy(*node);
     439              :     *node = NULL;
     440              :   }
     441              : }
     442              : 
     443              : // Frees the tree at node (each node with its own allocator) and sets the handle
     444              : // to NULL, so a later use is a plain NULL instead of a dangling pointer. NULL
     445              : // is safe. node is evaluated once and must be a modifiable lvalue. Destroy
     446              : // only a root the caller owns, never a borrowed node or one attached to a
     447              : // parent; remove a child with cjson_list_remove() or cjson_dictionary_remove().
     448              : #define cjson_destroy(node)      \
     449              :   ccol__cjson_destroy_impl(node, \
     450              :                            ccol__uniq(ccol__cjson_destroy_slot, __COUNTER__))
     451              : 
     452              : // Internal: The body of cjson_destroy(). slot is a ccol__uniq() name for the
     453              : // pointer to node, so nested destroy macros stay -Wshadow clean.
     454              : #define ccol__cjson_destroy_impl(node, slot) \
     455              :   do {                                       \
     456              :     __typeof__(node) *slot = &(node);        \
     457              :     if (*slot) {                             \
     458              :       cjson__destroy(*slot);                 \
     459              :       *slot = NULL;                          \
     460              :     }                                        \
     461              :   } while (0)
     462              : 
     463              : // Internal: Gives the node at path, root for an empty path, or NULL; it's the
     464              : // back-end of cjson_get(). A path of 256 bytes or more is copied with the
     465              : // allocator of root, and NULL also means that copy failed.
     466              : cjson cjson__get(cjson root, const char *path);
     467              : 
     468              : // Internal: Removes and deep-frees the node at path; it's the back-end of
     469              : // cjson_remove(). It walks to the parent and removes the leaf through
     470              : // cjson_dictionary_remove() or cjson_list_remove(). Errors follow the path
     471              : // rules at the top of this header; ccol_not_enough_memory when an allocation
     472              : // fails.
     473              : ccol_retval cjson__remove(cjson root, const char *path);
     474              : 
     475              : // Internal: Writes a scalar to the leaf at path; it's the back-end of
     476              : // cjson_set(). type is the JSON type, raw points at the C value of raw_size
     477              : // bytes, and is_signed says whether an integer source was signed. raw_size is
     478              : // checked against type before anything is read, because a direct call can pass
     479              : // a narrower payload. The leaf is created when absent (its parent must exist)
     480              : // and any old value is deep-freed. It returns ccol_invalid_args for the path
     481              : // errors at the top of this header, an unsupported type, a size mismatch, a
     482              : // string that isn't UTF-8, a void * that isn't NULL, and a NULL raw for any
     483              : // type but CJSON_NULL; ccol_key_not_found for an absent parent or an
     484              : // out-of-range leaf index; ccol_not_enough_memory; ccol_container_full for a
     485              : // new key in a full dictionary.
     486              : ccol_retval cjson__set_typed(cjson root, const char *path, cjson_node_type type,
     487              :                              void *raw, size_t raw_size, bool is_signed);
     488              : 
     489              : // What cjson__type_of() gives for a type that cjson_set() refuses (long double,
     490              : // a struct). It's on purpose not a real cjson_node_type, so the type check in
     491              : // cjson__set_typed() refuses it; CJSON_NULL as a default would pass that check.
     492              : // NULL and the C23 nullptr have their own association, because passing them is
     493              : // intended.
     494              : #define CJSON__TYPE_UNSUPPORTED ((cjson_node_type)0x7f)
     495              : 
     496              : // Evaluates to the cjson_node_type that the compile-time type of val maps to,
     497              : // or CJSON__TYPE_UNSUPPORTED; cjson_set() uses it to tell the back-end what
     498              : // kind of value it passes. val is not evaluated. The Clang form silences the
     499              : // warning about unreachable _Generic associations.
     500              : #if defined(CCOL__CLANG_GENERIC_ASSOC_WARNING)
     501              : #define cjson__type_of(val) \
     502              :   cjson__type_of_impl((val), ccol__uniq(cjson__type_of_tmp, __COUNTER__))
     503              : #define cjson__type_of_impl(val, cjson__type_of_name)                       \
     504              :   ({                                                                        \
     505              :     _Pragma("GCC diagnostic push");                                         \
     506              :     _Pragma("GCC diagnostic ignored \"-Wunreachable-code-generic-assoc\""); \
     507              :     cjson_node_type cjson__type_of_name = _Generic((val),                   \
     508              :         bool: CJSON_BOOL,                                                   \
     509              :         char: CJSON_INTEGER,                                                \
     510              :         signed char: CJSON_INTEGER,                                         \
     511              :         short: CJSON_INTEGER,                                               \
     512              :         int: CJSON_INTEGER,                                                 \
     513              :         long: CJSON_INTEGER,                                                \
     514              :         long long: CJSON_INTEGER,                                           \
     515              :         unsigned char: CJSON_INTEGER,                                       \
     516              :         unsigned short: CJSON_INTEGER,                                      \
     517              :         unsigned int: CJSON_INTEGER,                                        \
     518              :         unsigned long: CJSON_INTEGER,                                       \
     519              :         unsigned long long: CJSON_INTEGER,                                  \
     520              :         float: CJSON_FLOAT,                                                 \
     521              :         double: CJSON_FLOAT,                                                \
     522              :         char *: CJSON_STRING,                                               \
     523              :         const char *: CJSON_STRING,                                         \
     524              :         CCOL__NULLPTR_ASSOC(CJSON_NULL) void *: CJSON_NULL,                 \
     525              :         default: CJSON__TYPE_UNSUPPORTED);                                  \
     526              :     _Pragma("GCC diagnostic pop");                                          \
     527              :     cjson__type_of_name;                                                    \
     528              :   })
     529              : #else
     530              : #define cjson__type_of(val)                               \
     531              :   _Generic((val),                                         \
     532              :       bool: CJSON_BOOL,                                   \
     533              :       char: CJSON_INTEGER,                                \
     534              :       signed char: CJSON_INTEGER,                         \
     535              :       short: CJSON_INTEGER,                               \
     536              :       int: CJSON_INTEGER,                                 \
     537              :       long: CJSON_INTEGER,                                \
     538              :       long long: CJSON_INTEGER,                           \
     539              :       unsigned char: CJSON_INTEGER,                       \
     540              :       unsigned short: CJSON_INTEGER,                      \
     541              :       unsigned int: CJSON_INTEGER,                        \
     542              :       unsigned long: CJSON_INTEGER,                       \
     543              :       unsigned long long: CJSON_INTEGER,                  \
     544              :       float: CJSON_FLOAT,                                 \
     545              :       double: CJSON_FLOAT,                                \
     546              :       char *: CJSON_STRING,                               \
     547              :       const char *: CJSON_STRING,                         \
     548              :       CCOL__NULLPTR_ASSOC(CJSON_NULL) void *: CJSON_NULL, \
     549              :       default: CJSON__TYPE_UNSUPPORTED)
     550              : #endif
     551              : 
     552              : // True when plain char is signed on this platform, so cjson__is_signed() can
     553              : // classify a char value.
     554              : #if defined(__CHAR_UNSIGNED__)
     555              : #define CJSON__CHAR_SIGNED false
     556              : #else
     557              : #define CJSON__CHAR_SIGNED true
     558              : #endif
     559              : 
     560              : // Evaluates to true when val has a signed integer type; cjson_set() passes it
     561              : // on so the back-end widens the integer correctly. val is not evaluated.
     562              : #if defined(CCOL__CLANG_GENERIC_ASSOC_WARNING)
     563              : #define cjson__is_signed(val) \
     564              :   cjson__is_signed_impl((val), ccol__uniq(cjson__is, __COUNTER__))
     565              : #define cjson__is_signed_impl(val, cjson__is_name)                          \
     566              :   ({                                                                        \
     567              :     _Pragma("GCC diagnostic push");                                         \
     568              :     _Pragma("GCC diagnostic ignored \"-Wunreachable-code-generic-assoc\""); \
     569              :     bool cjson__is_name = _Generic((val),                                   \
     570              :         char: CJSON__CHAR_SIGNED,                                           \
     571              :         signed char: true,                                                  \
     572              :         short: true,                                                        \
     573              :         int: true,                                                          \
     574              :         long: true,                                                         \
     575              :         long long: true,                                                    \
     576              :         default: false);                                                    \
     577              :     _Pragma("GCC diagnostic pop");                                          \
     578              :     cjson__is_name;                                                         \
     579              :   })
     580              : #else
     581              : #define cjson__is_signed(val)   \
     582              :   _Generic((val),               \
     583              :       char: CJSON__CHAR_SIGNED, \
     584              :       signed char: true,        \
     585              :       short: true,              \
     586              :       int: true,                \
     587              :       long: true,               \
     588              :       long long: true,          \
     589              :       default: false)
     590              : #endif
     591              : 
     592              : // Evaluates to the node at the dot-separated path in the tree root, so a caller
     593              : // can read a deep value in one call. A plain component is a dictionary key,
     594              : // "#N" is a zero-based index on a list, and "\." and "\\" escape a dot and a
     595              : // backslash. A NULL or empty path gives root. The node is borrowed: The tree
     596              : // keeps owning it, and it stays valid until the tree changes. Gives NULL for a
     597              : // NULL root, an absent component, a malformed path or one whose shape doesn't
     598              : // fit the tree, and when the copy of a path of 256 bytes or more fails.
     599              : //
     600              : //   cjson city = cjson_get(doc, "users.#0.address.city");
     601              : #define cjson_get(root, path) cjson__get((root), (path))
     602              : 
     603              : // Writes the C scalar val to the leaf at path in the tree root, so a caller can
     604              : // set a deep value in one call; evaluates to a ccol_retval. val can be a
     605              : // bool, any integer type, float, double, or a char pointer, array or literal
     606              : // (all give CJSON_STRING); NULL or nullptr gives CJSON_NULL, and any other
     607              : // void * is ccol_invalid_args. Before C23 true is the int 1, so write
     608              : // (bool)true for a CJSON_BOOL. A bit-field doesn't compile; cast it. An
     609              : // unsigned value above LLONG_MAX is stored as the nearest CJSON_FLOAT, as the
     610              : // parser reads the same literal. The leaf is created when absent, but its
     611              : // parent must exist; an existing leaf is updated in place, takes the new type,
     612              : // and an old subtree is deep-freed. path is dot-separated, with #N for a list
     613              : // index and "\." for a dot inside a key. Gives ccol_success; ccol_invalid_args
     614              : // for a NULL root, an empty or malformed path, a path whose shape doesn't fit
     615              : // the tree, an unsupported type, a string or key that isn't UTF-8, or a double
     616              : // that isn't finite; ccol_key_not_found when a parent component or a leaf list
     617              : // index is absent; ccol_not_enough_memory; ccol_container_full for a new key in
     618              : // a full dictionary.
     619              : //
     620              : //   cjson_set(doc, "users.#0.active", (bool)true);
     621              : //   cjson_set(doc, "users.#0.score", 99);
     622              : #define cjson_set(root, path, val) \
     623              :   cjson__set_impl((root), (path), (val), ccol__uniq(cjson__sv, __COUNTER__))
     624              : 
     625              : // Internal: The body of cjson_set(). It copies val with __auto_type (arrays
     626              : // decay and top-level qualifiers go) into a temporary named cjson__sv_name, a
     627              : // ccol__uniq() name so the macro nests under -Wshadow, and evaluates to the
     628              : // result of cjson__set_typed() on that copy.
     629              : #define cjson__set_impl(root, path, val, cjson__sv_name)              \
     630              :   ({                                                                  \
     631              :     __auto_type cjson__sv_name = (val);                               \
     632              :     cjson__set_typed((root), (path), cjson__type_of(cjson__sv_name),  \
     633              :                      (void *)&cjson__sv_name, sizeof(cjson__sv_name), \
     634              :                      cjson__is_signed(cjson__sv_name));               \
     635              :   })
     636              : 
     637              : // Removes the node at path from the tree root and deep-frees it, so a caller
     638              : // can drop a deep value in one call. path is dot-separated, with #N for a list
     639              : // index and "\." for a dot inside a key; under a list parent the leaf must be
     640              : // a #N component. Evaluates to ccol_success, ccol_invalid_args for a NULL root
     641              : // or path, an empty or malformed path or one whose shape doesn't fit the tree,
     642              : // ccol_key_not_found when a well-formed component is absent, or
     643              : // ccol_not_enough_memory.
     644              : #define cjson_remove(root, path) cjson__remove((root), (path))
     645              : 
     646              : #pragma GCC visibility pop
        

Generated by: LCOV version 2.0-1