-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathjson.c
1958 lines (1604 loc) · 53.6 KB
/
json.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2005-2012 by KoanLogic s.r.l. - All rights reserved.
*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <toolbox/json.h>
#include <toolbox/carpal.h>
#include <toolbox/misc.h>
#include <toolbox/memory.h>
#include <toolbox/lexer.h>
/* Internal representation of any JSON value. */
struct u_json_s
{
u_json_type_t type;
char fqn[U_JSON_FQN_SZ]; /* Fully qualified name of this (sub)object. */
char key[U_TOKEN_SZ]; /* Local name, if applicable (i.e. !anon) */
char val[U_TOKEN_SZ]; /* If applicable, i.e. (!OBJECT && !ARRAY) */
/* Parent container. */
struct u_json_s *parent;
/* Nodes at the same level as this one (if any). */
TAILQ_ENTRY(u_json_s) siblings;
/* Children nodes' list when i.e. (ARRAY || OBJECT). */
TAILQ_HEAD(u_json_chld_s, u_json_s) children;
unsigned int depth; /* Depth of this node in the decoded tree. */
/* Cacheing machinery. */
unsigned int icur, count; /* Aux stuff used when indexing arrays. */
u_hmap_t *map; /* Alias reference to the global cache. */
};
/* Pointer to the name part of .fqn */
#define U_JSON_OBJ_NAME(jo) \
((jo->parent != NULL) ? jo->fqn + strlen(p->fqn) : jo->fqn)
#define U_JSON_OBJ_IS_CONTAINER(jo) \
((jo->type == U_JSON_TYPE_OBJECT) || (jo->type == U_JSON_TYPE_ARRAY))
#define U_JSON_OBJ_IS_BOOL(jo) \
((jo->type == U_JSON_TYPE_TRUE) || (jo->type == U_JSON_TYPE_FALSE))
/* Lexer methods */
static int u_json_match_value (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_number_first (u_lexer_t *jl);
static int u_json_match_number (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_int (u_lexer_t *jl);
static int u_json_match_frac_first (char c);
static int u_json_match_frac (u_lexer_t *jl);
static int u_json_match_exp_first (char c);
static int u_json_match_exp (u_lexer_t *jl);
static int u_json_match_true_first (u_lexer_t *jl);
static int u_json_match_false_first (u_lexer_t *jl);
static int u_json_match_true (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_false (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_null_first (u_lexer_t *jl);
static int u_json_match_null (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_string (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_string_first (u_lexer_t *jl);
static int u_json_match_escaped_unicode (u_lexer_t *jl);
static int u_json_match_object (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_object_first (u_lexer_t *jl);
static int u_json_match_array (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_array_first (u_lexer_t *jl);
static int u_json_match_pair (u_lexer_t *jl, u_json_t *jo);
static int u_json_match_pair_first (u_lexer_t *jl);
/* Lexer misc stuff. */
static int u_json_match_seq (u_lexer_t *jl, u_json_t *jo, int type,
char first, const char *rem, size_t rem_sz);
static const char *u_json_type_str (int type);
/* Objects misc stuff. */
static void u_json_do_print (u_json_t *jo, size_t l, void *opaque);
static void u_json_do_free (u_json_t *jo, size_t l, void *opaque);
static void u_json_do_index (u_json_t *jo, size_t l, void *map);
/* Encode/Decode/Validate. */
static int u_json_do_encode (u_json_t *jo, u_string_t *s);
static int u_json_do_parse (const char *json, u_json_t **pjo,
char status[U_LEXER_ERR_SZ]);
/* Needed by hmap_easy* because we are storing pointer data not owned by the
* hmap. */
static void nopf (void *dummy) { u_unused_args(dummy); return; }
static int u_json_new_container (u_json_type_t type, const char *key,
u_json_t **pjo);
static int u_json_new_atom (u_json_type_t type, const char *key,
const char *val, char check, u_json_t **pjo);
static int u_json_set_depth (u_json_t *jo, unsigned int depth);
/**
\defgroup json JSON
\{
The \ref json module implements a family of routines that allow
encoding, decoding and validation of JSON objects as defined in
<a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>.
\section decode Decoding
A NUL-terminated string in JSON syntax is decoded into its parse
tree by means of the ::u_json_decode function as the showed in the
following snippet:
\code
u_json_t *jo = NULL;
const char *i2 = "[ [ 1, 0 ], [ 0, 1 ] ]";
dbg_err_if (u_json_decode(i2, &jo));
\endcode
\section validate Validating
Should you just need to check the supplied string for syntax compliance
(i.e. without actually creating the syntax tree), the ::u_json_validate
interface can be used:
\code
char status[U_LEXER_ERR_SZ];
if (u_json_validate(i2, status))
u_con("Syntax error: %s", status);
\endcode
You should not use the validating interface on untrusted input.
In fact no maximum nesting depth is enforced on validation -- on the
contrary, the parsing interface has the compile-time define
::U_JSON_MAX_DEPTH for such purpose -- so a malicious user could make your
application stack explode by simply supplying a big-enough string made by
all \c '[' chars.
The intended use of the validating interface is for checking your
hand-crafted JSON strings before pushing them out, i.e. those you've
created without going through all the ::u_json_new -> ::u_json_add ->
::u_json_encode chain.
\section cache Indexing
Once the string has been parsed and (implicitly or explicitly)
validated, should your application request frequent and/or massive access
to its deeply nested attributes, then you may want to create an auxiliary
index to the parse tree via ::u_json_index. This way its nodes can be
accessed via a unique (and unambiguous -- provided that no anonymous key is
embedded into the JSON object) naming scheme, similar to the typical
struct/array access in C, i.e.:
- "." is the root node;
- ".k" is used to access value in the parent object stored under the
key "k";
- "[i]" is used to access the i-th value in the parent array.
So, for example, the string ".I2[0][0]" would retrieve the value "1" from
"{ "I2": [ [ 1, 0 ], [ 0, 1 ] ] }".
\code
long l;
dbg_err_if (u_json_index(jo));
u_json_cache_get_int(jo, ".[0][0]", &l); // l = 1
u_json_cache_get_int(jo, ".[0][1]", &l); // l = 0
u_json_cache_get_int(jo, ".[1][0]", &l); // l = 0
u_json_cache_get_int(jo, ".[1][1]", &l); // l = 1
\endcode
Please note that when index'ed, the parse tree enters a "frozen" state
in which nothing but values and types of non-container objects (i.e.
string, number, boolean and null's) can be changed. So, if you want to
come back to full tree manipulation, you must remove the indexing structure
by means of ::u_json_deindex -- which invalidates any subsequent cached
access attempt.
\section build Building and Encoding
JSON objects can be created ex-nihil via the ::u_json_new_* family
of functions, and then encoded in their serialized form via the
::u_json_encode interface:
\code
char *s = NULL;
u_json_t *root = NULL, *leaf = NULL;
dbg_err_if (u_json_new_object(NULL, &root));
dbg_err_if (u_json_new_int("integer", 999, &leaf));
dbg_err_if (u_json_add(root, leaf));
leaf = NULL;
// encode it, should give: "{ "integer": 999 }"
u_json_encode(root, &s);
\endcode
\section iter Iterators
The last basic concept that the user needs to know to work effectively with
the JSON module is iteration. Iterators allow efficient and safe traversal
of container types (i.e. arrays and objects), where a naive walk strategy
based on ::u_json_array_get_nth would instead lead to performance collapse
as access time is quadratic in the number of elements in the container.
\code
long i, e;
u_json_it_t jit;
u_json_t *jo = NULL, *cur;
const char *s = "[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]";
dbg_err_if (u_json_decode(s, &jo));
// init array iterator from first element and go forward.
dbg_err_if (u_json_it(u_json_child_first(jo), &jit));
for (i = 1; (cur = u_json_it_next(&jit)) != NULL; i++)
{
dbg_err_if (u_json_get_int(cur, &e));
dbg_err_if (e != i); // e = 1..10
}
\endcode
\section rfcimpl RFC implementation
The following implementation choices have been made (re Section 4. of
RFC 4627):
<table>
<tr>
<th>MAY</th>
<th>Answer</th>
<th>Notes</th>
</tr>
<tr>
<td>Accept non-JSON forms or extensions ?</td>
<td><b>NO</b></td>
<td>
Trailing non-JSON text is allowed (though warned) at the end of
string. I.e. the input string in scanned until the outermost
container is matched.
</td>
</tr>
<tr>
<td>Set limits on the size of accepted texts ?</td>
<td><b>NO</b></td>
<td>
Depending only upon the memory available to the parsing process.
</td>
</tr>
<tr>
<td>Set limits on the maximum depth of nesting ?</td>
<td><b>YES</b></td>
<td>
Made available to the parsing interface through the compile-time
constant ::U_JSON_MAX_DEPTH. The validating interface ignores this
limit, and as such should be used with care (i.e. never on untrusted
input).
</td>
</tr>
<tr>
<td>Set limits on the range of numbers ?</td>
<td><b>NO</b></td>
<td>
All numerical values are stored as strings. Truncation/conversion
issues can arise only when trying to extract their \c long or
\c double counterparts through the ::u_json_get_int or
::u_json_get_real commodity interfaces. In case they fail you can
still access the original (C-string) value through ::u_json_get_val.
</td>
</tr>
<tr>
<td>Set limits on the length and character contents of strings ?</td>
<td><b>YES</b></td>
<td>
String length for both keys and values are upper-bounded by
the compile-time constant ::U_TOKEN_SZ.
</td>
</tr>
</table>
*/
/**
* \brief Create a new and empty JSON object container
*
* Create a new and empty JSON object container and return its handler as
* the result argument \p *pjo
*
* \param pjo Pointer to the ::u_json_t that will be returned
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_new (u_json_t **pjo)
{
u_json_t *jo = NULL;
dbg_return_if (pjo == NULL, ~0);
warn_err_sif ((jo = u_zalloc(sizeof *jo)) == NULL);
TAILQ_INIT(&jo->children);
jo->type = U_JSON_TYPE_UNKNOWN;
jo->key[0] = jo->val[0] = jo->fqn[0] = '\0';
jo->parent = NULL;
jo->map = NULL;
jo->count = 0;
jo->depth = 0;
*pjo = jo;
return 0;
err:
if (jo)
u_free(jo);
return ~0;
}
/**
* \brief Set the type of a JSON object
*
* Set the type of the supplied JSON object \p jo to \p type.
*
* \param jo Pointer to a ::u_json_t object
* \param type One of the available ::u_json_type_t types
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_set_type (u_json_t *jo, u_json_type_t type)
{
dbg_return_if (jo == NULL, ~0);
dbg_return_ifm (jo->map, ~0, "Cannot set type of a cached object");
switch (type)
{
case U_JSON_TYPE_STRING:
case U_JSON_TYPE_NUMBER:
case U_JSON_TYPE_ARRAY:
case U_JSON_TYPE_OBJECT:
case U_JSON_TYPE_TRUE:
case U_JSON_TYPE_FALSE:
case U_JSON_TYPE_NULL:
case U_JSON_TYPE_UNKNOWN:
jo->type = type;
break;
default:
u_err("unhandled type %d", type);
return ~0;
}
return 0;
}
/**
* \brief ::u_json_set_val_ex wrapper with no \p val syntax check
*/
int u_json_set_val (u_json_t *jo, const char *val)
{
return u_json_set_val_ex(jo, val, 0);
}
/*
* \brief Set the value of a JSON object
*
* Set the value of the JSON object \p jo to the string value pointed by
* \p val. This operation is meaningful only in case the underlying object
* is a number or a string, in which case the syntax of the supplied value
* can be checked by passing non-0 value to the \p check parameter.
*
* \param jo Pointer to a ::u_json_t object
* \param val Pointer to the (non-NULL) value string
* \param check Set to non-0 if you need to syntax check \p val
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_set_val_ex (u_json_t *jo, const char *val, char check)
{
u_lexer_t *vl = NULL;
dbg_return_if (jo == NULL, ~0);
dbg_return_if (val == NULL, ~0);
/* Note that cached objects allow for value overwrite. */
if (check)
{
/* XXX The following declaration assumes C99 or C89+support of variable
* length automatic arrays -- as in GCC since at least version
* 2.95.3. */
char qval[strlen(val) + 3];
/* If we are supposed to set a string value, we need to quote it. */
(void) u_snprintf(qval, sizeof qval,
(jo->type == U_JSON_TYPE_STRING) ? "\"%s\"" : "%s", val);
dbg_err_if (u_lexer_new(qval, &vl));
}
/* If requested, pass 'val' through its validator. */
switch (jo->type)
{
case U_JSON_TYPE_STRING:
dbg_err_if (check && u_json_match_string(vl, NULL));
break;
case U_JSON_TYPE_NUMBER:
dbg_err_if (check && u_json_match_number(vl, NULL));
break;
default:
/* Non-critical error, just emit some debug info. */
goto end;
}
dbg_return_if (u_strlcpy(jo->val, val, sizeof jo->val), ~0);
/* Fall through. */
end:
u_lexer_free(vl);
return 0;
err:
u_lexer_free(vl);
return ~0;
}
/**
* \brief Set the key of a JSON object
*
* Set the key of the JSON object \p jo to the string value pointed by
* \p key.
*
* \param jo Pointer to a ::u_json_t object
* \param key Pointer to the key string. In case \p key \c NULL the value
* is reset to the empty string.
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_set_key (u_json_t *jo, const char *key)
{
dbg_return_if (jo == NULL, ~0);
dbg_return_ifm (jo->map, ~0, "Cannot set key of a cached object");
dbg_return_if (u_strlcpy(jo->key, key ? key : "", sizeof jo->key), ~0);
return 0;
}
/** \brief Wrapper function that creates an array container.
* (\p key may be \c NULL). */
int u_json_new_array (const char *key, u_json_t **pjo)
{
return u_json_new_container(U_JSON_TYPE_ARRAY, key, pjo);
}
/** \brief Wrapper function that creates an object container
* (\p key may be \c NULL). */
int u_json_new_object (const char *key, u_json_t **pjo)
{
return u_json_new_container(U_JSON_TYPE_OBJECT, key, pjo);
}
/**
* \brief Add a child JSON object to its parent container
*
* Add the child JSON object \p jo to its parent container \p head.
*
* \param head Pointer to the parent container
* \param jo Pointer to the child JSON object that shall be attached
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_add (u_json_t *head, u_json_t *jo)
{
dbg_return_if (head == NULL, ~0);
dbg_return_if (!U_JSON_OBJ_IS_CONTAINER(head), ~0);
dbg_return_ifm (head->map, ~0, "Cannot add new child to a cached object");
dbg_return_if (jo == NULL, ~0);
#ifdef U_JSON_OBJ_DEBUG
u_con("chld (%p): %s {%s} added at depth %u",
jo, u_json_type_str(jo->type), jo->key, jo->depth);
u_con("prnt (%p): %s {%s} at depth %u\n",
head, u_json_type_str(head->type), head->key, head->depth);
#endif /* U_JSON_OBJ_DEBUG */
TAILQ_INSERT_TAIL(&head->children, jo, siblings);
jo->parent = head;
/* Adjust children counter for array-type parents. */
if (head->type == U_JSON_TYPE_ARRAY)
head->count += 1;
return 0;
}
/**
* \brief Break down a JSON string into pieces
*
* Parse and (implicitly) validate the supplied JSON string \p json.
* In case of success, its internal representation is returned into the result
* argument \p *pjo.
*
* \param json A NUL-terminated string containing some serialized JSON
* \param pjo Result argument which will point to the internal
* representation of the parsed \p json string
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_decode (const char *json, u_json_t **pjo)
{
return u_json_do_parse(json, pjo, NULL);
}
/**
* \brief Validate the supplied JSON string.
*
* Validate the supplied JSON string \p json. In case \p json contains
* invalid syntax, the parser/lexer error message is returned into \p status.
*
* \param json A NUL-terminated string containing some serialized JSON
* \param status In case of error, this result argument will contain an
* explanation message from the parser/lexer.
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_validate (const char *json, char status[U_LEXER_ERR_SZ])
{
/* Just try to validate the input string (do not build the tree). */
return u_json_do_parse(json, NULL, status);
}
/**
* \brief Dispose any resource allocated to a JSON object
*
* Dispose any resource allocated to the supplied JSON object \p jo
*
* \param jo Pointer to the ::u_json_t object that must be free'd
*
* \return nothing
*/
void u_json_free (u_json_t *jo)
{
size_t dummy = 0;
if (jo == NULL)
return;
/* If there is an associated hmap free it. */
if (jo->map)
{
u_hmap_easy_free(jo->map);
jo->map = NULL;
}
/* Walk the tree in post order and free each node while we traverse. */
u_json_walk(jo, U_JSON_WALK_POSTORDER, dummy, u_json_do_free, NULL);
return;
}
/**
* \brief Encode a JSON object
*
* Encode the supplied JSON object \p jo to the result string pointed by
* \p *ps
*
* \param jo Pointer to the ::u_json_t object that must be encoded
* \param ps serialized JSON text corresponding to \p jo
*
* \retval ~0 on failure
* \retval 0 on success
*/
int u_json_encode (u_json_t *jo, char **ps)
{
u_string_t *s = NULL;
dbg_return_if (jo == NULL, ~0);
dbg_return_if (ps == NULL, ~0);
dbg_err_if (u_string_create(NULL, 0, &s));
dbg_err_if (u_json_do_encode(jo, s));
*ps = u_string_detach_cstr(s);
return 0;
err:
if (s)
u_string_free(s);
return ~0;
}
/**
* \brief Pre/post-order tree walker
*
* Traverse the supplied JSON object \p jo in pre/post-order, depending on
* \p strategy, invoking the callback function \p cb on each node.
*
* \param jo Pointer to ::u_json_t object to traverse
* \param strategy one of ::U_JSON_WALK_PREORDER or ::U_JSON_WALK_POSTORDER
* \param l depth level in the JSON tree (the root is at depth 0)
* \param cb function to invoke on each traversed node
* \param cb_args optional opaque data which will be supplied to \p cb
*
* \return nothing
*/
void u_json_walk (u_json_t *jo, int strategy, size_t l,
void (*cb)(u_json_t *, size_t, void *), void *cb_args)
{
dbg_return_if (strategy != U_JSON_WALK_PREORDER &&
strategy != U_JSON_WALK_POSTORDER, );
if (jo == NULL)
return;
if (strategy == U_JSON_WALK_PREORDER && cb)
cb(jo, l, cb_args);
/* When recurring into the children branch, increment depth by one. */
u_json_walk(TAILQ_FIRST(&jo->children), strategy, l + 1, cb, cb_args);
/* Siblings are at the same depth as the current node. */
u_json_walk(TAILQ_NEXT(jo, siblings), strategy, l, cb, cb_args);
if (strategy == U_JSON_WALK_POSTORDER && cb)
cb(jo, l, cb_args);
return;
}
/**
* \brief Print to stderr the internal representation of a JSON object
*
* Print to stderr the supplied JSON object \p jo
*
* \param jo Pointer to the ::u_json_t object that must be printed
*
* \return nothing
*/
void u_json_print (u_json_t *jo)
{
dbg_return_if (jo == NULL, );
/* Tree root is at '0' depth. */
u_json_walk(jo, U_JSON_WALK_PREORDER, 0, u_json_do_print, NULL);
return;
}
/**
* \brief Index JSON object contents.
*
* Index all contents of the supplied ::u_json_t top-level object \p jo.
* After data has been indexed, no more key/type modifications are possible
* on this object; instead, values of leaf nodes can still be changed.
* Also, either child node addition nor removal is possible after the object
* has been cached. If \p jo needs to be changed in aforementioned ways
* (type, key, addition or removal), it must be explicitly ::u_json_unindex'ed.
*
* \param jo Pointer to the ::u_json_t object that must be indexed
*
* \return nothing
*/
int u_json_index (u_json_t *jo)
{
size_t u; /* Unused. */
u_hmap_opts_t *opts = NULL;
u_hmap_t *hmap = NULL;
dbg_return_if (jo == NULL, ~0);
nop_return_if (jo->map, 0); /* If already cached, return ok. */
dbg_return_if (jo->parent, ~0); /* Cache can be created on top-objs only. */
/* Create the associative array. */
dbg_err_if (u_hmap_opts_new(&opts));
dbg_err_if (u_hmap_opts_set_val_type(opts, U_HMAP_OPTS_DATATYPE_POINTER));
dbg_err_if (u_hmap_opts_set_val_freefunc(opts, nopf));
dbg_err_if (u_hmap_easy_new(opts, &hmap));
u_hmap_opts_free(opts), opts = NULL;
/* Initialize array elems' indexing. */
jo->icur = 0;
/* Walk the tree in pre-order and cache each node while we traverse. */
u_json_walk(jo, U_JSON_WALK_PREORDER, u, u_json_do_index, hmap);
/* Attach the associative array to the top level object. */
jo->map = hmap, hmap = NULL;
return 0;
err:
if (opts)
u_hmap_opts_free(opts);
if (hmap)
u_hmap_easy_free(hmap);
return ~0;
}
/**
* \brief Remove cache from JSON object.
*
* Remove the whole cacheing machinery from the previously ::u_json_index'd
* ::u_json_t object \p jo.
*
* \param jo Pointer to the ::u_json_t object that must be de-indexed
*
* \retval 0 on success
* \retval ~0 on failure
*/
int u_json_unindex (u_json_t *jo)
{
dbg_return_if (jo == NULL, ~0);
nop_return_if (jo->map == NULL, 0);
u_hmap_easy_free(jo->map);
jo->map = NULL;
return 0;
}
/**
* \brief Retrieve JSON node by its cache name.
*
* Possibly retrieve a JSON node by its (fully qualified, or relative) cache
* \p name.
*
* \param jo Pointer to the ::u_json_t object that must be searched
* \param name name of the element that must be searched
*
* \return the retrieved JSON (sub)object on success; \c NULL in case \p key
* was not found
*/
u_json_t *u_json_cache_get (u_json_t *jo, const char *name)
{
u_json_t *res, *p;
char fqn[U_JSON_FQN_SZ];
dbg_return_if (jo == NULL, NULL);
dbg_return_if (jo->map == NULL, NULL);
dbg_return_if (name == NULL, NULL);
if ((p = jo->parent) == NULL)
{
/* If 'jo' is top level, 'name' must be fully qualified. */
return (u_json_t *) u_hmap_easy_get(jo->map, name);
}
/* Else ('jo' != top): first try 'name' as it were fully qualified. */
if ((res = (u_json_t *) u_hmap_easy_get(jo->map, name)))
return res;
/* If 'name' is relative, we need to prefix it with the parent name
* space. */
dbg_if (u_snprintf(fqn, sizeof fqn, "%s%s", jo->fqn, name));
return (u_json_t *) u_hmap_easy_get(jo->map, fqn);
}
/**
* \brief Set JSON node's type and value by its cache name.
*
* Set type and value of the supplied JSON (leaf) node by its (fully qualified
* or relative) cache \p name. If \p type is ::U_JSON_TYPE_UNKNOWN the
* underlying type will be left untouched.
*
* \param jo Pointer to an ::u_json_t object
* \param name name of the element that must be set
* \param type new type (or ::U_JSON_TYPE_UNKNOWN if no type change)
* \param val new value. MUST be non-NULL in case we are setting a
* string a or number.
*
* \retval 0 on success
* \retval ~0 on failure
*/
int u_json_cache_set_tv (u_json_t *jo, const char *name,
u_json_type_t type, const char *val)
{
u_json_t *res;
dbg_return_if (U_JSON_OBJ_IS_CONTAINER(jo), ~0);
dbg_return_if (type == U_JSON_TYPE_OBJECT || type == U_JSON_TYPE_ARRAY, ~0);
/* 'jo' and 'name' will be checked by u_json_cache_get();
* 'val' consistency is checked after type has been set. */
/* Retrieve the node. */
dbg_err_if ((res = u_json_cache_get(jo, name)) == NULL);
/* First set type (in case !unknown) so that we know how to check the
* subsequent value setting. */
if (type != U_JSON_TYPE_UNKNOWN)
res->type = type;
/* Set value. The caller must have supplied some non-NULL 'val' in case
* the final underlying type is a string or a number. */
if (res->type == U_JSON_TYPE_STRING || res->type == U_JSON_TYPE_NUMBER)
dbg_err_if (val == NULL || u_strlcpy(res->val, val, sizeof res->val));
return 0;
err:
return ~0;
}
/** \brief Return the number of elements in array \p jo, or \c 0 on error. */
unsigned int u_json_array_count (u_json_t *jo)
{
dbg_return_if (jo == NULL, 0);
dbg_return_if (jo->type != U_JSON_TYPE_ARRAY, 0);
return jo->count;
}
/** \brief Get n-th element from \p jo array. */
u_json_t *u_json_array_get_nth (u_json_t *jo, unsigned int n)
{
u_json_t *elem;
dbg_return_if (jo == NULL, NULL);
dbg_return_if (jo->type != U_JSON_TYPE_ARRAY, NULL);
dbg_return_if (n >= jo->count, NULL);
/* Use cache if available. */
if (jo->map)
{
char elem_fqn[U_JSON_FQN_SZ] = { '\0' };
dbg_if (u_snprintf(elem_fqn, sizeof elem_fqn, "%s[%u]", jo->fqn, n));
return u_json_cache_get(jo, elem_fqn);
}
/* Too bad if we don't have cache in place: we have to go through the
* list which is quadratic even with the following silly optimisation.
* So it's ok for a couple of lookups, but if done systematically it's
* an overkill. Freeze instead ! */
if (n > (jo->count / 2))
{
unsigned int r = jo->count - (n + 1);
TAILQ_FOREACH_REVERSE (elem, &jo->children, u_json_chld_s, siblings)
{
if (r == 0)
return elem;
r -= 1;
}
}
else
{
TAILQ_FOREACH (elem, &jo->children, siblings)
{
if (n == 0)
return elem;
n -= 1;
}
}
/* Unreachable. */
return NULL;
}
/** \brief Get the value associated with the non-container object \p jo. */
const char *u_json_get_val (u_json_t *jo)
{
dbg_return_if (jo == NULL, NULL);
switch (jo->type)
{
case U_JSON_TYPE_STRING:
case U_JSON_TYPE_NUMBER:
return jo->val;
case U_JSON_TYPE_TRUE:
return "true";
case U_JSON_TYPE_FALSE:
return "false";
case U_JSON_TYPE_NULL:
return "null";
case U_JSON_TYPE_OBJECT:
case U_JSON_TYPE_ARRAY:
case U_JSON_TYPE_UNKNOWN:
default:
return NULL;
}
}
/** \brief Get the \c long \c int value of the non-container object \p jo. */
int u_json_get_int (u_json_t *jo, long *pl)
{
dbg_return_if (jo == NULL, ~0);
dbg_return_if (jo->type != U_JSON_TYPE_NUMBER, ~0);
dbg_return_if (pl == NULL, ~0);
dbg_err_if (u_atol(jo->val, pl));
return 0;
err:
return ~0;
}
/** \brief Get the \c double precision FP value of the non-container object
* \p jo. */
int u_json_get_real (u_json_t *jo, double *pd)
{
dbg_return_if (jo == NULL, ~0);
dbg_return_if (jo->type != U_JSON_TYPE_NUMBER, ~0);
dbg_return_if (pd == NULL, ~0);
dbg_err_if (u_atof(jo->val, pd));
return 0;
err:
return ~0;
}
/** \brief Get the boolean value of the non-container object \p jo. */
int u_json_get_bool (u_json_t *jo, char *pb)
{
dbg_return_if (jo == NULL, ~0);
dbg_return_if (pb == NULL, ~0);
switch (jo->type)
{
case U_JSON_TYPE_TRUE:
*pb = 1;
break;
case U_JSON_TYPE_FALSE:
*pb = 0;
break;
default:
return ~0;
}
return 0;
}
/** \brief Wrapper around ::u_json_cache_get to retrieve string values from
* terminal (i.e. non-container) objects. */
const char *u_json_cache_get_val (u_json_t *jo, const char *name)
{
u_json_t *res = u_json_cache_get(jo, name);
return u_json_get_val(res);
}
/** \brief Wrapper around ::u_json_cache_get to retrieve integer values from
* terminal (i.e. non-container) objects. */
int u_json_cache_get_int (u_json_t *jo, const char *name, long *pval)
{
u_json_t *res;
dbg_return_if ((res = u_json_cache_get(jo, name)) == NULL, ~0);
return u_json_get_int(res, pval);
}
/** \brief Wrapper around ::u_json_cache_get to retrieve double precision FP
* values from terminal (i.e. non-container) objects. */
int u_json_cache_get_real (u_json_t *jo, const char *name, double *pval)
{
u_json_t *res;
dbg_return_if ((res = u_json_cache_get(jo, name)) == NULL, ~0);
return u_json_get_real(res, pval);
}
/** \brief Wrapper around ::u_json_cache_get to retrieve boolean values from
* terminal (i.e. non-container) objects. */
int u_json_cache_get_bool (u_json_t *jo, const char *name, char *pval)
{
u_json_t *res;
dbg_return_if ((res = u_json_cache_get(jo, name)) == NULL, ~0);
return u_json_get_bool(res, pval);
}
/**
* \brief Remove an object from its JSON container.
*
* Remove an object from its JSON container. This interface falls back to
* ::u_json_free in case the supplied \p jo is the root node.
*
* \param jo Pointer to the ::u_json_t object that must be removed
*
* \retval 0 on success
* \retval ~0 on failure
*/
int u_json_remove (u_json_t *jo)
{
u_json_t *p;
dbg_return_if (jo == NULL, ~0);
dbg_return_ifm (jo->map, ~0, "Cannot remove (from) a cached object");
if ((p = jo->parent))
{
/* Fix counters when parent is an array. */