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>
19 static void json_init(struct json_context *js)
21 mp_save(js->pool, &js->init_state);
22 js->trivial_token = json_new_node(js, JSON_INVALID);
25 struct json_context *json_new(void)
27 struct mempool *mp = mp_new(4096);
28 struct json_context *js = mp_alloc_zero(mp, sizeof(*js));
34 void json_delete(struct json_context *js)
39 void json_reset(struct json_context *js)
41 struct mempool *mp = js->pool;
42 mp_restore(mp, &js->init_state);
43 bzero(js, sizeof(*js));
48 void json_push(struct json_context *js)
50 ASSERT(!js->next_token);
54 void json_pop(struct json_context *js)
56 ASSERT(!js->next_token);
60 struct json_node *json_new_node(struct json_context *js, enum json_node_type type)
62 struct json_node *n = mp_alloc_fast(js->pool, sizeof(*n));
67 struct json_node *json_new_number(struct json_context *js, double value)
69 ASSERT(isfinite(value));
70 struct json_node *n = json_new_node(js, JSON_NUMBER);
75 #define JSON_NUM_TO(_type, _min, _max) \
76 bool json_number_to_##_type(struct json_node *num, _type *dest) \
78 if (num->type == JSON_NUMBER && \
79 num->number >= _min && num->number <= _max) \
81 *dest = num->number; \
87 JSON_NUM_TO(int, INT_MIN, INT_MAX)
88 JSON_NUM_TO(uint, 0, UINT_MAX)
89 JSON_NUM_TO(s64, INT64_MIN, INT64_MAX)
90 JSON_NUM_TO(u64, 0, UINT64_MAX)
92 struct json_node *json_new_array(struct json_context *js)
94 struct json_node *n = json_new_node(js, JSON_ARRAY);
95 GARY_INIT_SPACE_ALLOC(n->elements, 4, mp_get_allocator(js->pool));
99 void json_array_append(struct json_node *array, struct json_node *elt)
101 ASSERT(array->type == JSON_ARRAY);
102 *GARY_PUSH(array->elements) = elt;
105 struct json_node *json_new_object(struct json_context *js)
107 struct json_node *n = json_new_node(js, JSON_OBJECT);
108 GARY_INIT_SPACE_ALLOC(n->pairs, 4, mp_get_allocator(js->pool));
112 void json_object_set(struct json_node *n, const char *key, struct json_node *value)
114 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
115 if (!strcmp(n->pairs[i].key, key))
118 n->pairs[i].value = value;
121 n->pairs[i] = n->pairs[GARY_SIZE(n->pairs) - 1];
129 struct json_pair *p = GARY_PUSH(n->pairs);
135 struct json_node *json_object_get(struct json_node *n, const char *key)
137 for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
138 if (!strcmp(n->pairs[i].key, key))
139 return n->pairs[i].value;