]> mj.ucw.cz Git - libucw.git/blob - ucw-json/json.c
JSON: Rudimentary formatting
[libucw.git] / ucw-json / json.c
1 /*
2  *      UCW JSON Library -- Data Representation
3  *
4  *      (c) 2015 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/gary.h>
12 #include <ucw/mempool.h>
13 #include <ucw-json/json.h>
14
15 struct json_context *json_new(void)
16 {
17   struct mempool *mp = mp_new(4096);
18   struct json_context *js = mp_alloc_zero(mp, sizeof(*js));
19   js->pool = mp;
20   mp_save(mp, &js->init_state);
21   return js;
22 }
23
24 void json_delete(struct json_context *js)
25 {
26   mp_delete(js->pool);
27 }
28
29 void json_reset(struct json_context *js)
30 {
31   mp_restore(js->pool, &js->init_state);
32 }
33
34
35 struct json_node *json_new_node(struct json_context *js, enum json_node_type type)
36 {
37   struct json_node *n = mp_alloc_fast(js->pool, sizeof(*n));
38   n->type = type;
39   return n;
40 }
41
42 struct json_node *json_new_array(struct json_context *js)
43 {
44   struct json_node *n = json_new_node(js, JSON_ARRAY);
45   GARY_INIT_SPACE_ALLOC(n->elements, 4, mp_get_allocator(js->pool));
46   return n;
47 }
48
49 void json_array_append(struct json_node *array, struct json_node *elt)
50 {
51   ASSERT(array->type == JSON_ARRAY);
52   *GARY_PUSH(array->elements) = elt;
53 }
54
55 struct json_node *json_new_object(struct json_context *js)
56 {
57   struct json_node *n = json_new_node(js, JSON_OBJECT);
58   GARY_INIT_SPACE_ALLOC(n->pairs, 4, mp_get_allocator(js->pool));
59   return n;
60 }
61
62 void json_object_set(struct json_node *n, const char *key, struct json_node *value)
63 {
64   for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
65     if (!strcmp(n->pairs[i].key, key))
66       {
67         if (value)
68           n->pairs[i].value = value;
69         else
70           {
71             n->pairs[i] = n->pairs[GARY_SIZE(n->pairs) - 1];
72             GARY_POP(n->pairs);
73           }
74         return;
75       }
76
77   if (value)
78     {
79       struct json_pair *p = GARY_PUSH(n->pairs);
80       p->key = key;
81       p->value = value;
82     }
83 }
84
85 struct json_node *json_object_get(struct json_node *n, const char *key)
86 {
87   for (size_t i=0; i < GARY_SIZE(n->pairs); i++)
88     if (!strcmp(n->pairs[i].key, key))
89       return n->pairs[i].value;
90   return NULL;
91 }