-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.c
1949 lines (1722 loc) · 49.1 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
/* json.c - Json reader/writer for C language.
*
*
* (c) 2019 Oleg Alexeev <oleg.alexeev@inbox.ru> (https://github.com/exgit)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "json.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HAVE_TRACE 0
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned short ushort;
// Error reporting macro.
#if 1
#define ERROR(fmt, ...) fprintf(stderr, \
"JSON ERROR: %s():%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
#else
#define ERROR(fmt, ...) ((void)0)
#endif
// Tracing macro.
#if HAVE_TRACE == 1
#define TRACE(fmt, ...) fprintf(stderr, \
"JSON TRACE: %s():%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
#else
#define TRACE(fmt, ...) ((void)0)
#endif
/*****************************************************************************
* Arena memory allocator.
*****************************************************************************/
// magic number for free block header
#define MAGIC 0x76543210
// rounding up
#define ROUNDUP(x) x += (-x & (sizeof(void*) - 1))
// arena chunk header
typedef struct _marena_chunk_hdr_t marena_chunk_hdr_t;
struct _marena_chunk_hdr_t {
size_t size; // this chunk size in bytes
size_t allocated; // amount of allocated bytes in this chunk
marena_chunk_hdr_t *next; // next chunk ptr
};
// returnable memory block header (size aligned go GRANULARITY)
typedef struct _marena_rt_hdr_t marena_rt_hdr_t;
struct _marena_rt_hdr_t {
marena_rt_hdr_t *next; // ptr to next free block
size_t size; // size of this block (including header size)
uint mmc; // mismatch count for a free block
uint magic; // magic number for correctness test
};
// memory arena object (size aligned go GRANULARITY)
typedef struct _marena_t marena_t;
struct _marena_t {
size_t chunk_size; // arena chunk size
#if HAVE_TRACE == 1
size_t alloc_count;
size_t search_count;
size_t size_max;
size_t size_total;
#endif
marena_chunk_hdr_t *first; // first arena memory chunk
marena_chunk_hdr_t *curr; // current arena memory chunk
marena_rt_hdr_t *free; // ptr to first free returnable block
};
// Create arena chunk.
static marena_chunk_hdr_t *marena_create_chunk(size_t size)
{
ROUNDUP(size);
marena_chunk_hdr_t *chunk = malloc(sizeof(marena_chunk_hdr_t) + size);
if (chunk) {
chunk->size = size;
chunk->allocated = 0;
chunk->next = NULL;
}
return chunk;
}
// Destroy arena chunk list.
static void marena_destroy_chunk_list(marena_chunk_hdr_t *c)
{
while (c) {
marena_chunk_hdr_t *p = c;
c = c->next;
free(p);
}
}
// Reset memory arena.
static bool marena_reset(marena_t *ma, size_t default_chunk_size)
{
marena_chunk_hdr_t *chunk;
// Case: no chunks or big chunk not filled enough.
// Make default chunk.
if (ma->first == NULL
|| (ma->first->allocated < default_chunk_size / 2
&& ma->chunk_size > default_chunk_size)) {
marena_destroy_chunk_list(ma->first);
ma->chunk_size = default_chunk_size;
goto create;
}
// Case: chunks with different sizes.
// Make one chunk with current size.
for (chunk=ma->first; chunk; chunk=chunk->next) {
if (chunk->size != ma->chunk_size) {
marena_destroy_chunk_list(ma->first);
goto create;
}
}
// Case: chunk list is too long.
// Make one chunk with bigger size.
int count = 0;
for (chunk=ma->first; chunk; chunk=chunk->next) {
if (++count > 4) {
marena_destroy_chunk_list(ma->first);
ma->chunk_size *= 2;
goto create;
}
}
// Case: no adjustment needed.
goto reset;
create:
ma->first = marena_create_chunk(ma->chunk_size);
if (!ma->first)
return false;
reset:
#if HAVE_TRACE == 1
ma->alloc_count = 0;
ma->search_count = 0;
ma->size_max = 0;
for (ma->size_total=0, chunk=ma->first; chunk; chunk=chunk->next) {
ma->size_total += chunk->size;
}
#endif
ma->curr = ma->first;
ma->curr->allocated = 0;
ma->free = NULL;
return true;
}
// Create memory arena object.
static marena_t *marena_create(size_t size)
{
ROUNDUP(size);
marena_t *arena = malloc(sizeof(marena_t));
if (arena) {
arena->chunk_size = size;
arena->first = NULL;
if (!marena_reset(arena, size)) {
free(arena);
arena = NULL;
}
}
return arena;
}
// Destroy memory arena object.
static void marena_destroy(marena_t *ma)
{
marena_destroy_chunk_list(ma->first);
free(ma);
}
// Allocate memory from arena.
static void *marena_alloc(marena_t *ma, size_t size)
{
char *ret = NULL;
if (ma == NULL)
goto exit;
ROUNDUP(size);
// current chunk does not have enough space - try to select next chunk
if (ma->curr->allocated + size > ma->curr->size) {
if (ma->curr->next) {
if (ma->curr->next->size > size) {
ma->curr = ma->curr->next;
ma->curr->allocated = 0;
} else {
marena_destroy_chunk_list(ma->curr->next);
ma->curr->next = NULL;
}
}
}
// check current chunk again, but now it is guaranteed to be a last chunk
if (ma->curr->allocated + size > ma->curr->size) {
// grow chunk size as needed
while (ma->chunk_size < size)
ma->chunk_size *= 2;
// create new chunk
marena_chunk_hdr_t *chunk = marena_create_chunk(ma->chunk_size);
if (!chunk)
goto exit;
ma->curr->next = chunk;
ma->curr = chunk;
#if HAVE_TRACE == 1
ma->size_total += ma->chunk_size;
#endif
}
ret = (char*)ma->curr + sizeof(marena_chunk_hdr_t) + ma->curr->allocated;
ma->curr->allocated += size;
exit:
return ret;
}
// Allocate returnable block from memory arena.
static void *marena_alloc_rt(marena_t *ma, size_t size)
{
marena_rt_hdr_t **prev = &ma->free;
marena_rt_hdr_t *curr;
// add header size
ROUNDUP(size);
size += sizeof(marena_rt_hdr_t);
#if HAVE_TRACE == 1
ma->alloc_count++;
if (size > ma->size_max) {
TRACE("Setting new size_max: %ld", size);
ma->size_max = size;
}
#endif
// allocate from prevously freed
for (curr = *prev; curr; curr = curr->next) {
if (curr->size >= size) {
if (curr->size >= 4 * size) { // split block
curr->size -= size;
marena_rt_hdr_t *spl = (marena_rt_hdr_t*)((char*)curr + curr->size);
spl->next = 0;
spl->size = size;
spl->magic = MAGIC;
return (spl + 1);
} else { // allocate full block
*prev = curr->next;
return (curr + 1);
}
}
#if HAVE_TRACE == 1
ma->search_count++;
#endif
if (++curr->mmc > 8) {
*prev = curr->next; // remove block from free list
} else {
prev = &curr->next; // leave block in free list
}
}
// allocate from arena
curr = marena_alloc(ma, size);
if (!curr)
return NULL;
curr->next = NULL;
curr->size = size;
curr->magic = MAGIC;
return (curr + 1);
}
// Resize returnable block.
static void *marena_realloc_rt(marena_t *ma, void *ptr, size_t size)
{
char *ret = NULL;
if (ma == NULL)
goto exit;
// add header size
ROUNDUP(size);
size += sizeof(marena_rt_hdr_t);
// check if ptr really points to returnable block
marena_rt_hdr_t *curr = (marena_rt_hdr_t*)ptr - 1;
if (curr->magic != MAGIC)
goto exit;
// check if block already has requred size
if (curr->size >= size) {
ret = ptr;
goto exit;
}
// allocate new returnable block
ret = marena_alloc_rt(ma, size);
if (ret == NULL)
goto exit;
// copy data to new block
memcpy(ret, ptr, curr->size);
// free old block
curr->mmc = 0;
curr->next = ma->free;
ma->free = curr;
exit:
return ret;
}
// Free returnable block.
static void marena_free_rt(marena_t *ma, void *ptr)
{
// check if ptr really points to returnable block
marena_rt_hdr_t *curr = (marena_rt_hdr_t*)ptr - 1;
if (curr->magic != MAGIC)
return;
// free block
curr->mmc = 0;
curr->next = ma->free;
ma->free = curr;
}
/*****************************************************************************
* Json object attribute name table.
*****************************************************************************/
// Attribute name index type.
typedef ushort ani_t;
// Maximum number of attribute names in json.
#define ANI_MAX 0xFFFF
// Attribute names table object.
typedef struct _ant_t {
marena_t *mem; // memory allocator
// array of attribute names
const char **an; // attribute names
uint an_cnt; // count
uint an_cap; // capacity
// hash table (mapping between names and their indexes)
const char **ht_an; // attribute names
ani_t *ht_ani; // attribute name indexes
uint ht_size; // size
} ant_t;
// Create attribute names table object.
static ant_t *ant_create(marena_t *mem)
{
ant_t *ant = marena_alloc(mem, sizeof(*ant));
if (ant == NULL)
return NULL;
ant->mem = mem;
ant->an_cap = 16;
ant->an = marena_alloc_rt(mem, ant->an_cap * sizeof(ant->an[0]));
if (ant->an == NULL)
return NULL;
ant->an_cnt = 1; // attribute name indexes should start from 1
ant->an[0] = NULL; // because 0 can not be put in hash table
ant->ht_size = ant->an_cap * 4;
uint sk = ant->ht_size * sizeof(ant->ht_an[0]);
uint sv = ant->ht_size * sizeof(ant->ht_ani[0]);
ant->ht_an = marena_alloc_rt(mem, sk+sv);
if (ant->ht_an == NULL)
return NULL;
memset(ant->ht_an, 0, sk+sv);
ant->ht_ani = (ani_t*)((char*)ant->ht_an + sk);
return ant;
}
// Calculate hash value of a string.
static inline uint ant_hash(const char *s)
{
uint h = 0;
for (; *s; s++)
h = h * 7879 + (h >> 16) + *(const uchar*)s;
return h;
}
// Set hash table element.
static void ant_set(ant_t *ant, const char *name, int index)
{
uint i = ant_hash(name) % ant->ht_size;
while (ant->ht_an[i]) {
if (++i >= ant->ht_size)
i = 0;
}
ant->ht_an[i] = name;
ant->ht_ani[i] = (ani_t)index;
}
// Find hash table element.
static int ant_get(ant_t *ant, const char *name)
{
uint i = ant_hash(name) % ant->ht_size;
while (ant->ht_an[i]) {
if (0 == strcmp(name, ant->ht_an[i]))
return ant->ht_ani[i];
if (++i >= ant->ht_size)
i = 0;
}
return -1;
}
// Add new or search for existing token.
static int ant_add_token(ant_t *ant, const char *start, uint len)
{
uint i;
// copy name to buffer adding 0 at end
char name[256];
if (len >= sizeof(name)) {
ERROR("attribute name too long");
goto exit;
}
memcpy(name, start, len);
name[len] = 0;
// check if attribute name is already present
int index = ant_get(ant, name);
if (index >= 0)
return index;
// allocate memory for attribute name
char *p = marena_alloc(ant->mem, len + 1);
if (!p)
goto exit;
memcpy(p, name, len + 1);
// need to resize array and hash table
if (ant->an_cnt >= ant->an_cap) {
// grow array of attribute names
ant->an_cap *= 2;
ant->an = marena_realloc_rt(ant->mem, ant->an,
ant->an_cap * sizeof(ant->an[0]));
if (ant->an == NULL)
goto exit;
// grow hash table
const char **old_an = ant->ht_an;
ani_t *old_ani = ant->ht_ani;
uint old_size = ant->ht_size;
ant->ht_size = ant->an_cap * 4;
uint sk = ant->ht_size * sizeof(ant->ht_an[0]);
uint sv = ant->ht_size * sizeof(ant->ht_ani[0]);
ant->ht_an = marena_alloc_rt(ant->mem, sk+sv);
if (ant->ht_an == NULL)
goto exit;
memset(ant->ht_an, 0, sk+sv);
ant->ht_ani = (ani_t*)((char*)ant->ht_an + sk);
for (i = 0; i < old_size; i++) // do rehashing
if (old_an[i])
ant_set(ant, old_an[i], old_ani[i]);
marena_free_rt(ant->mem, old_an);
}
index = (int)ant->an_cnt++;
ant->an[index] = p;
ant_set(ant, p, index);
return index;
exit:
return -1;
}
/*****************************************************************************
* Hash table for mapping between attribute name index and node array index.
*****************************************************************************/
// Hash table object.
typedef struct _ht_t {
ani_t *k; // attribute name indexes
void *v; // node array indexes
int num; // number of elements in hash table
int size; // size of hash table
} ht_t;
// Create hash table object.
static void *ht_create(marena_t *mem, int cnt)
{
ht_t *ht = marena_alloc(mem, sizeof(*ht));
if (ht == NULL)
return NULL;
ht->num = cnt;
ht->size = cnt * 4;
uint sk = (uint)ht->size * sizeof(ht->k[0]);
uint sv = (uint)ht->size * (ht->num < 256 ? sizeof(uchar) : sizeof(ushort));
ht->k = marena_alloc(mem, sk+sv);
if (ht->k == NULL)
return NULL;
memset(ht->k, 0, sk+sv);
ht->v = (char*)ht->k + sk;
return ht;
}
// Set hash table element.
static void ht_set(ht_t *ht, ani_t k, int v)
{
int i = (int)k % ht->size;
while (ht->k[i]) {
if (ht->k[i] == k)
break;
if (++i >= ht->size)
i = 0;
}
ht->k[i] = k;
if (ht->num < 256) {
((uchar*)ht->v)[i] = (uchar)v;
} else {
((ushort*)ht->v)[i] = (ushort)v;
}
}
// Find hash table element.
static int ht_get(ht_t *ht, ani_t k)
{
int i = (int)k % ht->size;
while (ht->k[i]) {
if (ht->k[i] == k) {
if (ht->num < 256) {
return ((uchar*)ht->v)[i];
} else {
return ((ushort*)ht->v)[i];
}
}
if (++i >= ht->size)
i = 0;
}
return -1;
}
/*****************************************************************************
* Json parser data and functions.
*****************************************************************************/
// Minimal size of arena allocator.
#define JSON_MEM_MIN (16 * 1024)
// Minimal count of stack elements (determines possible json nesting).
#define JSON_STACK_MIN 16
// Initial capacity of dynamic arrays.
#define JSON_CAP_MIN 8
// Character types.
enum {
CNV, // invalid characters
CBL, // blank symbols ' ', '\t', '\n', '\r'
CMN, // minus '-'
CPT, // point
CNM, // numbers '0-9'
CLT, // letters '_', 'a-z', 'A-Z'
CQT, // quotes "'", '"'
CCM, // comma ','
CCL, // colon ':'
CAS, // array start '['
CAE, // array end ']'
COS, // object start '{'
COE, // object end '}'
CSL // slash '/'
};
// Token types.
typedef enum {
JINSTART, // input start
JINEND, // input end
JASTART, // '[' - array start
JAEND, // ']' - array end
JOSTART, // '{' - object start
JOEND, // '}' - object end
JCOMMA, // ',' - comma
JNULL, // null
JBOOL, // true or false
JINT, // integer number
JDBL, // double-precision floating-point number
JSTR, // string
JNAME, // object attribute name
JERROR // none of the above
} jtt;
// Parsing context.
typedef enum {
CTXVAL, // parsing singular value
CTXARR, // parsing json array
CTXOBJ // parsing json object
} jctx;
// Token object.
typedef struct {
jtt type; // token type
uint len; // token length
uint pos; // position inside json string
} jtok;
// Json object node.
typedef struct _jnode_obj_t {
jnode_t b; // inheritance from base type
ant_t *ant; // ptr to attribute names table
union {
ani_t *anis; // array of attribute name indexes
ht_t *ht; // ptr to hash table
};
} jnode_obj_t;
// Stack element of parser.
typedef struct {
jtok tokp; // previous token
jctx ctx; // parsing context
jnode_t *node; // current json node
int node_cap; // capacity of all arrays for current node
} jpstk;
// Json parser object.
struct _jparser_t {
marena_t *mem; // memory allocator
const char *start; // json string start
uint len; // json string length
uint pos; // current position in json string
ant_t *ant; // attribute names table
jnode_t **root; // ptr to root node ptr
jtok tokc; // current token
uint sidx; // stack index
jpstk *stack; // stack
uint ssize; // stack size
};
// Character type translation table.
static uchar ct[256] = {
//0 1 2 3 4 5 6 7 8 9 A B C D E F //
CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CBL, CBL, CNV, CNV, CBL, CNV, CNV, // 00
CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, CNV, // 10
CBL, CNV, CQT, CNV, CNV, CNV, CNV, CQT, CNV, CNV, CNV, CNV, CCM, CMN, CPT, CSL, // 20
CNM, CNM, CNM, CNM, CNM, CNM, CNM, CNM, CNM, CNM, CCL, CNV, CNV, CNV, CNV, CNV, // 30
CNV, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, // 40
CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CAS, CNV, CAE, CNV, CLT, // 50
CNV, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, // 60
CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, CLT, COS, CNV, COE, CNV, CNV // 70
};
// Forward declarations.
static jnode_t *jp_new_node(jparser_t *jp, jtype_t type);
static int jp_add_elt(jparser_t *jp, jnode_t *n);
static int jp_add_attr(jparser_t *jp, ani_t index);
static int jp_obj_end(jparser_t *jp);
static void jp_next(jparser_t *jp);
static const char *jp_read_str(jparser_t *jp, int *len);
// Json node for returning absent values.
static jnode_t none;
/* Get node from array node by index.
*
* In:
* node - json node of type JT_ARR
* i - array index
* Return:
* json node
*/
jnode_t *jn_elt(jnode_t *node, int i)
{
if (node->type != JT_ARR)
return &none;
if (!(0 <= i && i < node->elts.count))
return &none;
return node->elts.values[i];
}
/* Get node from object node by attribute name.
* Attribute names are case sensitive.
* Searching is done using hash tables.
*
* In:
* node - json node of type JT_OBJ
* name - object attribute name
* Return:
* json node
*/
jnode_t *jn_attr(jnode_t *node, const char *name)
{
if (node->type != JT_OBJ)
return &none;
// get attribute name index
jnode_obj_t *nobj = (jnode_obj_t*)node;
int i = ant_get(nobj->ant, name);
if (i < 0)
return &none;
// get array index
i = ht_get(nobj->ht, (ani_t)i);
if (i < 0)
return &none;
return node->attrs.values[i];
}
/* Create json parser object.
* All memory is allocated here and during parsing there are no
* calls to malloc() or free().
*
* In:
* jp[out] - address of ptr to json parser object
* mem - amount of memory to be used for parsing;
* if 0, then default value is used
* stack - stack depth; this value controls maximum nesting in json;
* if 0 then default value is used
* Return:
* 0 - success
* !0 - error
*/
int jp_create(jparser_t **jp, size_t mem, size_t stack)
{
int ret = -1;
// adjust input values
if (mem < JSON_MEM_MIN)
mem = JSON_MEM_MIN;
if (stack < JSON_STACK_MIN)
stack = JSON_STACK_MIN;
// get memory for parser object
jparser_t *p = malloc(sizeof(*p));
if (!p)
goto enomem;
memset(p, 0, sizeof(*p));
// get memory for stack
p->stack = malloc(stack * sizeof(p->stack[0]));
if (!p->stack)
goto enomem;
p->ssize = (uint)stack;
// get memory for allocator
p->mem = marena_create(mem);
if (!p->mem)
goto enomem;
*jp = p;
ret = 0;
exit:
return ret;
enomem:
ERROR("no memory");
if (p) {
free(p->stack);
free(p);
}
goto exit;
}
/* Destroy json parser object and release all allocated memory.
*
* In:
* jp - ptr to json parser object
*/
void jp_destroy(jparser_t *jp)
{
if (jp == NULL)
return;
marena_destroy(jp->mem);
free(jp->stack);
free(jp);
}
/* Parse json string into a tree of 'jnode_t' structures.
* These structures need not to be freed manually. They are freed
* automatically then jp_parse() is called next time or
* json parser object is destroyed.
*
* In:
* jp - ptr to json parser object
* root[out] - addres of ptr to root node
* json - ptr to json string
* len - length of json string
*
* Return:
* 0 - success
* !0 - error
*/
int jp_parse(jparser_t *jp, jnode_t **root, const char *json, size_t len)
{
jnode_t *n = NULL;
if (!marena_reset(jp->mem, JSON_MEM_MIN)) {
ERROR("no memory");
return -1;
}
jp->start = json;
jp->len = (uint)len;
jp->pos = 0;
jp->ant = ant_create(jp->mem);
if (!jp->ant) {
ERROR("no memory");
return -1;
}
*root = &none;
jp->root = root;
jp->tokc.type = JINSTART;
jp->tokc.pos = 0;
jp->tokc.len = 0;
jp->sidx = 0; // stack index
jpstk *s = jp->stack; // stack pointer
s->ctx = CTXVAL;
for (;;) {
s->tokp = jp->tokc;
jtt t = s->tokp.type;
jp_next(jp);
switch (jp->tokc.type) {
case JINEND:
if (s->ctx != CTXVAL)
return -1;
if (t == JINSTART)
return -1;
goto exit;
case JASTART:
n = jp_new_node(jp, JT_ARR);
if (n == NULL)
return -1;
if (++jp->sidx >= jp->ssize)
return -1;
s++;
s->node = n;
s->node_cap = JSON_CAP_MIN;
s->ctx = CTXARR;
break;
case JOSTART:
n = jp_new_node(jp, JT_OBJ);
if (n == NULL)
return -1;
if (++jp->sidx >= jp->ssize)
return -1;
s++;
s->node = n;
s->node_cap = JSON_CAP_MIN;
s->ctx = CTXOBJ;
break;
case JAEND:
if (s->ctx != CTXARR)
return -1;
if (t == JCOMMA)
return -1;
if (jp->sidx == 0)
return -1;
jp->sidx--;
s--;
break;
case JOEND:
if (s->ctx != CTXOBJ)
return -1;
if (t == JCOMMA || t == JNAME)
return -1;
if (jp_obj_end(jp))
return -1;
if (jp->sidx == 0)
return -1;
jp->sidx--;
s--;
break;
case JCOMMA:
if (s->ctx == CTXVAL) {
return -1;
} else if (s->ctx == CTXARR) {
if (t == JASTART)
return -1;
} else {
if (t == JOSTART || t == JNAME)
return -1;
}
break;
case JNULL:
n = jp_new_node(jp, JT_NULL);
if (n == NULL)
return -1;
break;
case JBOOL:
n = jp_new_node(jp, JT_BOOL);
if (n == NULL)
return -1;
break;
case JINT:
n = jp_new_node(jp, JT_INT);
if (n == NULL)
return -1;
break;
case JDBL:
#if JSON_DOUBLE == 1
n = jp_new_node(jp, JT_DBL);
if (n == NULL)
return -1;
break;
#else
return -1;
#endif
case JSTR:
n = jp_new_node(jp, JT_STR);
if (n == NULL)
return -1;
break;
case JNAME:
if (s->ctx != CTXOBJ)
return -1;
if (t != JOSTART && t != JCOMMA)
return -1;
jtok *t = &jp->tokc;
int i = ant_add_token(jp->ant, jp->start + t->pos, t->len);
if (i < 0)
return -1;
if (jp_add_attr(jp, (ani_t)i))
return -1;
break;
default:
return -1;
}
}
exit:
TRACE("Total memory: %ld", jp->mem->size_total);
TRACE("Allocations count: %ld", jp->mem->alloc_count);
TRACE("Search count: %ld", jp->mem->search_count);
return 0;
}
// Create new json node.
static jnode_t *jp_new_node(jparser_t *jp, jtype_t type)
{
uint ns = (type == JT_OBJ) ? sizeof(jnode_obj_t) : sizeof(jnode_t);
jnode_t *n = marena_alloc(jp->mem, ns);
if (n == NULL) {
ERROR("no memory");
return NULL;
}
memset(n, 0, ns);
n->type = type;
// set node value
if (type == JT_BOOL) {
const char *p = jp->start + jp->tokc.pos;
n->bool_val = ((*p | 0x20) == 't');