-
Notifications
You must be signed in to change notification settings - Fork 266
/
yyjson.h
8135 lines (6883 loc) · 310 KB
/
yyjson.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
/*==============================================================================
Copyright (c) 2020 YaoYuan <ibireme@gmail.com>
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.
*============================================================================*/
/**
@file yyjson.h
@date 2019-03-09
@author YaoYuan
*/
#ifndef YYJSON_H
#define YYJSON_H
/*==============================================================================
* Header Files
*============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <limits.h>
#include <string.h>
#include <float.h>
/*==============================================================================
* Compile-time Options
*============================================================================*/
/*
Define as 1 to disable JSON reader if JSON parsing is not required.
This will disable these functions at compile-time:
- yyjson_read()
- yyjson_read_opts()
- yyjson_read_file()
- yyjson_read_number()
- yyjson_mut_read_number()
This will reduce the binary size by about 60%.
*/
#ifndef YYJSON_DISABLE_READER
#endif
/*
Define as 1 to disable JSON writer if JSON serialization is not required.
This will disable these functions at compile-time:
- yyjson_write()
- yyjson_write_file()
- yyjson_write_opts()
- yyjson_val_write()
- yyjson_val_write_file()
- yyjson_val_write_opts()
- yyjson_mut_write()
- yyjson_mut_write_file()
- yyjson_mut_write_opts()
- yyjson_mut_val_write()
- yyjson_mut_val_write_file()
- yyjson_mut_val_write_opts()
This will reduce the binary size by about 30%.
*/
#ifndef YYJSON_DISABLE_WRITER
#endif
/*
Define as 1 to disable JSON Pointer, JSON Patch and JSON Merge Patch supports.
This will disable these functions at compile-time:
- yyjson_ptr_xxx()
- yyjson_mut_ptr_xxx()
- yyjson_doc_ptr_xxx()
- yyjson_mut_doc_ptr_xxx()
- yyjson_patch()
- yyjson_mut_patch()
- yyjson_merge_patch()
- yyjson_mut_merge_patch()
*/
#ifndef YYJSON_DISABLE_UTILS
#endif
/*
Define as 1 to disable the fast floating-point number conversion in yyjson,
and use libc's `strtod/snprintf` instead.
This will reduce the binary size by about 30%, but significantly slow down the
floating-point read/write speed.
*/
#ifndef YYJSON_DISABLE_FAST_FP_CONV
#endif
/*
Define as 1 to disable non-standard JSON support at compile-time:
- Reading and writing inf/nan literal, such as `NaN`, `-Infinity`.
- Single line and multiple line comments.
- Single trailing comma at the end of an object or array.
- Invalid unicode in string value.
This will also invalidate these run-time options:
- YYJSON_READ_ALLOW_INF_AND_NAN
- YYJSON_READ_ALLOW_COMMENTS
- YYJSON_READ_ALLOW_TRAILING_COMMAS
- YYJSON_READ_ALLOW_INVALID_UNICODE
- YYJSON_WRITE_ALLOW_INF_AND_NAN
- YYJSON_WRITE_ALLOW_INVALID_UNICODE
This will reduce the binary size by about 10%, and speed up the reading and
writing speed by about 2% to 6%.
*/
#ifndef YYJSON_DISABLE_NON_STANDARD
#endif
/*
Define as 1 to disable UTF-8 validation at compile time.
If all input strings are guaranteed to be valid UTF-8 encoding (for example,
some language's String object has already validated the encoding), using this
flag can avoid redundant UTF-8 validation in yyjson.
This flag can speed up the reading and writing speed of non-ASCII encoded
strings by about 3% to 7%.
Note: If this flag is used while passing in illegal UTF-8 strings, the
following errors may occur:
- Escaped characters may be ignored when parsing JSON strings.
- Ending quotes may be ignored when parsing JSON strings, causing the string
to be concatenated to the next value.
- When accessing `yyjson_mut_val` for serialization, the string ending may be
accessed out of bounds, causing a segmentation fault.
*/
#ifndef YYJSON_DISABLE_UTF8_VALIDATION
#endif
/*
Define as 1 to indicate that the target architecture does not support unaligned
memory access. Please refer to the comments in the C file for details.
*/
#ifndef YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
#endif
/* Define as 1 to export symbols when building this library as Windows DLL. */
#ifndef YYJSON_EXPORTS
#endif
/* Define as 1 to import symbols when using this library as Windows DLL. */
#ifndef YYJSON_IMPORTS
#endif
/* Define as 1 to include <stdint.h> for compiler which doesn't support C99. */
#ifndef YYJSON_HAS_STDINT_H
#endif
/* Define as 1 to include <stdbool.h> for compiler which doesn't support C99. */
#ifndef YYJSON_HAS_STDBOOL_H
#endif
/*==============================================================================
* Compiler Macros
*============================================================================*/
/** compiler version (MSVC) */
#ifdef _MSC_VER
# define YYJSON_MSC_VER _MSC_VER
#else
# define YYJSON_MSC_VER 0
#endif
/** compiler version (GCC) */
#ifdef __GNUC__
# define YYJSON_GCC_VER __GNUC__
# if defined(__GNUC_PATCHLEVEL__)
# define yyjson_gcc_available(major, minor, patch) \
((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \
>= (major * 10000 + minor * 100 + patch))
# else
# define yyjson_gcc_available(major, minor, patch) \
((__GNUC__ * 10000 + __GNUC_MINOR__ * 100) \
>= (major * 10000 + minor * 100 + patch))
# endif
#else
# define YYJSON_GCC_VER 0
# define yyjson_gcc_available(major, minor, patch) 0
#endif
/** real gcc check */
#if !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__ICC) && \
defined(__GNUC__)
# define YYJSON_IS_REAL_GCC 1
#else
# define YYJSON_IS_REAL_GCC 0
#endif
/** C version (STDC) */
#if defined(__STDC__) && (__STDC__ >= 1) && defined(__STDC_VERSION__)
# define YYJSON_STDC_VER __STDC_VERSION__
#else
# define YYJSON_STDC_VER 0
#endif
/** C++ version */
#if defined(__cplusplus)
# define YYJSON_CPP_VER __cplusplus
#else
# define YYJSON_CPP_VER 0
#endif
/** compiler builtin check (since gcc 10.0, clang 2.6, icc 2021) */
#ifndef yyjson_has_builtin
# ifdef __has_builtin
# define yyjson_has_builtin(x) __has_builtin(x)
# else
# define yyjson_has_builtin(x) 0
# endif
#endif
/** compiler attribute check (since gcc 5.0, clang 2.9, icc 17) */
#ifndef yyjson_has_attribute
# ifdef __has_attribute
# define yyjson_has_attribute(x) __has_attribute(x)
# else
# define yyjson_has_attribute(x) 0
# endif
#endif
/** compiler feature check (since clang 2.6, icc 17) */
#ifndef yyjson_has_feature
# ifdef __has_feature
# define yyjson_has_feature(x) __has_feature(x)
# else
# define yyjson_has_feature(x) 0
# endif
#endif
/** include check (since gcc 5.0, clang 2.7, icc 16, msvc 2017 15.3) */
#ifndef yyjson_has_include
# ifdef __has_include
# define yyjson_has_include(x) __has_include(x)
# else
# define yyjson_has_include(x) 0
# endif
#endif
/** inline for compiler */
#ifndef yyjson_inline
# if YYJSON_MSC_VER >= 1200
# define yyjson_inline __forceinline
# elif defined(_MSC_VER)
# define yyjson_inline __inline
# elif yyjson_has_attribute(always_inline) || YYJSON_GCC_VER >= 4
# define yyjson_inline __inline__ __attribute__((always_inline))
# elif defined(__clang__) || defined(__GNUC__)
# define yyjson_inline __inline__
# elif defined(__cplusplus) || YYJSON_STDC_VER >= 199901L
# define yyjson_inline inline
# else
# define yyjson_inline
# endif
#endif
/** noinline for compiler */
#ifndef yyjson_noinline
# if YYJSON_MSC_VER >= 1400
# define yyjson_noinline __declspec(noinline)
# elif yyjson_has_attribute(noinline) || YYJSON_GCC_VER >= 4
# define yyjson_noinline __attribute__((noinline))
# else
# define yyjson_noinline
# endif
#endif
/** align for compiler */
#ifndef yyjson_align
# if YYJSON_MSC_VER >= 1300
# define yyjson_align(x) __declspec(align(x))
# elif yyjson_has_attribute(aligned) || defined(__GNUC__)
# define yyjson_align(x) __attribute__((aligned(x)))
# elif YYJSON_CPP_VER >= 201103L
# define yyjson_align(x) alignas(x)
# else
# define yyjson_align(x)
# endif
#endif
/** likely for compiler */
#ifndef yyjson_likely
# if yyjson_has_builtin(__builtin_expect) || \
(YYJSON_GCC_VER >= 4 && YYJSON_GCC_VER != 5)
# define yyjson_likely(expr) __builtin_expect(!!(expr), 1)
# else
# define yyjson_likely(expr) (expr)
# endif
#endif
/** unlikely for compiler */
#ifndef yyjson_unlikely
# if yyjson_has_builtin(__builtin_expect) || \
(YYJSON_GCC_VER >= 4 && YYJSON_GCC_VER != 5)
# define yyjson_unlikely(expr) __builtin_expect(!!(expr), 0)
# else
# define yyjson_unlikely(expr) (expr)
# endif
#endif
/** compile-time constant check for compiler */
#ifndef yyjson_constant_p
# if yyjson_has_builtin(__builtin_constant_p) || (YYJSON_GCC_VER >= 3)
# define YYJSON_HAS_CONSTANT_P 1
# define yyjson_constant_p(value) __builtin_constant_p(value)
# else
# define YYJSON_HAS_CONSTANT_P 0
# define yyjson_constant_p(value) 0
# endif
#endif
/** deprecate warning */
#ifndef yyjson_deprecated
# if YYJSON_MSC_VER >= 1400
# define yyjson_deprecated(msg) __declspec(deprecated(msg))
# elif yyjson_has_feature(attribute_deprecated_with_message) || \
(YYJSON_GCC_VER > 4 || (YYJSON_GCC_VER == 4 && __GNUC_MINOR__ >= 5))
# define yyjson_deprecated(msg) __attribute__((deprecated(msg)))
# elif YYJSON_GCC_VER >= 3
# define yyjson_deprecated(msg) __attribute__((deprecated))
# else
# define yyjson_deprecated(msg)
# endif
#endif
/** function export */
#ifndef yyjson_api
# if defined(_WIN32)
# if defined(YYJSON_EXPORTS) && YYJSON_EXPORTS
# define yyjson_api __declspec(dllexport)
# elif defined(YYJSON_IMPORTS) && YYJSON_IMPORTS
# define yyjson_api __declspec(dllimport)
# else
# define yyjson_api
# endif
# elif yyjson_has_attribute(visibility) || YYJSON_GCC_VER >= 4
# define yyjson_api __attribute__((visibility("default")))
# else
# define yyjson_api
# endif
#endif
/** inline function export */
#ifndef yyjson_api_inline
# define yyjson_api_inline static yyjson_inline
#endif
/** stdint (C89 compatible) */
#if (defined(YYJSON_HAS_STDINT_H) && YYJSON_HAS_STDINT_H) || \
YYJSON_MSC_VER >= 1600 || YYJSON_STDC_VER >= 199901L || \
defined(_STDINT_H) || defined(_STDINT_H_) || \
defined(__CLANG_STDINT_H) || defined(_STDINT_H_INCLUDED) || \
yyjson_has_include(<stdint.h>)
# include <stdint.h>
#elif defined(_MSC_VER)
# if _MSC_VER < 1300
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
# else
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
# endif
#else
# if UCHAR_MAX == 0xFFU
typedef signed char int8_t;
typedef unsigned char uint8_t;
# else
# error cannot find 8-bit integer type
# endif
# if USHRT_MAX == 0xFFFFU
typedef unsigned short uint16_t;
typedef signed short int16_t;
# elif UINT_MAX == 0xFFFFU
typedef unsigned int uint16_t;
typedef signed int int16_t;
# else
# error cannot find 16-bit integer type
# endif
# if UINT_MAX == 0xFFFFFFFFUL
typedef unsigned int uint32_t;
typedef signed int int32_t;
# elif ULONG_MAX == 0xFFFFFFFFUL
typedef unsigned long uint32_t;
typedef signed long int32_t;
# elif USHRT_MAX == 0xFFFFFFFFUL
typedef unsigned short uint32_t;
typedef signed short int32_t;
# else
# error cannot find 32-bit integer type
# endif
# if defined(__INT64_TYPE__) && defined(__UINT64_TYPE__)
typedef __INT64_TYPE__ int64_t;
typedef __UINT64_TYPE__ uint64_t;
# elif defined(__GNUC__) || defined(__clang__)
# if !defined(_SYS_TYPES_H) && !defined(__int8_t_defined)
__extension__ typedef long long int64_t;
# endif
__extension__ typedef unsigned long long uint64_t;
# elif defined(_LONG_LONG) || defined(__MWERKS__) || defined(_CRAYC) || \
defined(__SUNPRO_C) || defined(__SUNPRO_CC)
typedef long long int64_t;
typedef unsigned long long uint64_t;
# elif (defined(__BORLANDC__) && __BORLANDC__ > 0x460) || \
defined(__WATCOM_INT64__) || defined (__alpha) || defined (__DECC)
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
# else
# error cannot find 64-bit integer type
# endif
#endif
/** stdbool (C89 compatible) */
#if (defined(YYJSON_HAS_STDBOOL_H) && YYJSON_HAS_STDBOOL_H) || \
(yyjson_has_include(<stdbool.h>) && !defined(__STRICT_ANSI__)) || \
YYJSON_MSC_VER >= 1800 || YYJSON_STDC_VER >= 199901L
# include <stdbool.h>
#elif !defined(__bool_true_false_are_defined)
# define __bool_true_false_are_defined 1
# if defined(__cplusplus)
# if defined(__GNUC__) && !defined(__STRICT_ANSI__)
# define _Bool bool
# if __cplusplus < 201103L
# define bool bool
# define false false
# define true true
# endif
# endif
# else
# define bool unsigned char
# define true 1
# define false 0
# endif
#endif
/** char bit check */
#if defined(CHAR_BIT)
# if CHAR_BIT != 8
# error non 8-bit char is not supported
# endif
#endif
/**
Microsoft Visual C++ 6.0 doesn't support converting number from u64 to f64:
error C2520: conversion from unsigned __int64 to double not implemented.
*/
#ifndef YYJSON_U64_TO_F64_NO_IMPL
# if (0 < YYJSON_MSC_VER) && (YYJSON_MSC_VER <= 1200)
# define YYJSON_U64_TO_F64_NO_IMPL 1
# else
# define YYJSON_U64_TO_F64_NO_IMPL 0
# endif
#endif
/*==============================================================================
* Compile Hint Begin
*============================================================================*/
/* extern "C" begin */
#ifdef __cplusplus
extern "C" {
#endif
/* warning suppress begin */
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunused-function"
# pragma clang diagnostic ignored "-Wunused-parameter"
#elif defined(__GNUC__)
# if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
# pragma GCC diagnostic push
# endif
# pragma GCC diagnostic ignored "-Wunused-function"
# pragma GCC diagnostic ignored "-Wunused-parameter"
#elif defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable:4800) /* 'int': forcing value to 'true' or 'false' */
#endif
/*==============================================================================
* Version
*============================================================================*/
/** The major version of yyjson. */
#define YYJSON_VERSION_MAJOR 0
/** The minor version of yyjson. */
#define YYJSON_VERSION_MINOR 10
/** The patch version of yyjson. */
#define YYJSON_VERSION_PATCH 0
/** The version of yyjson in hex: `(major << 16) | (minor << 8) | (patch)`. */
#define YYJSON_VERSION_HEX 0x000A00
/** The version string of yyjson. */
#define YYJSON_VERSION_STRING "0.10.0"
/** The version of yyjson in hex, same as `YYJSON_VERSION_HEX`. */
yyjson_api uint32_t yyjson_version(void);
/*==============================================================================
* JSON Types
*============================================================================*/
/** Type of a JSON value (3 bit). */
typedef uint8_t yyjson_type;
/** No type, invalid. */
#define YYJSON_TYPE_NONE ((uint8_t)0) /* _____000 */
/** Raw string type, no subtype. */
#define YYJSON_TYPE_RAW ((uint8_t)1) /* _____001 */
/** Null type: `null` literal, no subtype. */
#define YYJSON_TYPE_NULL ((uint8_t)2) /* _____010 */
/** Boolean type, subtype: TRUE, FALSE. */
#define YYJSON_TYPE_BOOL ((uint8_t)3) /* _____011 */
/** Number type, subtype: UINT, SINT, REAL. */
#define YYJSON_TYPE_NUM ((uint8_t)4) /* _____100 */
/** String type, subtype: NONE, NOESC. */
#define YYJSON_TYPE_STR ((uint8_t)5) /* _____101 */
/** Array type, no subtype. */
#define YYJSON_TYPE_ARR ((uint8_t)6) /* _____110 */
/** Object type, no subtype. */
#define YYJSON_TYPE_OBJ ((uint8_t)7) /* _____111 */
/** Subtype of a JSON value (2 bit). */
typedef uint8_t yyjson_subtype;
/** No subtype. */
#define YYJSON_SUBTYPE_NONE ((uint8_t)(0 << 3)) /* ___00___ */
/** False subtype: `false` literal. */
#define YYJSON_SUBTYPE_FALSE ((uint8_t)(0 << 3)) /* ___00___ */
/** True subtype: `true` literal. */
#define YYJSON_SUBTYPE_TRUE ((uint8_t)(1 << 3)) /* ___01___ */
/** Unsigned integer subtype: `uint64_t`. */
#define YYJSON_SUBTYPE_UINT ((uint8_t)(0 << 3)) /* ___00___ */
/** Signed integer subtype: `int64_t`. */
#define YYJSON_SUBTYPE_SINT ((uint8_t)(1 << 3)) /* ___01___ */
/** Real number subtype: `double`. */
#define YYJSON_SUBTYPE_REAL ((uint8_t)(2 << 3)) /* ___10___ */
/** String that do not need to be escaped for writing (internal use). */
#define YYJSON_SUBTYPE_NOESC ((uint8_t)(1 << 3)) /* ___01___ */
/** The mask used to extract the type of a JSON value. */
#define YYJSON_TYPE_MASK ((uint8_t)0x07) /* _____111 */
/** The number of bits used by the type. */
#define YYJSON_TYPE_BIT ((uint8_t)3)
/** The mask used to extract the subtype of a JSON value. */
#define YYJSON_SUBTYPE_MASK ((uint8_t)0x18) /* ___11___ */
/** The number of bits used by the subtype. */
#define YYJSON_SUBTYPE_BIT ((uint8_t)2)
/** The mask used to extract the reserved bits of a JSON value. */
#define YYJSON_RESERVED_MASK ((uint8_t)0xE0) /* 111_____ */
/** The number of reserved bits. */
#define YYJSON_RESERVED_BIT ((uint8_t)3)
/** The mask used to extract the tag of a JSON value. */
#define YYJSON_TAG_MASK ((uint8_t)0xFF) /* 11111111 */
/** The number of bits used by the tag. */
#define YYJSON_TAG_BIT ((uint8_t)8)
/** Padding size for JSON reader. */
#define YYJSON_PADDING_SIZE 4
/*==============================================================================
* Allocator
*============================================================================*/
/**
A memory allocator.
Typically you don't need to use it, unless you want to customize your own
memory allocator.
*/
typedef struct yyjson_alc {
/** Same as libc's malloc(size), should not be NULL. */
void *(*malloc)(void *ctx, size_t size);
/** Same as libc's realloc(ptr, size), should not be NULL. */
void *(*realloc)(void *ctx, void *ptr, size_t old_size, size_t size);
/** Same as libc's free(ptr), should not be NULL. */
void (*free)(void *ctx, void *ptr);
/** A context for malloc/realloc/free, can be NULL. */
void *ctx;
} yyjson_alc;
/**
A pool allocator uses fixed length pre-allocated memory.
This allocator may be used to avoid malloc/realloc calls. The pre-allocated
memory should be held by the caller. The maximum amount of memory required to
read a JSON can be calculated using the `yyjson_read_max_memory_usage()`
function, but the amount of memory required to write a JSON cannot be directly
calculated.
This is not a general-purpose allocator. It is designed to handle a single JSON
data at a time. If it is used for overly complex memory tasks, such as parsing
multiple JSON documents using the same allocator but releasing only a few of
them, it may cause memory fragmentation, resulting in performance degradation
and memory waste.
@param alc The allocator to be initialized.
If this parameter is NULL, the function will fail and return false.
If `buf` or `size` is invalid, this will be set to an empty allocator.
@param buf The buffer memory for this allocator.
If this parameter is NULL, the function will fail and return false.
@param size The size of `buf`, in bytes.
If this parameter is less than 8 words (32/64 bytes on 32/64-bit OS), the
function will fail and return false.
@return true if the `alc` has been successfully initialized.
@par Example
@code
// parse JSON with stack memory
char buf[1024];
yyjson_alc alc;
yyjson_alc_pool_init(&alc, buf, 1024);
const char *json = "{\"name\":\"Helvetica\",\"size\":16}"
yyjson_doc *doc = yyjson_read_opts(json, strlen(json), 0, &alc, NULL);
// the memory of `doc` is on the stack
@endcode
@warning This Allocator is not thread-safe.
*/
yyjson_api bool yyjson_alc_pool_init(yyjson_alc *alc, void *buf, size_t size);
/**
A dynamic allocator.
This allocator has a similar usage to the pool allocator above. However, when
there is not enough memory, this allocator will dynamically request more memory
using libc's `malloc` function, and frees it all at once when it is destroyed.
@return A new dynamic allocator, or NULL if memory allocation failed.
@note The returned value should be freed with `yyjson_alc_dyn_free()`.
@warning This Allocator is not thread-safe.
*/
yyjson_api yyjson_alc *yyjson_alc_dyn_new(void);
/**
Free a dynamic allocator which is created by `yyjson_alc_dyn_new()`.
@param alc The dynamic allocator to be destroyed.
*/
yyjson_api void yyjson_alc_dyn_free(yyjson_alc *alc);
/*==============================================================================
* Text Locating
*============================================================================*/
/**
Locate the line and column number for a byte position in a string.
This can be used to get better description for error position.
@param str The input string.
@param len The byte length of the input string.
@param pos The byte position within the input string.
@param line A pointer to receive the line number, starting from 1.
@param col A pointer to receive the column number, starting from 1.
@param chr A pointer to receive the character index, starting from 0.
@return true on success, false if `str` is NULL or `pos` is out of bounds.
@note Line/column/character are calculated based on Unicode characters for
compatibility with text editors. For multi-byte UTF-8 characters,
the returned value may not directly correspond to the byte position.
*/
yyjson_api bool yyjson_locate_pos(const char *str, size_t len, size_t pos,
size_t *line, size_t *col, size_t *chr);
/*==============================================================================
* JSON Structure
*============================================================================*/
/**
An immutable document for reading JSON.
This document holds memory for all its JSON values and strings. When it is no
longer used, the user should call `yyjson_doc_free()` to free its memory.
*/
typedef struct yyjson_doc yyjson_doc;
/**
An immutable value for reading JSON.
A JSON Value has the same lifetime as its document. The memory is held by its
document and and cannot be freed alone.
*/
typedef struct yyjson_val yyjson_val;
/**
A mutable document for building JSON.
This document holds memory for all its JSON values and strings. When it is no
longer used, the user should call `yyjson_mut_doc_free()` to free its memory.
*/
typedef struct yyjson_mut_doc yyjson_mut_doc;
/**
A mutable value for building JSON.
A JSON Value has the same lifetime as its document. The memory is held by its
document and and cannot be freed alone.
*/
typedef struct yyjson_mut_val yyjson_mut_val;
/*==============================================================================
* JSON Reader API
*============================================================================*/
/** Run-time options for JSON reader. */
typedef uint32_t yyjson_read_flag;
/** Default option (RFC 8259 compliant):
- Read positive integer as uint64_t.
- Read negative integer as int64_t.
- Read floating-point number as double with round-to-nearest mode.
- Read integer which cannot fit in uint64_t or int64_t as double.
- Report error if double number is infinity.
- Report error if string contains invalid UTF-8 character or BOM.
- Report error on trailing commas, comments, inf and nan literals. */
static const yyjson_read_flag YYJSON_READ_NOFLAG = 0;
/** Read the input data in-situ.
This option allows the reader to modify and use input data to store string
values, which can increase reading speed slightly.
The caller should hold the input data before free the document.
The input data must be padded by at least `YYJSON_PADDING_SIZE` bytes.
For example: `[1,2]` should be `[1,2]\0\0\0\0`, input length should be 5. */
static const yyjson_read_flag YYJSON_READ_INSITU = 1 << 0;
/** Stop when done instead of issuing an error if there's additional content
after a JSON document. This option may be used to parse small pieces of JSON
in larger data, such as `NDJSON`. */
static const yyjson_read_flag YYJSON_READ_STOP_WHEN_DONE = 1 << 1;
/** Allow single trailing comma at the end of an object or array,
such as `[1,2,3,]`, `{"a":1,"b":2,}` (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_TRAILING_COMMAS = 1 << 2;
/** Allow C-style single line and multiple line comments (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_COMMENTS = 1 << 3;
/** Allow inf/nan number and literal, case-insensitive,
such as 1e999, NaN, inf, -Infinity (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_INF_AND_NAN = 1 << 4;
/** Read all numbers as raw strings (value with `YYJSON_TYPE_RAW` type),
inf/nan literal is also read as raw with `ALLOW_INF_AND_NAN` flag. */
static const yyjson_read_flag YYJSON_READ_NUMBER_AS_RAW = 1 << 5;
/** Allow reading invalid unicode when parsing string values (non-standard).
Invalid characters will be allowed to appear in the string values, but
invalid escape sequences will still be reported as errors.
This flag does not affect the performance of correctly encoded strings.
@warning Strings in JSON values may contain incorrect encoding when this
option is used, you need to handle these strings carefully to avoid security
risks. */
static const yyjson_read_flag YYJSON_READ_ALLOW_INVALID_UNICODE = 1 << 6;
/** Read big numbers as raw strings. These big numbers include integers that
cannot be represented by `int64_t` and `uint64_t`, and floating-point
numbers that cannot be represented by finite `double`.
The flag will be overridden by `YYJSON_READ_NUMBER_AS_RAW` flag. */
static const yyjson_read_flag YYJSON_READ_BIGNUM_AS_RAW = 1 << 7;
/** Result code for JSON reader. */
typedef uint32_t yyjson_read_code;
/** Success, no error. */
static const yyjson_read_code YYJSON_READ_SUCCESS = 0;
/** Invalid parameter, such as NULL input string or 0 input length. */
static const yyjson_read_code YYJSON_READ_ERROR_INVALID_PARAMETER = 1;
/** Memory allocation failure occurs. */
static const yyjson_read_code YYJSON_READ_ERROR_MEMORY_ALLOCATION = 2;
/** Input JSON string is empty. */
static const yyjson_read_code YYJSON_READ_ERROR_EMPTY_CONTENT = 3;
/** Unexpected content after document, such as `[123]abc`. */
static const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_CONTENT = 4;
/** Unexpected ending, such as `[123`. */
static const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_END = 5;
/** Unexpected character inside the document, such as `[abc]`. */
static const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_CHARACTER = 6;
/** Invalid JSON structure, such as `[1,]`. */
static const yyjson_read_code YYJSON_READ_ERROR_JSON_STRUCTURE = 7;
/** Invalid comment, such as unclosed multi-line comment. */
static const yyjson_read_code YYJSON_READ_ERROR_INVALID_COMMENT = 8;
/** Invalid number, such as `123.e12`, `000`. */
static const yyjson_read_code YYJSON_READ_ERROR_INVALID_NUMBER = 9;
/** Invalid string, such as invalid escaped character inside a string. */
static const yyjson_read_code YYJSON_READ_ERROR_INVALID_STRING = 10;
/** Invalid JSON literal, such as `truu`. */
static const yyjson_read_code YYJSON_READ_ERROR_LITERAL = 11;
/** Failed to open a file. */
static const yyjson_read_code YYJSON_READ_ERROR_FILE_OPEN = 12;
/** Failed to read a file. */
static const yyjson_read_code YYJSON_READ_ERROR_FILE_READ = 13;
/** Error information for JSON reader. */
typedef struct yyjson_read_err {
/** Error code, see `yyjson_read_code` for all possible values. */
yyjson_read_code code;
/** Error message, constant, no need to free (NULL if success). */
const char *msg;
/** Error byte position for input data (0 if success). */
size_t pos;
} yyjson_read_err;
#if !defined(YYJSON_DISABLE_READER) || !YYJSON_DISABLE_READER
/**
Read JSON with options.
This function is thread-safe when:
1. The `dat` is not modified by other threads.
2. The `alc` is thread-safe or NULL.
@param dat The JSON data (UTF-8 without BOM), null-terminator is not required.
If this parameter is NULL, the function will fail and return NULL.
The `dat` will not be modified without the flag `YYJSON_READ_INSITU`, so you
can pass a `const char *` string and case it to `char *` if you don't use
the `YYJSON_READ_INSITU` flag.
@param len The length of JSON data in bytes.
If this parameter is 0, the function will fail and return NULL.
@param flg The JSON read options.
Multiple options can be combined with `|` operator. 0 means no options.
@param alc The memory allocator used by JSON reader.
Pass NULL to use the libc's default allocator.
@param err A pointer to receive error information.
Pass NULL if you don't need error information.
@return A new JSON document, or NULL if an error occurs.
When it's no longer needed, it should be freed with `yyjson_doc_free()`.
*/
yyjson_api yyjson_doc *yyjson_read_opts(char *dat,
size_t len,
yyjson_read_flag flg,
const yyjson_alc *alc,
yyjson_read_err *err);
/**
Read a JSON file.
This function is thread-safe when:
1. The file is not modified by other threads.
2. The `alc` is thread-safe or NULL.
@param path The JSON file's path.
If this path is NULL or invalid, the function will fail and return NULL.
@param flg The JSON read options.
Multiple options can be combined with `|` operator. 0 means no options.
@param alc The memory allocator used by JSON reader.
Pass NULL to use the libc's default allocator.
@param err A pointer to receive error information.
Pass NULL if you don't need error information.
@return A new JSON document, or NULL if an error occurs.
When it's no longer needed, it should be freed with `yyjson_doc_free()`.
@warning On 32-bit operating system, files larger than 2GB may fail to read.
*/
yyjson_api yyjson_doc *yyjson_read_file(const char *path,
yyjson_read_flag flg,
const yyjson_alc *alc,
yyjson_read_err *err);
/**
Read JSON from a file pointer.
@param fp The file pointer.
The data will be read from the current position of the FILE to the end.
If this fp is NULL or invalid, the function will fail and return NULL.
@param flg The JSON read options.
Multiple options can be combined with `|` operator. 0 means no options.
@param alc The memory allocator used by JSON reader.
Pass NULL to use the libc's default allocator.
@param err A pointer to receive error information.
Pass NULL if you don't need error information.
@return A new JSON document, or NULL if an error occurs.
When it's no longer needed, it should be freed with `yyjson_doc_free()`.
@warning On 32-bit operating system, files larger than 2GB may fail to read.
*/
yyjson_api yyjson_doc *yyjson_read_fp(FILE *fp,
yyjson_read_flag flg,
const yyjson_alc *alc,
yyjson_read_err *err);
/**
Read a JSON string.
This function is thread-safe.
@param dat The JSON data (UTF-8 without BOM), null-terminator is not required.
If this parameter is NULL, the function will fail and return NULL.
@param len The length of JSON data in bytes.
If this parameter is 0, the function will fail and return NULL.
@param flg The JSON read options.
Multiple options can be combined with `|` operator. 0 means no options.
@return A new JSON document, or NULL if an error occurs.
When it's no longer needed, it should be freed with `yyjson_doc_free()`.
*/
yyjson_api_inline yyjson_doc *yyjson_read(const char *dat,
size_t len,
yyjson_read_flag flg) {
flg &= ~YYJSON_READ_INSITU; /* const string cannot be modified */
return yyjson_read_opts((char *)(void *)(size_t)(const void *)dat,
len, flg, NULL, NULL);
}
/**
Returns the size of maximum memory usage to read a JSON data.
You may use this value to avoid malloc() or calloc() call inside the reader
to get better performance, or read multiple JSON with one piece of memory.
@param len The length of JSON data in bytes.
@param flg The JSON read options.
@return The maximum memory size to read this JSON, or 0 if overflow.
@par Example
@code
// read multiple JSON with same pre-allocated memory
char *dat1, *dat2, *dat3; // JSON data
size_t len1, len2, len3; // JSON length
size_t max_len = MAX(len1, MAX(len2, len3));
yyjson_doc *doc;
// use one allocator for multiple JSON
size_t size = yyjson_read_max_memory_usage(max_len, 0);
void *buf = malloc(size);
yyjson_alc alc;
yyjson_alc_pool_init(&alc, buf, size);
// no more alloc() or realloc() call during reading
doc = yyjson_read_opts(dat1, len1, 0, &alc, NULL);
yyjson_doc_free(doc);
doc = yyjson_read_opts(dat2, len2, 0, &alc, NULL);
yyjson_doc_free(doc);
doc = yyjson_read_opts(dat3, len3, 0, &alc, NULL);