forked from ijl/orjson
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyyjson.h
More file actions
5553 lines (4618 loc) · 205 KB
/
Copy pathyyjson.h
File metadata and controls
5553 lines (4618 loc) · 205 KB
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
/*==============================================================================
* Created by Yaoyuan on 2019/3/9.
* Copyright (C) 2019 Yaoyuan <ibireme@gmail.com>.
*
* Released under the MIT License:
* https://github.com/ibireme/yyjson/blob/master/LICENSE
*============================================================================*/
/** @file yyjson.h */
#ifndef YYJSON_H
#define YYJSON_H
/*==============================================================================
* Header Files
*============================================================================*/
#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 you don't need to parse JSON.
This will disable these functions at compile-time:
- yyjson_read_opts()
- yyjson_read_file()
- yyjson_read()
This will reduce the binary size by about 60%.
*/
#ifndef YYJSON_DISABLE_READER
#endif
/*
Define as 1 to disable JSON writer if you don't need to serialize JSON.
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 the fast floating-point number conversion in yyjson,
and use libc's `strtod/snprintf` instead.
This will reduce binary size by about 30%, but significantly slow down
floating-point reading and writing 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 binary size by about 10%, and increase performance slightly.
*/
#ifndef YYJSON_DISABLE_NON_STANDARD
#endif
/*
Define as 1 to disable unaligned memory access if target architecture does not
support unaligned memory access (such as some embedded processors).
If this value is not defined, yyjson will perform some automatic detection.
The wrong definition of this option may cause some performance degradation,
but will not cause run-time errors.
*/
#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__
#else
# define YYJSON_GCC_VER 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
/** 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
# 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
# define yyjson_unlikely(expr) __builtin_expect(!!(expr), 0)
# else
# define yyjson_unlikely(expr) (expr)
# 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
/*==============================================================================
* 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 5
/** The patch version of yyjson. */
#define YYJSON_VERSION_PATCH 1
/** The version of yyjson in hex: (major << 16) | (minor << 8) | (patch). */
#define YYJSON_VERSION_HEX 0x000501
/** The version string of yyjson. */
#define YYJSON_VERSION_STRING "0.5.1"
/** The version of yyjson in hex, same as `YYJSON_VERSION_HEX`. */
yyjson_api uint32_t yyjson_version(void);
/*==============================================================================
* JSON Types
*============================================================================*/
/** Type of JSON value (3 bit). */
typedef uint8_t yyjson_type;
#define YYJSON_TYPE_NONE ((uint8_t)0) /* _____000 */
#define YYJSON_TYPE_RAW ((uint8_t)1) /* _____001 */
#define YYJSON_TYPE_NULL ((uint8_t)2) /* _____010 */
#define YYJSON_TYPE_BOOL ((uint8_t)3) /* _____011 */
#define YYJSON_TYPE_NUM ((uint8_t)4) /* _____100 */
#define YYJSON_TYPE_STR ((uint8_t)5) /* _____101 */
#define YYJSON_TYPE_ARR ((uint8_t)6) /* _____110 */
#define YYJSON_TYPE_OBJ ((uint8_t)7) /* _____111 */
/** Subtype of JSON value (2 bit). */
typedef uint8_t yyjson_subtype;
#define YYJSON_SUBTYPE_NONE ((uint8_t)(0 << 3)) /* ___00___ */
#define YYJSON_SUBTYPE_FALSE ((uint8_t)(0 << 3)) /* ___00___ */
#define YYJSON_SUBTYPE_TRUE ((uint8_t)(1 << 3)) /* ___01___ */
#define YYJSON_SUBTYPE_UINT ((uint8_t)(0 << 3)) /* ___00___ */
#define YYJSON_SUBTYPE_SINT ((uint8_t)(1 << 3)) /* ___01___ */
#define YYJSON_SUBTYPE_REAL ((uint8_t)(2 << 3)) /* ___10___ */
/** Mask and bits of JSON value. */
#define YYJSON_TYPE_MASK ((uint8_t)0x07) /* _____111 */
#define YYJSON_TYPE_BIT ((uint8_t)3)
#define YYJSON_SUBTYPE_MASK ((uint8_t)0x18) /* ___11___ */
#define YYJSON_SUBTYPE_BIT ((uint8_t)2)
#define YYJSON_RESERVED_MASK ((uint8_t)0xE0) /* 111_____ */
#define YYJSON_RESERVED_BIT ((uint8_t)3)
#define YYJSON_TAG_MASK ((uint8_t)0xFF) /* 11111111 */
#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(), should not be NULL. */
void *(*malloc)(void *ctx, size_t size);
/** Same as libc's realloc(), should not be NULL. */
void *(*realloc)(void *ctx, void *ptr, size_t size);
/** Same as libc's free(), 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 used to avoid malloc()/memmove() calls. The pre-allocated
memory should be held by the caller. The upper limit of memory required to
read JSON can be calculated using the yyjson_read_max_memory_usage() function,
but the memory required to write JSON cannot be calculated directly.
This is not a general-purpose allocator, and should only be used to read or
write single JSON document.
@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 parameter is left unmodified.
@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
*/
yyjson_api bool yyjson_alc_pool_init(yyjson_alc *alc, void *buf, size_t size);
/*==============================================================================
* 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 real 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 << 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", 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 number as raw string (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;
/** 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 string or invalid file path. */
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 "[1]#". */
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 "[#]". */
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;
/**
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 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 *)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);
yyjson_doc_free(doc);
free(buf);
@endcode
@see yyjson_alc_pool_init()
*/
yyjson_api_inline size_t yyjson_read_max_memory_usage(size_t len,
yyjson_read_flag flg) {
/*
1. The max value count is (json_size / 2 + 1),
for example: "[1,2,3,4]" size is 9, value count is 5.
2. Some broken JSON may cost more memory during reading, but fail at end,
for example: "[[[[[[[[".
3. yyjson use 16 bytes per value, see struct yyjson_val.
4. yyjson use dynamic memory with a growth factor of 1.5.
The max memory size is (json_size / 2 * 16 * 1.5 + padding).
*/
size_t mul = (size_t)12 + !(flg & YYJSON_READ_INSITU);
size_t pad = 256;
size_t max = (size_t)(~(size_t)0);
if (flg & YYJSON_READ_STOP_WHEN_DONE) len = len < 256 ? 256 : len;
if (len >= (max - pad - mul) / mul) return 0;
return len * mul + pad;
}
/*==============================================================================
* JSON Writer API
*============================================================================*/
/** Run-time options for JSON writer. */
typedef uint32_t yyjson_write_flag;
/** Default option:
- Write JSON minify.
- Report error on inf or nan number.
- Report error on invalid UTF-8 string.
- Do not escape unicode or slash. */
static const yyjson_write_flag YYJSON_WRITE_NOFLAG = 0 << 0;
/** Write JSON pretty with 4 space indent. */
static const yyjson_write_flag YYJSON_WRITE_PRETTY = 1 << 0;
/** Escape unicode as `uXXXX`, make the output ASCII only. */
static const yyjson_write_flag YYJSON_WRITE_ESCAPE_UNICODE = 1 << 1;
/** Escape '/' as '\/'. */
static const yyjson_write_flag YYJSON_WRITE_ESCAPE_SLASHES = 1 << 2;
/** Write inf and nan number as 'Infinity' and 'NaN' literal (non-standard). */
static const yyjson_write_flag YYJSON_WRITE_ALLOW_INF_AND_NAN = 1 << 3;
/** Write inf and nan number as null literal.
This flag will override `YYJSON_WRITE_ALLOW_INF_AND_NAN` flag. */
static const yyjson_write_flag YYJSON_WRITE_INF_AND_NAN_AS_NULL = 1 << 4;
/** Allow invalid unicode when encoding string values (non-standard).
Invalid characters in string value will be copied byte by byte.
If `YYJSON_WRITE_ESCAPE_UNICODE` flag is also set, invalid character will be
escaped as `U+FFFD` (replacement character).
This flag does not affect the performance of correctly encoded strings. */
static const yyjson_read_flag YYJSON_WRITE_ALLOW_INVALID_UNICODE = 1 << 5;
/** Result code for JSON writer */
typedef uint32_t yyjson_write_code;
/** Success, no error. */
static const yyjson_write_code YYJSON_WRITE_SUCCESS = 0;
/** Invalid parameter, such as NULL document. */
static const yyjson_write_code YYJSON_WRITE_ERROR_INVALID_PARAMETER = 1;
/** Memory allocation failure occurs. */
static const yyjson_write_code YYJSON_WRITE_ERROR_MEMORY_ALLOCATION = 2;
/** Invalid value type in JSON document. */
static const yyjson_write_code YYJSON_WRITE_ERROR_INVALID_VALUE_TYPE = 3;
/** NaN or Infinity number occurs. */
static const yyjson_write_code YYJSON_WRITE_ERROR_NAN_OR_INF = 4;
/** Failed to open a file. */
static const yyjson_write_code YYJSON_WRITE_ERROR_FILE_OPEN = 5;
/** Failed to write a file. */
static const yyjson_write_code YYJSON_WRITE_ERROR_FILE_WRITE = 6;
/** Invalid unicode in string. */
static const yyjson_write_code YYJSON_WRITE_ERROR_INVALID_STRING = 7;
/** Error information for JSON writer. */
typedef struct yyjson_write_err {
/** Error code, see `yyjson_write_code` for all possible values. */
yyjson_write_code code;
/** Error message, constant, no need to free (NULL if success). */
const char *msg;
} yyjson_write_err;
/*==============================================================================
* JSON Document Writer API
*============================================================================*/
/**
Write a document to JSON string with options.
This function is thread-safe when:
The `alc` is thread-safe or NULL.
@param doc The JSON document.
If this doc is NULL or has no root, the function will fail and return false.
@param flg The JSON write options.
Multiple options can be combined with `|` operator. 0 means no options.
@param alc The memory allocator used by JSON writer.
Pass NULL to use the libc's default allocator.
@param len A pointer to receive output length in bytes.
Pass NULL if you don't need length information.
@param err A pointer to receive error information.
Pass NULL if you don't need error information.
@return A new JSON string, or NULL if an error occurs.
This string is encoded as UTF-8 with a null-terminator.
When it's no longer needed, it should be freed with free() or alc->free().
*/
yyjson_api char *yyjson_write_opts(const yyjson_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc,
size_t *len,
yyjson_write_err *err);
/**
Write a document to JSON file with options.
This function is thread-safe when:
1. The file is not accessed 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 false.
If this file is not empty, the content will be discarded.
@param doc The JSON document.
If this doc is NULL or has no root, the function will fail and return false.
@param flg The JSON write options.
Multiple options can be combined with `|` operator. 0 means no options.
@param alc The memory allocator used by JSON writer.
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 true if successful, false if an error occurs.
@warning On 32-bit operating system, files larger than 2GB may fail to write.
*/
yyjson_api bool yyjson_write_file(const char *path,
const yyjson_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc,
yyjson_write_err *err);
/**
Write a document to JSON string.
This function is thread-safe.
@param doc The JSON document.
If this doc is NULL or has no root, the function will fail and return false.
@param flg The JSON write options.
Multiple options can be combined with `|` operator. 0 means no options.
@param len A pointer to receive output length in bytes.
Pass NULL if you don't need length information.
@return A new JSON string, or NULL if an error occurs.
This string is encoded as UTF-8 with a null-terminator.
When it's no longer needed, it should be freed with free().
*/
yyjson_api_inline char *yyjson_write(const yyjson_doc *doc,
yyjson_write_flag flg,
size_t *len) {
return yyjson_write_opts(doc, flg, NULL, len, NULL);
}
/**
Write a document to JSON string with options.
This function is thread-safe when:
1. The `doc` is not modified by other threads.
2. The `alc` is thread-safe or NULL.
@param doc The mutable JSON document.
If this doc is NULL or has no root, the function will fail and return false.
@param flg The JSON write options.
Multiple options can be combined with `|` operator. 0 means no options.
@param alc The memory allocator used by JSON writer.
Pass NULL to use the libc's default allocator.
@param len A pointer to receive output length in bytes.
Pass NULL if you don't need length information.
@param err A pointer to receive error information.
Pass NULL if you don't need error information.
@return A new JSON string, or NULL if an error occurs.
This string is encoded as UTF-8 with a null-terminator.
When it's no longer needed, it should be freed with free() or alc->free().
*/
yyjson_api char *yyjson_mut_write_opts(const yyjson_mut_doc *doc,
yyjson_write_flag flg,
const yyjson_alc *alc,
size_t *len,
yyjson_write_err *err);
/**
Write a document to JSON file with options.
This function is thread-safe when:
1. The file is not accessed by other threads.
2. The `doc` is not modified by other threads.
3. 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 false.
If this file is not empty, the content will be discarded.
@param doc The mutable JSON document.
If this doc is NULL or has no root, the function will fail and return false.