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>
17 static void json_init(struct json_context *js)
19 mp_save(js->pool, &js->init_state);
20 js->trivial_token = json_new_node(js, JSON_INVALID);
23 struct json_context *json_new(void)
25 struct mempool *mp = mp_new(4096);
26 struct json_context *js = mp_alloc_zero(mp, sizeof(*js));
32 void json_delete(struct json_context *js)
37 void json_reset(struct json_context *js)
39 struct mempool *mp = js->pool;
40 mp_restore(mp, &js->init_state);
41 bzero(js, sizeof(*js));
46 void json_push(struct json_context *js)
48 ASSERT(!js->next_token);
52 void json_pop(struct json_context *js)
54 ASSERT(!js->next_token);
58 struct json_node *json_new_node(struct json_context *js, enum json_node_type type)
60 struct json_node *n = mp_alloc_fast(js->pool, sizeof(*n));
65 struct json_node *json_new_number(struct json_context *js, double value)
67 ASSERT(isfinite(value));
68 struct json_node *n = json_new_node(js, JSON_NUMBER);
73 struct json_node *json_new_array(struct json_context *js)
75 struct json_node *n = json_new_node(js, JSON_ARRAY);
76 GARY_INIT_SPACE_ALLOC(n->elements, 4, mp_get_allocator(js->pool));
80 void json_array_append(struct json_node *array, struct json_node *elt)
82 ASSERT(array->type == JSON_ARRAY);
83 *GARY_PUSH(array->elements) = elt;
86 struct json_node *json_new_object(struct json_context *js)
88 struct json_node *n = json_new_node(js, JSON_OBJECT);
89 GARY_INIT_SPACE_ALLOC(n->pairs, 4, mp_get_allocator(js->pool));
93 void json_object_set(struct json_node *n, const char *key, struct json_node *value)
95 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
96 if (!strcmp(n->pairs[i].key, key))
99 n->pairs[i].value = value;
102 n->pairs[i] = n->pairs[GARY_SIZE(n->pairs) - 1];
110 struct json_pair *p = GARY_PUSH(n->pairs);
116 struct json_node *json_object_get(struct json_node *n, const char *key)
118 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
119 if (!strcmp(n->pairs[i].key, key))
120 return n->pairs[i].value;