2 * UCW JSON Library -- Data Representation
4 * (c) 2015 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
14 #include <ucw/mempool.h>
15 #include <ucw-json/json.h>
17 struct json_context *json_new(void)
19 struct mempool *mp = mp_new(4096);
20 struct json_context *js = mp_alloc_zero(mp, sizeof(*js));
22 mp_save(mp, &js->init_state);
26 void json_delete(struct json_context *js)
31 void json_reset(struct json_context *js)
33 mp_restore(js->pool, &js->init_state);
37 struct json_node *json_new_node(struct json_context *js, enum json_node_type type)
39 struct json_node *n = mp_alloc_fast(js->pool, sizeof(*n));
44 struct json_node *json_new_array(struct json_context *js)
46 struct json_node *n = json_new_node(js, JSON_ARRAY);
47 GARY_INIT_SPACE_ALLOC(n->elements, 4, mp_get_allocator(js->pool));
51 void json_array_append(struct json_node *array, struct json_node *elt)
53 ASSERT(array->type == JSON_ARRAY);
54 *GARY_PUSH(array->elements) = elt;
57 struct json_node *json_new_object(struct json_context *js)
59 struct json_node *n = json_new_node(js, JSON_OBJECT);
60 GARY_INIT_SPACE_ALLOC(n->pairs, 4, mp_get_allocator(js->pool));
64 void json_object_set(struct json_node *n, const char *key, struct json_node *value)
66 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
67 if (!strcmp(n->pairs[i].key, key))
70 n->pairs[i].value = value;
73 n->pairs[i] = n->pairs[GARY_SIZE(n->pairs) - 1];
81 struct json_pair *p = GARY_PUSH(n->pairs);
87 struct json_node *json_object_get(struct json_node *n, const char *key)
89 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
90 if (!strcmp(n->pairs[i].key, key))
91 return n->pairs[i].value;