-
Notifications
You must be signed in to change notification settings - Fork 8
/
parson.h
2239 lines (2035 loc) · 77.2 KB
/
parson.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
/*
Parson ( http://kgabis.github.com/parson/ )
Copyright (c) 2012 - 2017 Krzysztof Gabis
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.
*/
#ifndef parson_parson_h
#define parson_parson_h
#ifdef __cplusplus
extern "C"
{
#endif
#include <stddef.h> /* size_t */
/* Types and enums */
typedef struct json_object_t JSON_Object;
typedef struct json_array_t JSON_Array;
typedef struct json_value_t JSON_Value;
enum json_value_type {
JSONError = -1,
JSONNull = 1,
JSONString = 2,
JSONNumber = 3,
JSONObject = 4,
JSONArray = 5,
JSONBoolean = 6
};
typedef int JSON_Value_Type;
enum json_result_t {
JSONSuccess = 0,
JSONFailure = -1
};
typedef int JSON_Status;
typedef void * (*JSON_Malloc_Function)(size_t);
typedef void (*JSON_Free_Function)(void *);
/* Call only once, before calling any other function from parson API. If not called, malloc and free
from stdlib will be used for all allocations */
void json_set_allocation_functions(JSON_Malloc_Function malloc_fun, JSON_Free_Function free_fun);
/* Parses first JSON value in a file, returns NULL in case of error */
JSON_Value * json_parse_file(const char *filename);
/* Parses first JSON value in a file and ignores comments (/ * * / and //),
returns NULL in case of error */
JSON_Value * json_parse_file_with_comments(const char *filename);
/* Parses first JSON value in a string, returns NULL in case of error */
JSON_Value * json_parse_string(const char *string);
/* Parses first JSON value in a string and ignores comments (/ * * / and //),
returns NULL in case of error */
JSON_Value * json_parse_string_with_comments(const char *string);
/* Serialization */
size_t json_serialization_size(const JSON_Value *value); /* returns 0 on fail */
JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes);
JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename);
char * json_serialize_to_string(const JSON_Value *value);
/* Pretty serialization */
size_t json_serialization_size_pretty(const JSON_Value *value); /* returns 0 on fail */
JSON_Status json_serialize_to_buffer_pretty(const JSON_Value *value, char *buf, size_t buf_size_in_bytes);
JSON_Status json_serialize_to_file_pretty(const JSON_Value *value, const char *filename);
char * json_serialize_to_string_pretty(const JSON_Value *value);
void json_free_serialized_string(char *string); /* frees string from json_serialize_to_string and json_serialize_to_string_pretty */
/* Comparing */
int json_value_equals(const JSON_Value *a, const JSON_Value *b);
/* Validation
This is *NOT* JSON Schema. It validates json by checking if object have identically
named fields with matching types.
For example schema {"name":"", "age":0} will validate
{"name":"Joe", "age":25} and {"name":"Joe", "age":25, "gender":"m"},
but not {"name":"Joe"} or {"name":"Joe", "age":"Cucumber"}.
In case of arrays, only first value in schema is checked against all values in tested array.
Empty objects ({}) validate all objects, empty arrays ([]) validate all arrays,
null validates values of every type.
*/
JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value);
/*
* JSON Object
*/
JSON_Value * json_object_get_value (const JSON_Object *object, const char *name);
const char * json_object_get_string (const JSON_Object *object, const char *name);
JSON_Object * json_object_get_object (const JSON_Object *object, const char *name);
JSON_Array * json_object_get_array (const JSON_Object *object, const char *name);
double json_object_get_number (const JSON_Object *object, const char *name); /* returns 0 on fail */
int json_object_get_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */
/* dotget functions enable addressing values with dot notation in nested objects,
just like in structs or c++/java/c# objects (e.g. objectA.objectB.value).
Because valid names in JSON can contain dots, some values may be inaccessible
this way. */
JSON_Value * json_object_dotget_value (const JSON_Object *object, const char *name);
const char * json_object_dotget_string (const JSON_Object *object, const char *name);
JSON_Object * json_object_dotget_object (const JSON_Object *object, const char *name);
JSON_Array * json_object_dotget_array (const JSON_Object *object, const char *name);
double json_object_dotget_number (const JSON_Object *object, const char *name); /* returns 0 on fail */
int json_object_dotget_boolean(const JSON_Object *object, const char *name); /* returns -1 on fail */
/* Functions to get available names */
size_t json_object_get_count (const JSON_Object *object);
const char * json_object_get_name (const JSON_Object *object, size_t index);
JSON_Value * json_object_get_value_at(const JSON_Object *object, size_t index);
JSON_Value * json_object_get_wrapping_value(const JSON_Object *object);
/* Functions to check if object has a value with a specific name. Returned value is 1 if object has
* a value and 0 if it doesn't. dothas functions behave exactly like dotget functions. */
int json_object_has_value (const JSON_Object *object, const char *name);
int json_object_has_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type);
int json_object_dothas_value (const JSON_Object *object, const char *name);
int json_object_dothas_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type);
/* Creates new name-value pair or frees and replaces old value with a new one.
* json_object_set_value does not copy passed value so it shouldn't be freed afterwards. */
JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value);
JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string);
JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number);
JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean);
JSON_Status json_object_set_null(JSON_Object *object, const char *name);
/* Works like dotget functions, but creates whole hierarchy if necessary.
* json_object_dotset_value does not copy passed value so it shouldn't be freed afterwards. */
JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value);
JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string);
JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number);
JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean);
JSON_Status json_object_dotset_null(JSON_Object *object, const char *name);
/* Frees and removes name-value pair */
JSON_Status json_object_remove(JSON_Object *object, const char *name);
/* Works like dotget function, but removes name-value pair only on exact match. */
JSON_Status json_object_dotremove(JSON_Object *object, const char *key);
/* Removes all name-value pairs in object */
JSON_Status json_object_clear(JSON_Object *object);
/*
*JSON Array
*/
JSON_Value * json_array_get_value (const JSON_Array *array, size_t index);
const char * json_array_get_string (const JSON_Array *array, size_t index);
JSON_Object * json_array_get_object (const JSON_Array *array, size_t index);
JSON_Array * json_array_get_array (const JSON_Array *array, size_t index);
double json_array_get_number (const JSON_Array *array, size_t index); /* returns 0 on fail */
int json_array_get_boolean(const JSON_Array *array, size_t index); /* returns -1 on fail */
size_t json_array_get_count (const JSON_Array *array);
JSON_Value * json_array_get_wrapping_value(const JSON_Array *array);
/* Frees and removes value at given index, does nothing and returns JSONFailure if index doesn't exist.
* Order of values in array may change during execution. */
JSON_Status json_array_remove(JSON_Array *array, size_t i);
/* Frees and removes from array value at given index and replaces it with given one.
* Does nothing and returns JSONFailure if index doesn't exist.
* json_array_replace_value does not copy passed value so it shouldn't be freed afterwards. */
JSON_Status json_array_replace_value(JSON_Array *array, size_t i, JSON_Value *value);
JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string);
JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number);
JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean);
JSON_Status json_array_replace_null(JSON_Array *array, size_t i);
/* Frees and removes all values from array */
JSON_Status json_array_clear(JSON_Array *array);
/* Appends new value at the end of array.
* json_array_append_value does not copy passed value so it shouldn't be freed afterwards. */
JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value);
JSON_Status json_array_append_string(JSON_Array *array, const char *string);
JSON_Status json_array_append_number(JSON_Array *array, double number);
JSON_Status json_array_append_boolean(JSON_Array *array, int boolean);
JSON_Status json_array_append_null(JSON_Array *array);
/*
*JSON Value
*/
JSON_Value * json_value_init_object (void);
JSON_Value * json_value_init_array (void);
JSON_Value * json_value_init_string (const char *string); /* copies passed string */
JSON_Value * json_value_init_number (double number);
JSON_Value * json_value_init_boolean(int boolean);
JSON_Value * json_value_init_null (void);
JSON_Value * json_value_deep_copy (const JSON_Value *value);
void json_value_free (JSON_Value *value);
JSON_Value_Type json_value_get_type (const JSON_Value *value);
JSON_Object * json_value_get_object (const JSON_Value *value);
JSON_Array * json_value_get_array (const JSON_Value *value);
const char * json_value_get_string (const JSON_Value *value);
double json_value_get_number (const JSON_Value *value);
int json_value_get_boolean(const JSON_Value *value);
JSON_Value * json_value_get_parent (const JSON_Value *value);
/* Same as above, but shorter */
JSON_Value_Type json_type (const JSON_Value *value);
JSON_Object * json_object (const JSON_Value *value);
JSON_Array * json_array (const JSON_Value *value);
const char * json_string (const JSON_Value *value);
double json_number (const JSON_Value *value);
int json_boolean(const JSON_Value *value);
#ifdef __cplusplus
}
#endif
#endif
#ifdef PARSON_IMPLEMENTATION
/*
Parson ( http://kgabis.github.com/parson/ )
Copyright (c) 2012 - 2017 Krzysztof Gabis
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.
*/
#ifdef _MSC_VER
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif /* _CRT_SECURE_NO_WARNINGS */
#endif /* _MSC_VER */
//#include "parson.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
/* Apparently sscanf is not implemented in some "standard" libraries, so don't use it, if you
* don't have to. */
#define sscanf THINK_TWICE_ABOUT_USING_SSCANF
#define STARTING_CAPACITY 16
#define MAX_NESTING 2048
#define FLOAT_FORMAT "%1.17g"
#define SIZEOF_TOKEN(a) (sizeof(a) - 1)
#define SKIP_CHAR(str) ((*str)++)
#define SKIP_WHITESPACES(str) while (isspace(**str)) { SKIP_CHAR(str); }
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#undef malloc
#undef free
static JSON_Malloc_Function parson_malloc = malloc;
static JSON_Free_Function parson_free = free;
#define IS_CONT(b) (((unsigned char)(b) & 0xC0) == 0x80) /* is utf-8 continuation byte */
/* Type definitions */
typedef union json_value_value {
char *string;
double number;
JSON_Object *object;
JSON_Array *array;
int boolean;
int null;
} JSON_Value_Value;
struct json_value_t {
JSON_Value *parent;
JSON_Value_Type type;
JSON_Value_Value value;
};
struct json_object_t {
JSON_Value *wrapping_value;
char **names;
JSON_Value **values;
size_t count;
size_t capacity;
};
struct json_array_t {
JSON_Value *wrapping_value;
JSON_Value **items;
size_t count;
size_t capacity;
};
/* Various */
static char * read_file(const char *filename);
static void remove_comments(char *string, const char *start_token, const char *end_token);
static char * parson_strndup(const char *string, size_t n);
static char * parson_strdup(const char *string);
static int hex_char_to_int(char c);
static int parse_utf16_hex(const char *string, unsigned int *result);
static int num_bytes_in_utf8_sequence(unsigned char c);
static int verify_utf8_sequence(const unsigned char *string, int *len);
static int is_valid_utf8(const char *string, size_t string_len);
static int is_decimal(const char *string, size_t length);
/* JSON Object */
static JSON_Object * json_object_init(JSON_Value *wrapping_value);
static JSON_Status json_object_add(JSON_Object *object, const char *name, JSON_Value *value);
static JSON_Status json_object_resize(JSON_Object *object, size_t new_capacity);
static JSON_Value * json_object_nget_value(const JSON_Object *object, const char *name, size_t n);
static void json_object_free(JSON_Object *object);
/* JSON Array */
static JSON_Array * json_array_init(JSON_Value *wrapping_value);
static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value);
static JSON_Status json_array_resize(JSON_Array *array, size_t new_capacity);
static void json_array_free(JSON_Array *array);
/* JSON Value */
static JSON_Value * json_value_init_string_no_copy(char *string);
/* Parser */
static JSON_Status skip_quotes(const char **string);
static int parse_utf16(const char **unprocessed, char **processed);
static char * process_string(const char *input, size_t len);
static char * get_quoted_string(const char **string);
static JSON_Value * parse_object_value(const char **string, size_t nesting);
static JSON_Value * parse_array_value(const char **string, size_t nesting);
static JSON_Value * parse_string_value(const char **string);
static JSON_Value * parse_boolean_value(const char **string);
static JSON_Value * parse_number_value(const char **string);
static JSON_Value * parse_null_value(const char **string);
static JSON_Value * parse_value(const char **string, size_t nesting);
/* Serialization */
static int json_serialize_to_buffer_r(const JSON_Value *value, char *buf, int level, int is_pretty, char *num_buf);
static int json_serialize_string(const char *string, char *buf);
static int append_indent(char *buf, int level);
static int append_string(char *buf, const char *string);
/* Various */
static char * parson_strndup(const char *string, size_t n) {
char *output_string = (char*)parson_malloc(n + 1);
if (!output_string) {
return NULL;
}
output_string[n] = '\0';
strncpy(output_string, string, n);
return output_string;
}
static char * parson_strdup(const char *string) {
return parson_strndup(string, strlen(string));
}
static int hex_char_to_int(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
static int parse_utf16_hex(const char *s, unsigned int *result) {
int x1, x2, x3, x4;
if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0' || s[3] == '\0') {
return 0;
}
x1 = hex_char_to_int(s[0]);
x2 = hex_char_to_int(s[1]);
x3 = hex_char_to_int(s[2]);
x4 = hex_char_to_int(s[3]);
if (x1 == -1 || x2 == -1 || x3 == -1 || x4 == -1) {
return 0;
}
*result = (unsigned int)((x1 << 12) | (x2 << 8) | (x3 << 4) | x4);
return 1;
}
static int num_bytes_in_utf8_sequence(unsigned char c) {
if (c == 0xC0 || c == 0xC1 || c > 0xF4 || IS_CONT(c)) {
return 0;
} else if ((c & 0x80) == 0) { /* 0xxxxxxx */
return 1;
} else if ((c & 0xE0) == 0xC0) { /* 110xxxxx */
return 2;
} else if ((c & 0xF0) == 0xE0) { /* 1110xxxx */
return 3;
} else if ((c & 0xF8) == 0xF0) { /* 11110xxx */
return 4;
}
return 0; /* won't happen */
}
static int verify_utf8_sequence(const unsigned char *string, int *len) {
unsigned int cp = 0;
*len = num_bytes_in_utf8_sequence(string[0]);
if (*len == 1) {
cp = string[0];
} else if (*len == 2 && IS_CONT(string[1])) {
cp = string[0] & 0x1F;
cp = (cp << 6) | (string[1] & 0x3F);
} else if (*len == 3 && IS_CONT(string[1]) && IS_CONT(string[2])) {
cp = ((unsigned char)string[0]) & 0xF;
cp = (cp << 6) | (string[1] & 0x3F);
cp = (cp << 6) | (string[2] & 0x3F);
} else if (*len == 4 && IS_CONT(string[1]) && IS_CONT(string[2]) && IS_CONT(string[3])) {
cp = string[0] & 0x7;
cp = (cp << 6) | (string[1] & 0x3F);
cp = (cp << 6) | (string[2] & 0x3F);
cp = (cp << 6) | (string[3] & 0x3F);
} else {
return 0;
}
/* overlong encodings */
if ((cp < 0x80 && *len > 1) ||
(cp < 0x800 && *len > 2) ||
(cp < 0x10000 && *len > 3)) {
return 0;
}
/* invalid unicode */
if (cp > 0x10FFFF) {
return 0;
}
/* surrogate halves */
if (cp >= 0xD800 && cp <= 0xDFFF) {
return 0;
}
return 1;
}
static int is_valid_utf8(const char *string, size_t string_len) {
int len = 0;
const char *string_end = string + string_len;
while (string < string_end) {
if (!verify_utf8_sequence((const unsigned char*)string, &len)) {
return 0;
}
string += len;
}
return 1;
}
static int is_decimal(const char *string, size_t length) {
if (length > 1 && string[0] == '0' && string[1] != '.') {
return 0;
}
if (length > 2 && !strncmp(string, "-0", 2) && string[2] != '.') {
return 0;
}
while (length--) {
if (strchr("xX", string[length])) {
return 0;
}
}
return 1;
}
static char * read_file(const char * filename) {
FILE *fp = fopen(filename, "r");
size_t file_size;
long pos;
char *file_contents;
if (!fp) {
return NULL;
}
fseek(fp, 0L, SEEK_END);
pos = ftell(fp);
if (pos < 0) {
fclose(fp);
return NULL;
}
file_size = pos;
rewind(fp);
file_contents = (char*)parson_malloc(sizeof(char) * (file_size + 1));
if (!file_contents) {
fclose(fp);
return NULL;
}
if (fread(file_contents, file_size, 1, fp) < 1) {
if (ferror(fp)) {
fclose(fp);
parson_free(file_contents);
return NULL;
}
}
fclose(fp);
file_contents[file_size] = '\0';
return file_contents;
}
static void remove_comments(char *string, const char *start_token, const char *end_token) {
int in_string = 0, escaped = 0;
size_t i;
char *ptr = NULL, current_char;
size_t start_token_len = strlen(start_token);
size_t end_token_len = strlen(end_token);
if (start_token_len == 0 || end_token_len == 0) {
return;
}
while ((current_char = *string) != '\0') {
if (current_char == '\\' && !escaped) {
escaped = 1;
string++;
continue;
} else if (current_char == '\"' && !escaped) {
in_string = !in_string;
} else if (!in_string && strncmp(string, start_token, start_token_len) == 0) {
for(i = 0; i < start_token_len; i++) {
string[i] = ' ';
}
string = string + start_token_len;
ptr = strstr(string, end_token);
if (!ptr) {
return;
}
for (i = 0; i < (ptr - string) + end_token_len; i++) {
string[i] = ' ';
}
string = ptr + end_token_len - 1;
}
escaped = 0;
string++;
}
}
/* JSON Object */
static JSON_Object * json_object_init(JSON_Value *wrapping_value) {
JSON_Object *new_obj = (JSON_Object*)parson_malloc(sizeof(JSON_Object));
if (new_obj == NULL) {
return NULL;
}
new_obj->wrapping_value = wrapping_value;
new_obj->names = (char**)NULL;
new_obj->values = (JSON_Value**)NULL;
new_obj->capacity = 0;
new_obj->count = 0;
return new_obj;
}
static JSON_Status json_object_add(JSON_Object *object, const char *name, JSON_Value *value) {
size_t index = 0;
if (object == NULL || name == NULL || value == NULL) {
return JSONFailure;
}
if (json_object_get_value(object, name) != NULL) {
return JSONFailure;
}
if (object->count >= object->capacity) {
size_t new_capacity = MAX(object->capacity * 2, STARTING_CAPACITY);
if (json_object_resize(object, new_capacity) == JSONFailure) {
return JSONFailure;
}
}
index = object->count;
object->names[index] = parson_strdup(name);
if (object->names[index] == NULL) {
return JSONFailure;
}
value->parent = json_object_get_wrapping_value(object);
object->values[index] = value;
object->count++;
return JSONSuccess;
}
static JSON_Status json_object_resize(JSON_Object *object, size_t new_capacity) {
char **temp_names = NULL;
JSON_Value **temp_values = NULL;
if ((object->names == NULL && object->values != NULL) ||
(object->names != NULL && object->values == NULL) ||
new_capacity == 0) {
return JSONFailure; /* Shouldn't happen */
}
temp_names = (char**)parson_malloc(new_capacity * sizeof(char*));
if (temp_names == NULL) {
return JSONFailure;
}
temp_values = (JSON_Value**)parson_malloc(new_capacity * sizeof(JSON_Value*));
if (temp_values == NULL) {
parson_free(temp_names);
return JSONFailure;
}
if (object->names != NULL && object->values != NULL && object->count > 0) {
memcpy(temp_names, object->names, object->count * sizeof(char*));
memcpy(temp_values, object->values, object->count * sizeof(JSON_Value*));
}
parson_free(object->names);
parson_free(object->values);
object->names = temp_names;
object->values = temp_values;
object->capacity = new_capacity;
return JSONSuccess;
}
static JSON_Value * json_object_nget_value(const JSON_Object *object, const char *name, size_t n) {
size_t i, name_length;
for (i = 0; i < json_object_get_count(object); i++) {
name_length = strlen(object->names[i]);
if (name_length != n) {
continue;
}
if (strncmp(object->names[i], name, n) == 0) {
return object->values[i];
}
}
return NULL;
}
static void json_object_free(JSON_Object *object) {
size_t i;
for (i = 0; i < object->count; i++) {
parson_free(object->names[i]);
json_value_free(object->values[i]);
}
parson_free(object->names);
parson_free(object->values);
parson_free(object);
}
/* JSON Array */
static JSON_Array * json_array_init(JSON_Value *wrapping_value) {
JSON_Array *new_array = (JSON_Array*)parson_malloc(sizeof(JSON_Array));
if (new_array == NULL) {
return NULL;
}
new_array->wrapping_value = wrapping_value;
new_array->items = (JSON_Value**)NULL;
new_array->capacity = 0;
new_array->count = 0;
return new_array;
}
static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value) {
if (array->count >= array->capacity) {
size_t new_capacity = MAX(array->capacity * 2, STARTING_CAPACITY);
if (json_array_resize(array, new_capacity) == JSONFailure) {
return JSONFailure;
}
}
value->parent = json_array_get_wrapping_value(array);
array->items[array->count] = value;
array->count++;
return JSONSuccess;
}
static JSON_Status json_array_resize(JSON_Array *array, size_t new_capacity) {
JSON_Value **new_items = NULL;
if (new_capacity == 0) {
return JSONFailure;
}
new_items = (JSON_Value**)parson_malloc(new_capacity * sizeof(JSON_Value*));
if (new_items == NULL) {
return JSONFailure;
}
if (array->items != NULL && array->count > 0) {
memcpy(new_items, array->items, array->count * sizeof(JSON_Value*));
}
parson_free(array->items);
array->items = new_items;
array->capacity = new_capacity;
return JSONSuccess;
}
static void json_array_free(JSON_Array *array) {
size_t i;
for (i = 0; i < array->count; i++) {
json_value_free(array->items[i]);
}
parson_free(array->items);
parson_free(array);
}
/* JSON Value */
static JSON_Value * json_value_init_string_no_copy(char *string) {
JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
if (!new_value) {
return NULL;
}
new_value->parent = NULL;
new_value->type = JSONString;
new_value->value.string = string;
return new_value;
}
/* Parser */
static JSON_Status skip_quotes(const char **string) {
if (**string != '\"') {
return JSONFailure;
}
SKIP_CHAR(string);
while (**string != '\"') {
if (**string == '\0') {
return JSONFailure;
} else if (**string == '\\') {
SKIP_CHAR(string);
if (**string == '\0') {
return JSONFailure;
}
}
SKIP_CHAR(string);
}
SKIP_CHAR(string);
return JSONSuccess;
}
static int parse_utf16(const char **unprocessed, char **processed) {
unsigned int cp, lead, trail;
int parse_succeeded = 0;
char *processed_ptr = *processed;
const char *unprocessed_ptr = *unprocessed;
unprocessed_ptr++; /* skips u */
parse_succeeded = parse_utf16_hex(unprocessed_ptr, &cp);
if (!parse_succeeded) {
return JSONFailure;
}
if (cp < 0x80) {
processed_ptr[0] = (char)cp; /* 0xxxxxxx */
} else if (cp < 0x800) {
processed_ptr[0] = ((cp >> 6) & 0x1F) | 0xC0; /* 110xxxxx */
processed_ptr[1] = ((cp) & 0x3F) | 0x80; /* 10xxxxxx */
processed_ptr += 1;
} else if (cp < 0xD800 || cp > 0xDFFF) {
processed_ptr[0] = ((cp >> 12) & 0x0F) | 0xE0; /* 1110xxxx */
processed_ptr[1] = ((cp >> 6) & 0x3F) | 0x80; /* 10xxxxxx */
processed_ptr[2] = ((cp) & 0x3F) | 0x80; /* 10xxxxxx */
processed_ptr += 2;
} else if (cp >= 0xD800 && cp <= 0xDBFF) { /* lead surrogate (0xD800..0xDBFF) */
lead = cp;
unprocessed_ptr += 4; /* should always be within the buffer, otherwise previous sscanf would fail */
if (*unprocessed_ptr++ != '\\' || *unprocessed_ptr++ != 'u') {
return JSONFailure;
}
parse_succeeded = parse_utf16_hex(unprocessed_ptr, &trail);
if (!parse_succeeded || trail < 0xDC00 || trail > 0xDFFF) { /* valid trail surrogate? (0xDC00..0xDFFF) */
return JSONFailure;
}
cp = ((((lead - 0xD800) & 0x3FF) << 10) | ((trail - 0xDC00) & 0x3FF)) + 0x010000;
processed_ptr[0] = (((cp >> 18) & 0x07) | 0xF0); /* 11110xxx */
processed_ptr[1] = (((cp >> 12) & 0x3F) | 0x80); /* 10xxxxxx */
processed_ptr[2] = (((cp >> 6) & 0x3F) | 0x80); /* 10xxxxxx */
processed_ptr[3] = (((cp) & 0x3F) | 0x80); /* 10xxxxxx */
processed_ptr += 3;
} else { /* trail surrogate before lead surrogate */
return JSONFailure;
}
unprocessed_ptr += 3;
*processed = processed_ptr;
*unprocessed = unprocessed_ptr;
return JSONSuccess;
}
/* Copies and processes passed string up to supplied length.
Example: "\u006Corem ipsum" -> lorem ipsum */
static char* process_string(const char *input, size_t len) {
const char *input_ptr = input;
size_t initial_size = (len + 1) * sizeof(char);
size_t final_size = 0;
char *output = NULL, *output_ptr = NULL, *resized_output = NULL;
output = (char*)parson_malloc(initial_size);
if (output == NULL) {
goto error;
}
output_ptr = output;
while ((*input_ptr != '\0') && (size_t)(input_ptr - input) < len) {
if (*input_ptr == '\\') {
input_ptr++;
switch (*input_ptr) {
case '\"': *output_ptr = '\"'; break;
case '\\': *output_ptr = '\\'; break;
case '/': *output_ptr = '/'; break;
case 'b': *output_ptr = '\b'; break;
case 'f': *output_ptr = '\f'; break;
case 'n': *output_ptr = '\n'; break;
case 'r': *output_ptr = '\r'; break;
case 't': *output_ptr = '\t'; break;
case 'u':
if (parse_utf16(&input_ptr, &output_ptr) == JSONFailure) {
goto error;
}
break;
default:
goto error;
}
} else if ((unsigned char)*input_ptr < 0x20) {
goto error; /* 0x00-0x19 are invalid characters for json string (http://www.ietf.org/rfc/rfc4627.txt) */
} else {
*output_ptr = *input_ptr;
}
output_ptr++;
input_ptr++;
}
*output_ptr = '\0';
/* resize to new length */
final_size = (size_t)(output_ptr-output) + 1;
/* todo: don't resize if final_size == initial_size */
resized_output = (char*)parson_malloc(final_size);
if (resized_output == NULL) {
goto error;
}
memcpy(resized_output, output, final_size);
parson_free(output);
return resized_output;
error:
parson_free(output);
return NULL;
}
/* Return processed contents of a string between quotes and
skips passed argument to a matching quote. */
static char * get_quoted_string(const char **string) {
const char *string_start = *string;
size_t string_len = 0;
JSON_Status status = skip_quotes(string);
if (status != JSONSuccess) {
return NULL;
}
string_len = *string - string_start - 2; /* length without quotes */
return process_string(string_start + 1, string_len);
}
static JSON_Value * parse_value(const char **string, size_t nesting) {
if (nesting > MAX_NESTING) {
return NULL;
}
SKIP_WHITESPACES(string);
switch (**string) {
case '{':
return parse_object_value(string, nesting + 1);
case '[':
return parse_array_value(string, nesting + 1);
case '\"':
return parse_string_value(string);
case 'f': case 't':
return parse_boolean_value(string);
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return parse_number_value(string);
case 'n':
return parse_null_value(string);
default:
return NULL;
}
}
static JSON_Value * parse_object_value(const char **string, size_t nesting) {
JSON_Value *output_value = json_value_init_object(), *new_value = NULL;
JSON_Object *output_object = json_value_get_object(output_value);
char *new_key = NULL;
if (output_value == NULL || **string != '{') {
return NULL;
}
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
if (**string == '}') { /* empty object */
SKIP_CHAR(string);
return output_value;
}
while (**string != '\0') {
new_key = get_quoted_string(string);
if (new_key == NULL) {
json_value_free(output_value);
return NULL;
}
SKIP_WHITESPACES(string);
if (**string != ':') {
parson_free(new_key);
json_value_free(output_value);
return NULL;
}
SKIP_CHAR(string);
new_value = parse_value(string, nesting);
if (new_value == NULL) {
parson_free(new_key);
json_value_free(output_value);
return NULL;
}
if (json_object_add(output_object, new_key, new_value) == JSONFailure) {
parson_free(new_key);
json_value_free(new_value);
json_value_free(output_value);
return NULL;
}
parson_free(new_key);
SKIP_WHITESPACES(string);
if (**string != ',') {
break;
}
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
}
SKIP_WHITESPACES(string);
if (**string != '}' || /* Trim object after parsing is over */
json_object_resize(output_object, json_object_get_count(output_object)) == JSONFailure) {
json_value_free(output_value);
return NULL;
}
SKIP_CHAR(string);
return output_value;
}
static JSON_Value * parse_array_value(const char **string, size_t nesting) {
JSON_Value *output_value = json_value_init_array(), *new_array_value = NULL;
JSON_Array *output_array = json_value_get_array(output_value);
if (!output_value || **string != '[') {
return NULL;
}
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
if (**string == ']') { /* empty array */
SKIP_CHAR(string);
return output_value;
}
while (**string != '\0') {
new_array_value = parse_value(string, nesting);
if (new_array_value == NULL) {
json_value_free(output_value);
return NULL;
}
if (json_array_add(output_array, new_array_value) == JSONFailure) {
json_value_free(new_array_value);
json_value_free(output_value);
return NULL;
}
SKIP_WHITESPACES(string);
if (**string != ',') {
break;
}
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
}
SKIP_WHITESPACES(string);
if (**string != ']' || /* Trim array after parsing is over */
json_array_resize(output_array, json_array_get_count(output_array)) == JSONFailure) {
json_value_free(output_value);
return NULL;
}
SKIP_CHAR(string);
return output_value;
}
static JSON_Value * parse_string_value(const char **string) {
JSON_Value *value = NULL;
char *new_string = get_quoted_string(string);
if (new_string == NULL) {
return NULL;
}
value = json_value_init_string_no_copy(new_string);
if (value == NULL) {
parson_free(new_string);
return NULL;
}
return value;
}
static JSON_Value * parse_boolean_value(const char **string) {