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.
12 #include <ucw/mempool.h>
13 #include <ucw-json/json.h>
15 static void json_init(struct json_context *js)
17 mp_save(js->pool, &js->init_state);
18 js->trivial_token = json_new_node(js, JSON_INVALID);
21 struct json_context *json_new(void)
23 struct mempool *mp = mp_new(4096);
24 struct json_context *js = mp_alloc_zero(mp, sizeof(*js));
30 void json_delete(struct json_context *js)
35 void json_reset(struct json_context *js)
37 struct mempool *mp = js->pool;
38 mp_restore(mp, &js->init_state);
39 bzero(js, sizeof(*js));
44 void json_push(struct json_context *js)
46 ASSERT(!js->next_token);
50 void json_pop(struct json_context *js)
52 ASSERT(!js->next_token);
56 struct json_node *json_new_node(struct json_context *js, enum json_node_type type)
58 struct json_node *n = mp_alloc_fast(js->pool, sizeof(*n));
63 struct json_node *json_new_array(struct json_context *js)
65 struct json_node *n = json_new_node(js, JSON_ARRAY);
66 GARY_INIT_SPACE_ALLOC(n->elements, 4, mp_get_allocator(js->pool));
70 void json_array_append(struct json_node *array, struct json_node *elt)
72 ASSERT(array->type == JSON_ARRAY);
73 *GARY_PUSH(array->elements) = elt;
76 struct json_node *json_new_object(struct json_context *js)
78 struct json_node *n = json_new_node(js, JSON_OBJECT);
79 GARY_INIT_SPACE_ALLOC(n->pairs, 4, mp_get_allocator(js->pool));
83 void json_object_set(struct json_node *n, const char *key, struct json_node *value)
85 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
86 if (!strcmp(n->pairs[i].key, key))
89 n->pairs[i].value = value;
92 n->pairs[i] = n->pairs[GARY_SIZE(n->pairs) - 1];
100 struct json_pair *p = GARY_PUSH(n->pairs);
106 struct json_node *json_object_get(struct json_node *n, const char *key)
108 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
109 if (!strcmp(n->pairs[i].key, key))
110 return n->pairs[i].value;