-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathghh_json.h
1672 lines (1274 loc) · 41.8 KB
/
ghh_json.h
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
#ifndef GHH_JSON_H
#define GHH_JSON_H
#ifdef __cplusplus
extern "C" {
#endif
// licensing info at end of file.
#include <stddef.h>
#include <stdio.h>
#include <stdbool.h>
typedef enum json_type {
JSON_OBJECT,
JSON_ARRAY,
JSON_STRING,
JSON_NUMBER,
JSON_TRUE,
JSON_FALSE,
JSON_NULL
} json_type_e;
typedef struct json_object {
union json_obj_data {
struct json_hmap *hmap;
struct json_vec *vec;
char *string;
double number;
} data;
json_type_e type;
} json_object_t;
typedef struct json {
json_object_t *root;
// allocators
struct json_tptr **tracked; // fat pointer array of tracked pointers
char **pages; // fat pointer
size_t cur_tracked, tracked_cap; // tracks tracked pointers
size_t cur_page, page_cap; // tracks allocator pages
size_t used; // tracks current page stack
} json_t;
void json_load(json_t *, char *text);
void json_load_empty(json_t *);
void json_load_file(json_t *, const char *filepath);
void json_unload(json_t *);
// returns a string allocated with JSON_MALLOC
// TODO make this a lot easier
char *json_serialize(json_object_t *, bool mini, int indent, size_t *out_len);
// take an object, retrieve data and cast
json_object_t *json_get_object(json_object_t *, char *key);
// returns actual, mutable array pointer. do not modify.
json_object_t **json_get_array(json_object_t *, char *key, size_t *out_size);
char *json_get_string(json_object_t *, char *key);
double json_get_number(json_object_t *, char *key);
bool json_get_bool(json_object_t *, char *key);
// returns actual, mutable array pointer. do not modify.
char **json_get_keys(json_object_t *, size_t *out_size);
// cast an object to a data type
json_object_t **json_to_array(json_object_t *, size_t *out_size);
char *json_to_string(json_object_t *);
double json_to_number(json_object_t *);
bool json_to_bool(json_object_t *);
// remove a json_object from another json_object (unordered)
json_object_t *json_pop(json_t *, json_object_t *, char *key);
// pop but ordered, this is O(n) rather than O(1) removal time
json_object_t *json_pop_ordered(json_t *, json_object_t *, char *key);
// add a json_object to another json_object
void json_put(json_t *, json_object_t *, char *key, json_object_t *child);
void json_put_copy(json_t *, json_object_t *, char *key, json_object_t *child);
// equivalent to calling json_new_type() and then json_put().
// return the new object
json_object_t *json_put_object(json_t *, json_object_t *, char *key);
void json_put_array(
json_t *, json_object_t *, char *key, json_object_t **objects, size_t size
);
void json_put_string(json_t *, json_object_t *, char *key, char *string);
void json_put_number(json_t *, json_object_t *, char *key, double number);
void json_put_bool(json_t *, json_object_t *, char *key, bool value);
void json_put_null(json_t *, json_object_t *, char *key);
// create a json data type on a json_t memory context
json_object_t *json_new_object(json_t *);
json_object_t *json_new_array(json_t *, json_object_t **objects, size_t size);
json_object_t *json_new_string(json_t *, char *string);
json_object_t *json_new_number(json_t *, double number);
json_object_t *json_new_bool(json_t *, bool value);
json_object_t *json_new_null(json_t *);
// allocate and recursively copy an object and its children
json_object_t *json_copy(json_t *, json_object_t *);
#ifdef GHH_JSON_IMPL
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
// errors + debugging ==========================================================
#ifdef JSON_DEBUG_INFO
#define JSON_DEBUG(...) printf(__VA_ARGS__)
#else
#define JSON_DEBUG(...)
#endif
#ifndef NDEBUG
#define JSON_ASSERT(cond, ...) if (!(cond)) JSON_ERROR(__VA_ARGS__)
#else
#define JSON_ASSERT(...)
#endif
#define JSON_ERROR(...)\
do {\
fprintf(stderr, "JSON ERROR: ");\
fprintf(stderr, __VA_ARGS__);\
exit(-1);\
} while (0)
#define JSON_CTX_ERROR(ctx, ...)\
do {\
fprintf(stderr, "JSON ERROR: ");\
fprintf(stderr, __VA_ARGS__);\
json_contextual_error(ctx);\
exit(-1);\
} while (0)
#ifndef NDEBUG
// could do this with an X macro but I think it would reduce clarity
static const char *json_types[] = {
"JSON_OBJECT",
"JSON_ARRAY",
"JSON_STRING",
"JSON_NUMBER",
"JSON_TRUE",
"JSON_FALSE",
"JSON_NULL"
};
#endif
typedef struct json_ctx {
json_t *json;
const char *text;
size_t index;
} json_ctx_t;
static void json_contextual_error(json_ctx_t *ctx) {
// get line number and line index
size_t line = 1, line_index = 0;
for (size_t i = 0; i < ctx->index; ++i) {
if (ctx->text[i] == '\n') {
++line;
line_index = i + 1;
}
}
// get line length
size_t i = line_index;
int line_length = 0;
while (ctx->text[i] != '\n' && ctx->text[i] != '\0') {
++line_length;
++i;
}
// print formatted line data
printf("%6zu | %.*s\n", line, line_length, ctx->text + line_index);
printf("%6s | %*s\n", "", (int)(ctx->index - line_index) + 1, "^");
}
// memory ======================================================================
#ifndef JSON_MALLOC
#define JSON_MALLOC(size) malloc(size)
#endif
#ifndef JSON_FREE
#define JSON_FREE(ptr) free(ptr)
#endif
// size of fread() buffer
#ifndef JSON_FREAD_BUF_SIZE
#define JSON_FREAD_BUF_SIZE 4096
#endif
// size of each json_t allocator page, increasing this results pretty directly
// in less cache misses
#ifndef JSON_PAGE_SIZE
#define JSON_PAGE_SIZE 65536
#endif
// initial sizes of stretchy buffers for json_t allocators
#define JSON_INIT_PAGE_CAP 8
#define JSON_INIT_TRACKED_CAP 256
// tracked pointer header
typedef struct json_tptr {
size_t size, index;
} json_tptr_t;
// fat functions use fat pointers to track memory allocation with JSON_MALLOC
// and JSON_FREE. this is useful for allocating things that aren't on a json_t
// allocator
static void *json_fat_alloc(size_t size) {
size_t *ptr = (size_t *)JSON_MALLOC(sizeof(*ptr) + size);
*ptr++ = size;
return ptr;
}
static inline void json_fat_free(void *ptr) {
JSON_FREE((size_t *)ptr - 1);
}
static void *json_fat_realloc(void *ptr, size_t size) {
void *new_ptr = json_fat_alloc(size);
if (ptr) {
// copy min(old_size, new_size)
size_t copy_size = *((size_t *)ptr - 1);
if (copy_size > size)
copy_size = size;
memcpy(new_ptr, ptr, copy_size);
json_fat_free(ptr);
}
return new_ptr;
}
static void *json_tracked_alloc(json_t *json, size_t size) {
// allocate tracked pointer
json_tptr_t *tptr = (json_tptr_t *)JSON_MALLOC(sizeof(*tptr) + size);
tptr->size = size;
tptr->index = json->cur_tracked++;
// push tracked pointer on tracked array
if (json->cur_tracked == json->tracked_cap) {
size_t old_cap = json->tracked_cap;
json->tracked_cap <<= 1;
json->tracked = (json_tptr_t **)json_fat_realloc(
json->tracked,
json->tracked_cap * sizeof(*json->tracked)
);
for (size_t i = old_cap; i < json->tracked_cap; ++i)
json->tracked[i] = NULL;
}
json->tracked[tptr->index] = tptr;
JSON_DEBUG("tracked alloc %zu.\n", tptr->index);
return tptr + 1;
}
static void json_tracked_free(json_t *json, void *ptr) {
size_t index = ((json_tptr_t *)ptr - 1)->index;
JSON_FREE(json->tracked[index]);
json->tracked[index] = NULL;
JSON_DEBUG("tracked free %zu.\n", index);
}
// does NOT handle null pointers
static void *json_tracked_realloc(json_t *json, void *ptr, size_t size) {
JSON_ASSERT(ptr, "json_tracked_realloc doesn't support null pointers.\n");
// allocate new tracked pointer
json_tptr_t *old_tptr = (json_tptr_t *)ptr - 1;
json_tptr_t *new_tptr = (json_tptr_t *)JSON_MALLOC(
sizeof(*new_tptr) + size
);
new_tptr->size = size;
new_tptr->index = old_tptr->index;
// copy data
size_t copy_size = old_tptr->size > new_tptr->size
? new_tptr->size : old_tptr->size;
memcpy(new_tptr + 1, ptr, copy_size);
// replace old_tptr in tracked array
JSON_FREE(old_tptr);
json->tracked[new_tptr->index] = new_tptr;
JSON_DEBUG("tracked realloc %zu.\n", new_tptr->index);
return new_tptr + 1;
}
// allocates on a json_t page
static void *json_page_alloc(json_t *json, size_t size) {
// allocate new page when needed
if (json->used + size > JSON_PAGE_SIZE) {
if (size >= JSON_PAGE_SIZE) {
JSON_DEBUG("allocating custom page and new page.\n");
// size too big for pages, give this pointer its own page
json->pages[++json->cur_page] = (char *)JSON_MALLOC(size);
void *ptr = json->pages[json->cur_page];
json->pages[++json->cur_page] = (char *)JSON_MALLOC(JSON_PAGE_SIZE);
json->used = 0;
return ptr;
} else {
JSON_DEBUG("allocating new page.\n");
// allocate new page
if (++json->cur_page == json->page_cap) {
json->page_cap <<= 1;
json->pages = (char **)json_fat_realloc(
json->pages,
json->page_cap * sizeof(*json->pages)
);
}
json->pages[json->cur_page] = (char *)JSON_MALLOC(JSON_PAGE_SIZE);
json->used = 0;
}
}
// return page space
void *ptr = json->pages[json->cur_page] + json->used;
json->used += size;
return ptr;
}
// array (vector) ==============================================================
#define JSON_VEC_INIT_CAP 8
typedef struct json_vec {
void **data; // fat ptr
size_t size, cap, min_cap;
} json_vec_t;
static void json_vec_alloc_one(json_t *json, json_vec_t *vec) {
if (vec->size + 1 > vec->cap) {
vec->cap <<= 1;
vec->data = (void **)json_tracked_realloc(
json,
vec->data,
vec->cap * sizeof(*vec->data)
);
}
}
static void json_vec_free_one(json_t *json, json_vec_t *vec) {
JSON_ASSERT(vec->size, "popped from vec of size zero.\n");
if (vec->cap > vec->min_cap && vec->size < vec->cap >> 2) {
vec->cap >>= 1;
vec->data = (void **)json_tracked_realloc(
json,
vec->data,
vec->cap * sizeof(*vec->data)
);
}
--vec->size;
}
static void json_vec_make(json_t *json, json_vec_t *vec, size_t init_cap) {
vec->size = 0;
vec->min_cap = vec->cap = init_cap;
vec->data = (void **)json_tracked_alloc(
json,
vec->cap * sizeof(*vec->data)
);
}
static void json_vec_push(json_t *json, json_vec_t *vec, void *item) {
json_vec_alloc_one(json, vec);
vec->data[vec->size++] = item;
}
static void *json_vec_pop(json_t *json, json_vec_t *vec) {
json_object_t *object = (json_object_t *)vec->data[vec->size - 1];
json_vec_free_one(json, vec);
return object;
}
static void *json_vec_del(json_t *json, json_vec_t *vec, size_t index) {
JSON_ASSERT(
index < vec->size,
"attempted to delete vec item past it's size.\n"
);
void *item = vec->data[index];
vec->data[index] = json_vec_pop(json, vec);
return item;
}
static void *json_vec_del_ordered(
json_t *json, json_vec_t *vec, size_t index
) {
JSON_ASSERT(
index < vec->size,
"attempted to delete vec item past it's size.\n"
);
void *item = vec->data[index];
memcpy(
vec->data + index,
vec->data + index + 1,
(vec->size - index - 1) * sizeof(*vec->data)
);
json_vec_free_one(json, vec);
return item;
}
// hashmap =====================================================================
#define JSON_HMAP_INIT_CAP 8
#if INTPTR_MAX == INT64_MAX
// 64 bit
typedef uint64_t json_hash_t;
#define JSON_FNV_PRIME 0x00000100000001b3
#define JSON_FNV_BASIS 0xcbf29ce484222325
#else
// 32 bit
typedef uint32_t json_hash_t;
#define JSON_FNV_PRIME 0x01000193a
#define JSON_FNV_BASIS 0x0811c9dc5
#endif
typedef struct json_hnode {
json_object_t *object;
json_hash_t hash;
size_t index, steps;
} json_hnode_t;
typedef struct json_hmap {
json_vec_t vec; // stores keys in order
json_hnode_t *nodes; // fat ptr
size_t size, cap, min_cap;
} json_hmap_t;
// fnv-1a hash function (http://isthe.com/chongo/tech/comp/fnv/)
static json_hash_t json_hash_str(char *str) {
json_hash_t hash = JSON_FNV_BASIS;
while (*str)
hash = (hash ^ *str++) * JSON_FNV_PRIME;
return hash;
}
static json_hnode_t *json_hnodes_alloc(json_t *json, size_t num_nodes) {
json_hnode_t *nodes = (json_hnode_t *)json_tracked_alloc(
json,
num_nodes * sizeof(*nodes)
);
for (size_t i = 0; i < num_nodes; ++i)
nodes[i].hash = 0;
return nodes;
}
static bool json_hmap_put_node(json_t *, json_hmap_t *, json_hnode_t *);
static void json_hmap_rehash(json_t *json, json_hmap_t *hmap, size_t new_cap) {
json_hnode_t *old_nodes = hmap->nodes;
size_t old_cap = hmap->cap;
hmap->cap = new_cap;
hmap->nodes = json_hnodes_alloc(json, hmap->cap);
hmap->size = 0;
for (size_t i = 0; i < old_cap; ++i) {
if (old_nodes[i].hash) {
old_nodes[i].index = old_nodes[i].hash % hmap->cap;
old_nodes[i].steps = 0;
json_hmap_put_node(json, hmap, &old_nodes[i]);
}
}
json_tracked_free(json, old_nodes);
}
static inline void json_hmap_alloc_slot(json_t *json, json_hmap_t *hmap) {
if (hmap->size + 1 > hmap->cap >> 1)
json_hmap_rehash(json, hmap, hmap->cap << 1);
++hmap->size;
}
static inline void json_hmap_free_slot(json_t *json, json_hmap_t *hmap) {
if (hmap->size < hmap->cap >> 2 && hmap->cap > hmap->min_cap)
json_hmap_rehash(json, hmap, hmap->cap >> 1);
--hmap->size;
}
static void json_hmap_make(json_t *json, json_hmap_t *hmap, size_t init_cap) {
json_vec_make(json, &hmap->vec, init_cap);
hmap->size = 0;
hmap->cap = hmap->min_cap = init_cap;
hmap->nodes = json_hnodes_alloc(json, hmap->cap);
}
static json_hnode_t *json_hmap_get_node(json_hmap_t *hmap, json_hash_t hash) {
size_t index = hash % hmap->cap;
// iterate through hash chain until match or empty node is found
while (hmap->nodes[index].hash) {
if (hmap->nodes[index].hash == hash)
return &hmap->nodes[index];
index = (index + 1) % hmap->cap;
}
return NULL;
}
// for rehash + put
// returns whether a previous node has been replaced
static bool json_hmap_put_node(
json_t *json, json_hmap_t *hmap, json_hnode_t *node
) {
size_t index = node->index;
// find suitable bucket
while (hmap->nodes[index].hash) {
if (hmap->nodes[index].hash == node->hash) {
// found matching bucket
hmap->nodes[index].object = node->object;
return true;
}
index = (index + 1) % hmap->cap;
++node->steps;
}
// found empty bucket
hmap->nodes[index] = *node;
json_hmap_alloc_slot(json, hmap);
return false;
}
static void json_hmap_put(
json_t *json, json_hmap_t *hmap, char *key, json_object_t *object
) {
json_hnode_t node;
node.object = object;
node.hash = json_hash_str(key);
node.index = node.hash % hmap->cap;
if (!json_hmap_put_node(json, hmap, &node))
json_vec_push(json, &hmap->vec, key);
}
static json_object_t *json_hmap_get(json_hmap_t *hmap, char *key) {
json_hnode_t *node = json_hmap_get_node(hmap, json_hash_str(key));
return node ? node->object : NULL;
}
static json_object_t *json_hmap_del(
json_t *json, json_hmap_t *hmap, char *key, bool order
) {
json_hash_t hash = json_hash_str(key);
size_t index = hash % hmap->cap;
// find node
while (hmap->nodes[index].hash != hash) {
if (!hmap->nodes[index].hash)
return NULL; // node doesn't exist
index = (index + 1) % hmap->cap;
}
json_object_t *object = hmap->nodes[index].object;
// replace chain
size_t last = index, steps = 0;
while (hmap->nodes[index = (index + 1) % hmap->cap].hash) {
if (hmap->nodes[index].steps >= ++steps) {
// found node that is a valid chain replacement
hmap->nodes[last] = hmap->nodes[index];
hmap->nodes[last].steps -= steps;
last = index;
steps = 0;
}
}
// last node in chain is now a duplicate
hmap->nodes[last].hash = 0;
json_hmap_free_slot(json, hmap);
// remove key from vec
for (size_t i = 0; i < hmap->vec.size; ++i) {
if (!strcmp(key, (char *)hmap->vec.data[i])) {
if (order)
json_vec_del_ordered(json, &hmap->vec, i);
else
json_vec_del(json, &hmap->vec, i);
break;
}
}
return object;
}
// parsing =====================================================================
// for mapping escape sequences
#define JSON_ESCAPE_CHARACTERS_X\
X('"', '\"')\
X('\\', '\\')\
X('/', '/')\
X('b', '\b')\
X('f', '\f')\
X('n', '\n')\
X('r', '\r')\
X('t', '\t')
static bool json_is_whitespace(char ch) {
switch (ch) {
case 0x20:
case 0x0A:
case 0x0D:
case 0x09:
return true;
default:
return false;
}
}
static inline bool json_is_digit(char ch) {
return ch >= '0' && ch <= '9';
}
// skip whitespace to start of next token
static void json_next_token(json_ctx_t *ctx) {
while (1) {
if (!json_is_whitespace(ctx->text[ctx->index]))
return;
++ctx->index;
}
}
// compare next token with passed token
static bool json_token_equals(
json_ctx_t *ctx, const char *token, size_t length
) {
for (size_t i = 0; i < length; ++i)
if (ctx->text[ctx->index + i] != token[i])
return false;
return true;
}
// error if next token does not equal passed token, otherwise skip
static void json_expect_token(
json_ctx_t *ctx, const char *token, size_t length
) {
if (!json_token_equals(ctx, token, length))
JSON_CTX_ERROR(ctx, "unknown token, expected \"%s\".\n", token);
ctx->index += length;
}
// error if next character is not a valid json string character, otherwise
// return char and skip
static char json_expect_str_char(json_ctx_t *ctx) {
if (ctx->text[ctx->index] == '\\') {
// escape codes
char ch;
switch (ctx->text[++ctx->index]) {
#define X(a, b) case a: ch = b; break;
JSON_ESCAPE_CHARACTERS_X
#undef X
case 'u':
JSON_CTX_ERROR(
ctx,
"ghh_json does not support unicode escape sequences currently."
"\n"
);
default:
JSON_CTX_ERROR(
ctx,
"unknown character escape: '%c' (%hhX)\n",
ctx->text[ctx->index], ctx->text[ctx->index]
);
}
++ctx->index;
return ch;
} else {
// raw character
return ctx->text[ctx->index++];
}
}
// return string allocated on ctx allocator if valid string, otherwise error
static char *json_expect_string(json_ctx_t *ctx) {
// verify string and count string length
if (ctx->text[ctx->index++] != '\"')
JSON_CTX_ERROR(ctx, "unknown token, expected string.\n");
size_t start_index = ctx->index;
size_t length = 0;
while (ctx->text[ctx->index] != '\"') {
switch (ctx->text[ctx->index]) {
default:
json_expect_str_char(ctx);
++length;
break;
case '\n':
case '\0':
JSON_CTX_ERROR(ctx, "string ended unexpectedly.\n");
}
}
// read string
char *str = (char *)json_page_alloc(ctx->json, (length + 1) * sizeof(*str));
ctx->index = start_index;
for (size_t i = 0; i < length; ++i)
str[i] = json_expect_str_char(ctx);
str[length] = '\0';
++ctx->index; // skip ending double quote
return str;
}
static double json_expect_number(json_ctx_t *ctx) {
size_t start_index = ctx->index;
// minus symbol
if (ctx->text[ctx->index] == '-')
++ctx->index;
// integral component
if (!json_is_digit(ctx->text[ctx->index]))
JSON_CTX_ERROR(ctx, "expected digit.\n");
while (json_is_digit(ctx->text[ctx->index])) {
++ctx->index;
}
// fractional component
if (ctx->text[ctx->index] == '.') {
++ctx->index;
if (!json_is_digit(ctx->text[ctx->index]))
JSON_CTX_ERROR(ctx, "expected digit.\n");
while (json_is_digit(ctx->text[ctx->index])) {
++ctx->index;
}
}
// exponential component
if (ctx->text[ctx->index] == 'e' || ctx->text[ctx->index] == 'E') {
++ctx->index;
// read exponent
if (ctx->text[ctx->index] == '+' || ctx->text[ctx->index] == '-')
++ctx->index;
if (!json_is_digit(ctx->text[ctx->index]))
JSON_CTX_ERROR(ctx, "expected digit.\n");
while (json_is_digit(ctx->text[ctx->index])) {
++ctx->index;
}
}
// number is valid json and accepted, can parse
char buf[128];
size_t length = ctx->index - start_index;
strncpy(buf, &ctx->text[start_index], length);
return atof(buf);
}
static json_object_t *json_expect_obj(json_ctx_t *, json_object_t *);
static json_object_t *json_expect_array(json_ctx_t *, json_object_t *);
// fills object in with value
static void json_expect_value(json_ctx_t *ctx, json_object_t *object) {
switch (ctx->text[ctx->index]) {
case '{':
json_expect_obj(ctx, object);
object->type = JSON_OBJECT;
break;
case '[':
json_expect_array(ctx, object);
object->type = JSON_ARRAY;
break;
case '"':
object->data.string = json_expect_string(ctx);
object->type = JSON_STRING;
break;
case 't':
json_expect_token(ctx, "true", 4);
object->type = JSON_TRUE;
break;
case 'f':
json_expect_token(ctx, "false", 5);
object->type = JSON_FALSE;
break;
case 'n':
json_expect_token(ctx, "null", 4);
object->type = JSON_NULL;
break;
default:;
// could be number
if (json_is_digit(ctx->text[ctx->index])
|| ctx->text[ctx->index] == '-') {
object->data.number = json_expect_number(ctx);
object->type = JSON_NUMBER;
break;
}
JSON_CTX_ERROR(ctx, "unknown token, expected value.\n");
}
}
static json_object_t *json_expect_array(
json_ctx_t *ctx, json_object_t *object
) {
json_vec_t *vec = (json_vec_t *)json_page_alloc(ctx->json, sizeof(*vec));
json_vec_make(ctx->json, vec, JSON_VEC_INIT_CAP);
object->data.vec = vec;
++ctx->index; // skip '['
// check for empty array
json_next_token(ctx);
if (ctx->text[ctx->index] == ']') {
++ctx->index;
return object;
}
// parse key/value pairs
while (1) {
// get child and store
json_object_t *child = (json_object_t *)json_page_alloc(
ctx->json,
sizeof(*child)
);
json_expect_value(ctx, child);
json_vec_push(ctx->json, vec, child);
// iterate
json_next_token(ctx);
if (ctx->text[ctx->index] == ']') {
++ctx->index;
break;
}
json_expect_token(ctx, ",", 1);
json_next_token(ctx);
}
return object;
}
static json_object_t *json_expect_obj(json_ctx_t *ctx, json_object_t *object) {
json_hmap_t *hmap = (json_hmap_t *)json_page_alloc(
ctx->json,
sizeof(*hmap)
);
json_hmap_make(ctx->json, hmap, JSON_HMAP_INIT_CAP);
object->data.hmap = hmap;
++ctx->index; // skip '{'
// check for empty object
json_next_token(ctx);
if (ctx->text[ctx->index] == '}') {
++ctx->index;
return object;
}
// parse key/value pairs
while (1) {
// get pair and store
json_object_t *child = (json_object_t *)json_page_alloc(
ctx->json,
sizeof(*object)
);
char *key = json_expect_string(ctx);
json_next_token(ctx);
json_expect_token(ctx, ":", 1);
json_next_token(ctx);
json_expect_value(ctx, child);
json_hmap_put(ctx->json, hmap, key, child);
// iterate
json_next_token(ctx);
if (ctx->text[ctx->index] == '}') {
++ctx->index;
break;
}
json_expect_token(ctx, ",", 1);
json_next_token(ctx);
}
return object;
}
static void json_parse(json_t *json, const char *text) {
json_ctx_t ctx;
ctx.json = json;
ctx.text = text;
ctx.index = 0;
// recursive parse at root
json_next_token(&ctx);
switch (ctx.text[ctx.index]) {
case '{':
json->root = (json_object_t *)json_page_alloc(
ctx.json,
sizeof(*json->root)
);
json_expect_obj(&ctx, json->root);
json->root->type = JSON_OBJECT;
json_next_token(&ctx);
json_expect_token(&ctx, "", 1);
break;
case '[':
json->root = (json_object_t *)json_page_alloc(
ctx.json,