| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- /* ujson: small arena JSON DOM parser for ring-3 commands.
- *
- * The caller owns all memory: a node pool and a string pool. Parsing never
- * allocates; it fails cleanly when either pool is exhausted. Strings (keys
- * and values) are unescaped into the string pool as NUL-terminated UTF-8
- * (\uXXXX escapes and surrogate pairs are decoded). Numbers keep their raw
- * text; ujson_int() converts the integer part.
- *
- * Pure freestanding C with no includes, so the host test (ujson_test.c) links
- * the same file. */
- #ifndef UJSON_H
- #define UJSON_H
- #define UJSON_NULL 0
- #define UJSON_FALSE 1
- #define UJSON_TRUE 2
- #define UJSON_NUMBER 3
- #define UJSON_STRING 4
- #define UJSON_ARRAY 5
- #define UJSON_OBJECT 6
- #define UJSON_MAX_DEPTH 48
- struct ujson_node {
- unsigned char type;
- const char *key; /* member name inside an object, else 0 */
- const char *str; /* STRING: decoded text; NUMBER: raw text */
- unsigned int len; /* STRING/NUMBER: bytes; ARRAY/OBJECT: count */
- int child; /* first child index, -1 none */
- int next; /* next sibling index, -1 none */
- };
- struct ujson {
- struct ujson_node *nodes;
- unsigned int cap, n;
- char *sbuf;
- unsigned int scap, sn;
- const char *error; /* static message after a failed parse */
- unsigned int error_pos;
- };
- /* A string pool of len + 2 * nodes bytes is always large enough. */
- void ujson_init(struct ujson *j, struct ujson_node *nodes, unsigned int cap,
- char *sbuf, unsigned int scap);
- /* Returns the root node index (0) or -1 on error (j->error says why). */
- int ujson_parse(struct ujson *j, const char *src, unsigned int len);
- int ujson_type(const struct ujson *j, int idx);
- /* Object member by name; -1 when idx is not an object or has no member. */
- int ujson_get(const struct ujson *j, int idx, const char *key);
- /* Array/object iteration: first child and next sibling, -1 at the end. */
- int ujson_first(const struct ujson *j, int idx);
- int ujson_next(const struct ujson *j, int idx);
- unsigned int ujson_count(const struct ujson *j, int idx);
- /* "" when idx is not a string (or -1). */
- const char *ujson_str(const struct ujson *j, int idx);
- /* Convenience: ujson_str(ujson_get(obj, key)). */
- const char *ujson_get_str(const struct ujson *j, int obj, const char *key);
- /* Integer part of a number (or numeric string); def otherwise. */
- long ujson_int(const struct ujson *j, int idx, long def);
- /* 1 for true, a non-zero number or a non-empty string; 0 otherwise. */
- int ujson_truthy(const struct ujson *j, int idx);
- /* Write s as a JSON string literal (with the quotes). Returns the length
- * written, or -1 when it does not fit in cap (including the NUL). */
- int ujson_escape(char *out, unsigned int cap, const char *s);
- #endif
|