scorpiox-bot-plugin-websearch
←yyjson.cc
11224 lines · 406 KBHEADBlameDownload
1/*==============================================================================
2 Copyright (c) 2020 YaoYuan <ibireme@gmail.com>
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 *============================================================================*/
22
23#include "yyjson.h"
24#include <math.h> /* for `HUGE_VAL/INFINIY/NAN` macros, no libm required */
25
26
27
28/*==============================================================================
29 * MARK: - Warning Suppress (Private)
30 *============================================================================*/
31
32#if defined(__clang__)
33# pragma clang diagnostic ignored "-Wunused-function"
34# pragma clang diagnostic ignored "-Wunused-parameter"
35# pragma clang diagnostic ignored "-Wunused-label"
36# pragma clang diagnostic ignored "-Wunused-macros"
37# pragma clang diagnostic ignored "-Wunused-variable"
38#elif YYJSON_IS_REAL_GCC
39# pragma GCC diagnostic ignored "-Wunused-function"
40# pragma GCC diagnostic ignored "-Wunused-parameter"
41# pragma GCC diagnostic ignored "-Wunused-label"
42# pragma GCC diagnostic ignored "-Wunused-macros"
43# pragma GCC diagnostic ignored "-Wunused-variable"
44#elif defined(_MSC_VER)
45# pragma warning(disable:4100) /* unreferenced formal parameter */
46# pragma warning(disable:4101) /* unreferenced variable */
47# pragma warning(disable:4102) /* unreferenced label */
48# pragma warning(disable:4127) /* conditional expression is constant */
49# pragma warning(disable:4702) /* unreachable code */
50# pragma warning(disable:4706) /* assignment within conditional expression */
51#endif
52
53
54
55/*==============================================================================
56 * MARK: - Version (Public)
57 *============================================================================*/
58
59uint32_t yyjson_version(void) {
60 return YYJSON_VERSION_HEX;
61}
62
63
64
65/*==============================================================================
66 * MARK: - Flags (Private)
67 *============================================================================*/
68
69/* msvc intrinsic */
70#if YYJSON_MSC_VER >= 1400
71# include <intrin.h>
72# if defined(_M_AMD64) || defined(_M_ARM64)
73# define MSC_HAS_BIT_SCAN_64 1
74# pragma intrinsic(_BitScanForward64)
75# pragma intrinsic(_BitScanReverse64)
76# else
77# define MSC_HAS_BIT_SCAN_64 0
78# endif
79# if defined(_M_AMD64) || defined(_M_ARM64) || \
80 defined(_M_IX86) || defined(_M_ARM)
81# define MSC_HAS_BIT_SCAN 1
82# pragma intrinsic(_BitScanForward)
83# pragma intrinsic(_BitScanReverse)
84# else
85# define MSC_HAS_BIT_SCAN 0
86# endif
87# if defined(_M_AMD64)
88# define MSC_HAS_UMUL128 1
89# pragma intrinsic(_umul128)
90# else
91# define MSC_HAS_UMUL128 0
92# endif
93#else
94# define MSC_HAS_BIT_SCAN_64 0
95# define MSC_HAS_BIT_SCAN 0
96# define MSC_HAS_UMUL128 0
97#endif
98
99/* gcc builtin */
100#if yyjson_has_builtin(__builtin_clzll) || yyjson_gcc_available(3, 4, 0)
101# define GCC_HAS_CLZLL 1
102#else
103# define GCC_HAS_CLZLL 0
104#endif
105
106#if yyjson_has_builtin(__builtin_ctzll) || yyjson_gcc_available(3, 4, 0)
107# define GCC_HAS_CTZLL 1
108#else
109# define GCC_HAS_CTZLL 0
110#endif
111
112/* int128 type */
113#if defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16) && \
114 (defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER))
115# define YYJSON_HAS_INT128 1
116#else
117# define YYJSON_HAS_INT128 0
118#endif
119
120/* IEEE 754 floating-point binary representation */
121#if defined(__STDC_IEC_559__) || defined(__STDC_IEC_60559_BFP__)
122# define YYJSON_HAS_IEEE_754 1
123#elif FLT_RADIX == 2 && \
124 FLT_MANT_DIG == 24 && FLT_DIG == 6 && \
125 FLT_MIN_EXP == -125 && FLT_MAX_EXP == 128 && \
126 FLT_MIN_10_EXP == -37 && FLT_MAX_10_EXP == 38 && \
127 DBL_MANT_DIG == 53 && DBL_DIG == 15 && \
128 DBL_MIN_EXP == -1021 && DBL_MAX_EXP == 1024 && \
129 DBL_MIN_10_EXP == -307 && DBL_MAX_10_EXP == 308
130# define YYJSON_HAS_IEEE_754 1
131#else
132# define YYJSON_HAS_IEEE_754 0
133# undef YYJSON_DISABLE_FAST_FP_CONV
134# define YYJSON_DISABLE_FAST_FP_CONV 1
135#endif
136
137/*
138 Correct rounding in double number computations.
139
140 On the x86 architecture, some compilers may use x87 FPU instructions for
141 floating-point arithmetic. The x87 FPU loads all floating point number as
142 80-bit double-extended precision internally, then rounds the result to original
143 precision, which may produce inaccurate results. For a more detailed
144 explanation, see the paper: https://arxiv.org/abs/cs/0701192
145
146 Here are some examples of double precision calculation error:
147
148 2877.0 / 1e6 == 0.002877, but x87 returns 0.0028770000000000002
149 43683.0 * 1e21 == 4.3683e25, but x87 returns 4.3683000000000004e25
150
151 Here are some examples of compiler flags to generate x87 instructions on x86:
152
153 clang -m32 -mno-sse
154 gcc/icc -m32 -mfpmath=387
155 msvc /arch:SSE or /arch:IA32
156
157 If we are sure that there's no similar error described above, we can define the
158 YYJSON_DOUBLE_MATH_CORRECT as 1 to enable the fast path calculation. This is
159 not an accurate detection, it's just try to avoid the error at compile-time.
160 An accurate detection can be done at run-time:
161
162 bool is_double_math_correct(void) {
163 volatile double r = 43683.0;
164 r *= 1e21;
165 return r == 4.3683e25;
166 }
167
168 See also: utils.h in https://github.com/google/double-conversion/
169 */
170#if !defined(FLT_EVAL_METHOD) && defined(__FLT_EVAL_METHOD__)
171# define FLT_EVAL_METHOD __FLT_EVAL_METHOD__
172#endif
173
174#if defined(FLT_EVAL_METHOD) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1
175# define YYJSON_DOUBLE_MATH_CORRECT 0
176#elif defined(i386) || defined(__i386) || defined(__i386__) || \
177 defined(_X86_) || defined(__X86__) || defined(_M_IX86) || \
178 defined(__I86__) || defined(__IA32__) || defined(__THW_INTEL)
179# if (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP == 2) || \
180 (defined(__SSE2_MATH__) && __SSE2_MATH__)
181# define YYJSON_DOUBLE_MATH_CORRECT 1
182# else
183# define YYJSON_DOUBLE_MATH_CORRECT 0
184# endif
185#elif defined(__mc68000__) || defined(__pnacl__) || defined(__native_client__)
186# define YYJSON_DOUBLE_MATH_CORRECT 0
187#else
188# define YYJSON_DOUBLE_MATH_CORRECT 1
189#endif
190
191/*
192 Detect the endianness at compile-time.
193 YYJSON_ENDIAN == YYJSON_BIG_ENDIAN
194 YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN
195 */
196#define YYJSON_BIG_ENDIAN 4321
197#define YYJSON_LITTLE_ENDIAN 1234
198
199#if yyjson_has_include(<sys/types.h>)
200# include <sys/types.h> /* POSIX */
201#endif
202#if yyjson_has_include(<endian.h>)
203# include <endian.h> /* Linux */
204#elif yyjson_has_include(<sys/endian.h>)
205# include <sys/endian.h> /* BSD, Android */
206#elif yyjson_has_include(<machine/endian.h>)
207# include <machine/endian.h> /* BSD, Darwin */
208#endif
209
210#if defined(BYTE_ORDER) && BYTE_ORDER
211# if defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN)
212# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
213# elif defined(LITTLE_ENDIAN) && (BYTE_ORDER == LITTLE_ENDIAN)
214# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
215# endif
216#elif defined(__BYTE_ORDER) && __BYTE_ORDER
217# if defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN)
218# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
219# elif defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN)
220# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
221# endif
222#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__
223# if defined(__ORDER_BIG_ENDIAN__) && \
224 (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
225# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
226# elif defined(__ORDER_LITTLE_ENDIAN__) && \
227 (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
228# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
229# endif
230#elif (defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__ == 1) || \
231 defined(__i386) || defined(__i386__) || \
232 defined(_X86_) || defined(__X86__) || \
233 defined(_M_IX86) || defined(__THW_INTEL__) || \
234 defined(__x86_64) || defined(__x86_64__) || \
235 defined(__amd64) || defined(__amd64__) || \
236 defined(_M_AMD64) || defined(_M_X64) || \
237 defined(_M_ARM) || defined(_M_ARM64) || \
238 defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \
239 defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) || \
240 defined(__EMSCRIPTEN__) || defined(__wasm__) || \
241 defined(__loongarch__)
242# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN
243#elif (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__ == 1) || \
244 defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \
245 defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) || \
246 defined(__or1k__) || defined(__OR1K__)
247# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN
248#else
249# define YYJSON_ENDIAN 0 /* unknown endian, detect at run-time */
250#endif
251
252/*
253 This macro controls how yyjson handles unaligned memory accesses.
254
255 By default, yyjson uses `memcpy()` for memory copying. This allows the compiler
256 to optimize the code and emit unaligned memory access instructions when
257 supported by the target architecture.
258
259 However, on some older compilers or architectures where `memcpy()` is not
260 well-optimized and may result in unnecessary function calls, defining this
261 macro as 1 may help. In such cases, yyjson switches to manual byte-by-byte
262 access, which can potentially improve performance.
263
264 An example of the generated assembly code for ARM can be found here:
265 https://godbolt.org/z/334jjhxPT
266
267 This flag is already enabled for common architectures in the following code,
268 so manual configuration is usually unnecessary. If unsure, you can check the
269 generated assembly or run benchmarks to make an informed decision.
270 */
271#ifndef YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
272# if defined(__ia64) || defined(_IA64) || defined(__IA64__) || \
273 defined(__ia64__) || defined(_M_IA64) || defined(__itanium__)
274# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* Itanium */
275# elif (defined(__arm__) || defined(__arm64__) || defined(__aarch64__)) && \
276 (defined(__GNUC__) || defined(__clang__)) && \
277 (!defined(__ARM_FEATURE_UNALIGNED) || !__ARM_FEATURE_UNALIGNED)
278# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* ARM */
279# elif defined(__sparc) || defined(__sparc__)
280# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* SPARC */
281# elif defined(__mips) || defined(__mips__) || defined(__MIPS__)
282# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* MIPS */
283# elif defined(__m68k__) || defined(M68000)
284# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* M68K */
285# else
286# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 0
287# endif
288#endif
289
290/*
291 Estimated initial ratio of the JSON data (data_size / value_count).
292 For example:
293
294 data: {"id":12345678,"name":"Harry"}
295 data_size: 30
296 value_count: 5
297 ratio: 6
298
299 yyjson uses dynamic memory with a growth factor of 1.5 when reading and writing
300 JSON, the ratios below are used to determine the initial memory size.
301
302 A too large ratio will waste memory, and a too small ratio will cause multiple
303 memory growths and degrade performance. Currently, these ratios are generated
304 with some commonly used JSON datasets.
305 */
306#define YYJSON_READER_ESTIMATED_PRETTY_RATIO 16
307#define YYJSON_READER_ESTIMATED_MINIFY_RATIO 6
308#define YYJSON_WRITER_ESTIMATED_PRETTY_RATIO 32
309#define YYJSON_WRITER_ESTIMATED_MINIFY_RATIO 18
310
311/* The initial and maximum size of the memory pool's chunk in yyjson_mut_doc. */
312#define YYJSON_MUT_DOC_STR_POOL_INIT_SIZE 0x100
313#define YYJSON_MUT_DOC_STR_POOL_MAX_SIZE 0x10000000
314#define YYJSON_MUT_DOC_VAL_POOL_INIT_SIZE (0x10 * sizeof(yyjson_mut_val))
315#define YYJSON_MUT_DOC_VAL_POOL_MAX_SIZE (0x1000000 * sizeof(yyjson_mut_val))
316
317/* The minimum size of the dynamic allocator's chunk. */
318#define YYJSON_ALC_DYN_MIN_SIZE 0x1000
319
320/* Default value for compile-time options. */
321#ifndef YYJSON_DISABLE_READER
322#define YYJSON_DISABLE_READER 0
323#endif
324#ifndef YYJSON_DISABLE_WRITER
325#define YYJSON_DISABLE_WRITER 0
326#endif
327#ifndef YYJSON_DISABLE_INCR_READER
328#define YYJSON_DISABLE_INCR_READER 0
329#endif
330#ifndef YYJSON_DISABLE_UTILS
331#define YYJSON_DISABLE_UTILS 0
332#endif
333#ifndef YYJSON_DISABLE_FAST_FP_CONV
334#define YYJSON_DISABLE_FAST_FP_CONV 0
335#endif
336#ifndef YYJSON_DISABLE_NON_STANDARD
337#define YYJSON_DISABLE_NON_STANDARD 0
338#endif
339#ifndef YYJSON_DISABLE_UTF8_VALIDATION
340#define YYJSON_DISABLE_UTF8_VALIDATION 0
341#endif
342#ifndef YYJSON_READER_DEPTH_LIMIT
343#define YYJSON_READER_DEPTH_LIMIT 0
344#endif
345
346/*==============================================================================
347 * MARK: - Macros (Private)
348 *============================================================================*/
349
350/* Macros used for loop unrolling and other purpose. */
351#define repeat2(x) { x x }
352#define repeat4(x) { x x x x }
353#define repeat8(x) { x x x x x x x x }
354#define repeat16(x) { x x x x x x x x x x x x x x x x }
355
356#define repeat2_incr(x) { x(0) x(1) }
357#define repeat4_incr(x) { x(0) x(1) x(2) x(3) }
358#define repeat8_incr(x) { x(0) x(1) x(2) x(3) x(4) x(5) x(6) x(7) }
359#define repeat16_incr(x) { x(0) x(1) x(2) x(3) x(4) x(5) x(6) x(7) \
360 x(8) x(9) x(10) x(11) x(12) x(13) x(14) x(15) }
361#define repeat_in_1_18(x) { x(1) x(2) x(3) x(4) x(5) x(6) x(7) x(8) \
362 x(9) x(10) x(11) x(12) x(13) x(14) x(15) x(16) \
363 x(17) x(18) }
364
365/* Macros used to provide branch prediction information for compiler. */
366#undef likely
367#define likely(x) yyjson_likely(x)
368#undef unlikely
369#define unlikely(x) yyjson_unlikely(x)
370
371/* Macros used to provide inline information for compiler. */
372#undef static_inline
373#define static_inline static yyjson_inline
374#undef static_noinline
375#define static_noinline static yyjson_noinline
376
377/* Macros for min and max. */
378#undef yyjson_min
379#define yyjson_min(x, y) ((x) < (y) ? (x) : (y))
380#undef yyjson_max
381#define yyjson_max(x, y) ((x) > (y) ? (x) : (y))
382
383/* Used to write u64 literal for C89 which doesn't support "ULL" suffix. */
384#undef U64
385#define U64(hi, lo) ((((u64)hi##UL) << 32U) + lo##UL)
386#undef U32
387#define U32(hi) ((u32)(hi##UL))
388
389/* Used to cast away (remove) const qualifier. */
390#define constcast(type) (type)(void *)(size_t)(const void *)
391
392/*
393 Compiler barriers for single variables.
394
395 These macros inform GCC that a read or write access to the given memory
396 location will occur, preventing certain compiler optimizations or reordering
397 around the access to 'val'. They do not emit any actual instructions.
398
399 This is useful when GCC's default optimization strategies are suboptimal and
400 precise control over memory access patterns is required.
401 These barriers are not needed when using Clang or MSVC.
402 */
403#if YYJSON_IS_REAL_GCC
404# define gcc_load_barrier(val) __asm__ volatile(""::"m"(val))
405# define gcc_store_barrier(val) __asm__ volatile("":"=m"(val))
406# define gcc_full_barrier(val) __asm__ volatile("":"=m"(val):"m"(val))
407#else
408# define gcc_load_barrier(val)
409# define gcc_store_barrier(val)
410# define gcc_full_barrier(val)
411#endif
412
413
414
415/*==============================================================================
416 * MARK: - Constants (Private)
417 *============================================================================*/
418
419/* Common error messages. */
420#define MSG_FOPEN "failed to open file"
421#define MSG_FREAD "failed to read file"
422#define MSG_FWRITE "failed to write file"
423#define MSG_FCLOSE "failed to close file"
424#define MSG_MALLOC "failed to allocate memory"
425#define MSG_CHAR_T "invalid literal, expected 'true'"
426#define MSG_CHAR_F "invalid literal, expected 'false'"
427#define MSG_CHAR_N "invalid literal, expected 'null'"
428#define MSG_CHAR "unexpected character, expected a JSON value"
429#define MSG_ARR_END "unexpected character, expected ',' or ']'"
430#define MSG_OBJ_KEY "unexpected character, expected a string key"
431#define MSG_OBJ_SEP "unexpected character, expected ':' after key"
432#define MSG_OBJ_END "unexpected character, expected ',' or '}'"
433#define MSG_GARBAGE "unexpected content after document"
434#define MSG_NOT_END "unexpected end of data"
435#define MSG_COMMENT "unclosed multiline comment"
436#define MSG_COMMA "trailing comma is not allowed"
437#define MSG_NAN_INF "nan or inf number is not allowed"
438#define MSG_ERR_TYPE "invalid JSON value type"
439#define MSG_ERR_BOM "UTF-8 byte order mark (BOM) is not supported"
440#define MSG_ERR_UTF8 "invalid utf-8 encoding in string"
441#define MSG_ERR_UTF16 "UTF-16 encoding is not supported"
442#define MSG_ERR_UTF32 "UTF-32 encoding is not supported"
443#define MSG_DEPTH "depth limit exceeded"
444
445/* U64 constant values */
446#undef U64_MAX
447#define U64_MAX U64(0xFFFFFFFF, 0xFFFFFFFF)
448#undef I64_MAX
449#define I64_MAX U64(0x7FFFFFFF, 0xFFFFFFFF)
450#undef USIZE_MAX
451#define USIZE_MAX ((usize)(~(usize)0))
452
453/* Maximum number of digits for reading u32/u64/usize safety (not overflow). */
454#undef U32_SAFE_DIG
455#define U32_SAFE_DIG 9 /* u32 max is 4294967295, 10 digits */
456#undef U64_SAFE_DIG
457#define U64_SAFE_DIG 19 /* u64 max is 18446744073709551615, 20 digits */
458#undef USIZE_SAFE_DIG
459#define USIZE_SAFE_DIG (sizeof(usize) == 8 ? U64_SAFE_DIG : U32_SAFE_DIG)
460
461/* Inf bits (positive) */
462#define F64_BITS_INF U64(0x7FF00000, 0x00000000)
463
464/* NaN bits (quiet NaN, no payload, no sign) */
465#if defined(__hppa__) || (defined(__mips__) && !defined(__mips_nan2008))
466#define F64_BITS_NAN U64(0x7FF7FFFF, 0xFFFFFFFF)
467#else
468#define F64_BITS_NAN U64(0x7FF80000, 0x00000000)
469#endif
470
471/* maximum significant digits count in decimal when reading double number */
472#define F64_MAX_DEC_DIG 768
473
474/* maximum decimal power of double number (1.7976931348623157e308) */
475#define F64_MAX_DEC_EXP 308
476
477/* minimum decimal power of double number (4.9406564584124654e-324) */
478#define F64_MIN_DEC_EXP (-324)
479
480/* maximum binary power of double number */
481#define F64_MAX_BIN_EXP 1024
482
483/* minimum binary power of double number */
484#define F64_MIN_BIN_EXP (-1021)
485
486/* float/double number bits */
487#define F32_BITS 32
488#define F64_BITS 64
489
490/* float/double number exponent part bits */
491#define F32_EXP_BITS 8
492#define F64_EXP_BITS 11
493
494/* float/double number significand part bits */
495#define F32_SIG_BITS 23
496#define F64_SIG_BITS 52
497
498/* float/double number significand part bits (with 1 hidden bit) */
499#define F32_SIG_FULL_BITS 24
500#define F64_SIG_FULL_BITS 53
501
502/* float/double number significand bit mask */
503#define F32_SIG_MASK U32(0x007FFFFF)
504#define F64_SIG_MASK U64(0x000FFFFF, 0xFFFFFFFF)
505
506/* float/double number exponent bit mask */
507#define F32_EXP_MASK U32(0x7F800000)
508#define F64_EXP_MASK U64(0x7FF00000, 0x00000000)
509
510/* float/double number exponent bias */
511#define F32_EXP_BIAS 127
512#define F64_EXP_BIAS 1023
513
514/* float/double number significant digits count in decimal */
515#define F32_DEC_DIG 9
516#define F64_DEC_DIG 17
517
518/* buffer length required for float/double number writer */
519#define FP_BUF_LEN 40
520
521/* maximum length of a number in incremental parsing */
522#define INCR_NUM_MAX_LEN 1024
523
524
525
526/*==============================================================================
527 * MARK: - Types (Private)
528 *============================================================================*/
529
530/** Type define for primitive types. */
531typedef float f32;
532typedef double f64;
533typedef int8_t i8;
534typedef uint8_t u8;
535typedef int16_t i16;
536typedef uint16_t u16;
537typedef int32_t i32;
538typedef uint32_t u32;
539typedef int64_t i64;
540typedef uint64_t u64;
541typedef size_t usize;
542
543/** 128-bit integer, used by floating-point number reader and writer. */
544#if YYJSON_HAS_INT128
545__extension__ typedef __int128 i128;
546__extension__ typedef unsigned __int128 u128;
547#endif
548
549/** 16/32/64-bit vector */
550typedef struct v16 { char c[2]; } v16;
551typedef struct v32 { char c[4]; } v32;
552typedef struct v64 { char c[8]; } v64;
553
554/** 16/32/64-bit vector union */
555typedef union v16_uni { v16 v; u16 u; } v16_uni;
556typedef union v32_uni { v32 v; u32 u; } v32_uni;
557typedef union v64_uni { v64 v; u64 u; } v64_uni;
558
559
560
561/*==============================================================================
562 * MARK: - Load/Store Utils (Private)
563 *============================================================================*/
564
565#define byte_move_idx(x) ((char *)dst)[x] = ((const char *)src)[x];
566#define byte_move_src(x) ((char *)tmp)[x] = ((const char *)src)[x];
567#define byte_move_dst(x) ((char *)dst)[x] = ((const char *)tmp)[x];
568
569/** Same as `memcpy(dst, src, 2)`, no overlap. */
570static_inline void byte_copy_2(void *dst, const void *src) {
571#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
572 memcpy(dst, src, 2);
573#else
574 repeat2_incr(byte_move_idx)
575#endif
576}
577
578/** Same as `memcpy(dst, src, 4)`, no overlap. */
579static_inline void byte_copy_4(void *dst, const void *src) {
580#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
581 memcpy(dst, src, 4);
582#else
583 repeat4_incr(byte_move_idx)
584#endif
585}
586
587/** Same as `memcpy(dst, src, 8)`, no overlap. */
588static_inline void byte_copy_8(void *dst, const void *src) {
589#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
590 memcpy(dst, src, 8);
591#else
592 repeat8_incr(byte_move_idx)
593#endif
594}
595
596/** Same as `memcpy(dst, src, 16)`, no overlap. */
597static_inline void byte_copy_16(void *dst, const void *src) {
598#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
599 memcpy(dst, src, 16);
600#else
601 repeat16_incr(byte_move_idx)
602#endif
603}
604
605/** Same as `memmove(dst, src, 2)`, allows overlap. */
606static_inline void byte_move_2(void *dst, const void *src) {
607#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
608 u16 tmp;
609 memcpy(&tmp, src, 2);
610 memcpy(dst, &tmp, 2);
611#else
612 char tmp[2];
613 repeat2_incr(byte_move_src)
614 repeat2_incr(byte_move_dst)
615#endif
616}
617
618/** Same as `memmove(dst, src, 4)`, allows overlap. */
619static_inline void byte_move_4(void *dst, const void *src) {
620#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
621 u32 tmp;
622 memcpy(&tmp, src, 4);
623 memcpy(dst, &tmp, 4);
624#else
625 char tmp[4];
626 repeat4_incr(byte_move_src)
627 repeat4_incr(byte_move_dst)
628#endif
629}
630
631/** Same as `memmove(dst, src, 8)`, allows overlap. */
632static_inline void byte_move_8(void *dst, const void *src) {
633#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
634 u64 tmp;
635 memcpy(&tmp, src, 8);
636 memcpy(dst, &tmp, 8);
637#else
638 char tmp[8];
639 repeat8_incr(byte_move_src)
640 repeat8_incr(byte_move_dst)
641#endif
642}
643
644/** Same as `memmove(dst, src, 16)`, allows overlap. */
645static_inline void byte_move_16(void *dst, const void *src) {
646#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
647 char *pdst = (char *)dst;
648 const char *psrc = (const char *)src;
649 u64 tmp1, tmp2;
650 memcpy(&tmp1, psrc, 8);
651 memcpy(&tmp2, psrc + 8, 8);
652 memcpy(pdst, &tmp1, 8);
653 memcpy(pdst + 8, &tmp2, 8);
654#else
655 char tmp[16];
656 repeat16_incr(byte_move_src)
657 repeat16_incr(byte_move_dst)
658#endif
659}
660
661/** Same as `memmove(dst, src, n)`, but only `dst <= src` and `n <= 16`. */
662static_inline void byte_move_forward(void *dst, void *src, usize n) {
663 char *d = (char *)dst, *s = (char *)src;
664 n += (n % 2); /* round up to even */
665 if (n == 16) { byte_move_16(d, s); return; }
666 if (n >= 8) { byte_move_8(d, s); n -= 8; d += 8; s += 8; }
667 if (n >= 4) { byte_move_4(d, s); n -= 4; d += 4; s += 4; }
668 if (n >= 2) { byte_move_2(d, s); }
669}
670
671/** Same as `memcmp(buf, pat, 2) == 0`. */
672static_inline bool byte_match_2(void *buf, const char *pat) {
673#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
674 v16_uni u1, u2;
675 memcpy(&u1, buf, 2);
676 memcpy(&u2, pat, 2);
677 return u1.u == u2.u;
678#else
679 return ((char *)buf)[0] == ((const char *)pat)[0] &&
680 ((char *)buf)[1] == ((const char *)pat)[1];
681#endif
682}
683
684/** Same as `memcmp(buf, pat, 4) == 0`. */
685static_inline bool byte_match_4(void *buf, const char *pat) {
686#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
687 v32_uni u1, u2;
688 memcpy(&u1, buf, 4);
689 memcpy(&u2, pat, 4);
690 return u1.u == u2.u;
691#else
692 return ((char *)buf)[0] == ((const char *)pat)[0] &&
693 ((char *)buf)[1] == ((const char *)pat)[1] &&
694 ((char *)buf)[2] == ((const char *)pat)[2] &&
695 ((char *)buf)[3] == ((const char *)pat)[3];
696#endif
697}
698
699/** Loads 2 bytes from `src` as a u16 (native-endian). */
700static_inline u16 byte_load_2(const void *src) {
701 v16_uni uni;
702#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
703 memcpy(&uni, src, 2);
704#else
705 uni.v.c[0] = ((const char *)src)[0];
706 uni.v.c[1] = ((const char *)src)[1];
707#endif
708 return uni.u;
709}
710
711/** Loads 3 bytes from `src` as a u32 (native-endian). */
712static_inline u32 byte_load_3(const void *src) {
713 v32_uni uni;
714#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
715 memcpy(&uni, src, 2);
716 uni.v.c[2] = ((const char *)src)[2];
717 uni.v.c[3] = 0;
718#else
719 uni.v.c[0] = ((const char *)src)[0];
720 uni.v.c[1] = ((const char *)src)[1];
721 uni.v.c[2] = ((const char *)src)[2];
722 uni.v.c[3] = 0;
723#endif
724 return uni.u;
725}
726
727/** Loads 4 bytes from `src` as a u32 (native-endian). */
728static_inline u32 byte_load_4(const void *src) {
729 v32_uni uni;
730#if !YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS
731 memcpy(&uni, src, 4);
732#else
733 uni.v.c[0] = ((const char *)src)[0];
734 uni.v.c[1] = ((const char *)src)[1];
735 uni.v.c[2] = ((const char *)src)[2];
736 uni.v.c[3] = ((const char *)src)[3];
737#endif
738 return uni.u;
739}
740
741
742
743/*==============================================================================
744 * MARK: - Character Utils (Private)
745 * These lookup tables were generated by `misc/make_tables.c`.
746 *============================================================================*/
747
748/* char_table1 */
749#define CHAR_TYPE_ASCII (1 << 0) /* Except: ["\], [0x00-0x1F, 0x80-0xFF] */
750#define CHAR_TYPE_ASCII_SQ (1 << 1) /* Except: ['\], [0x00-0x1F, 0x80-0xFF] */
751#define CHAR_TYPE_SPACE (1 << 2) /* Whitespace: [ \t\n\r] */
752#define CHAR_TYPE_SPACE_EXT (1 << 3) /* Whitespace: [ \t\n\r\v\f], JSON5 */
753#define CHAR_TYPE_NUM (1 << 4) /* Number: [.-+0-9] */
754#define CHAR_TYPE_COMMENT (1 << 5) /* Comment: [/] */
755
756/* char_table2 */
757#define CHAR_TYPE_EOL (1 << 0) /* End of line: [\r\n] */
758#define CHAR_TYPE_EOL_EXT (1 << 1) /* End of line: [\r\n], JSON5 */
759#define CHAR_TYPE_ID_START (1 << 2) /* ID start: [_$A-Za-z\], U+0080+ */
760#define CHAR_TYPE_ID_NEXT (1 << 3) /* ID next: [_$A-Za-z0-9\], U+0080+ */
761#define CHAR_TYPE_ID_ASCII (1 << 4) /* ID next ASCII: [_$A-Za-z0-9] */
762
763/* char_table3 */
764#define CHAR_TYPE_SIGN (1 << 0) /* [-+] */
765#define CHAR_TYPE_DIGIT (1 << 1) /* [0-9] */
766#define CHAR_TYPE_NONZERO (1 << 2) /* [1-9] */
767#define CHAR_TYPE_EXP (1 << 3) /* [eE] */
768#define CHAR_TYPE_DOT (1 << 4) /* [.] */
769
770static const u8 char_table1[256] = {
771 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
772 0x00, 0x0C, 0x0C, 0x08, 0x08, 0x0C, 0x00, 0x00,
773 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
774 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
775 0x0F, 0x03, 0x02, 0x03, 0x03, 0x03, 0x03, 0x01,
776 0x03, 0x03, 0x03, 0x13, 0x03, 0x13, 0x13, 0x23,
777 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13,
778 0x13, 0x13, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
779 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
780 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
781 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
782 0x03, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03,
783 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
784 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
785 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
786 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03,
787 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
788 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
789 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
790 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
791 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
792 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
793 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
794 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
795 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
796 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
797 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
798 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
799 0x00, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00,
800 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
801 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
802 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
803};
804
805static const u8 char_table2[256] = {
806 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
807 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00,
808 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
809 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
810 0x00, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00,
811 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
812 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
813 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
814 0x00, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C,
815 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C,
816 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C,
817 0x1C, 0x1C, 0x1C, 0x00, 0x0C, 0x00, 0x00, 0x1C,
818 0x00, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C,
819 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C,
820 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C,
821 0x1C, 0x1C, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00,
822 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
823 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
824 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
825 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
826 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
827 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
828 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
829 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
830 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
831 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
832 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
833 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
834 0x0C, 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
835 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
836 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C,
837 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C
838};
839
840static const u8 char_table3[256] = {
841 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
842 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
843 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
844 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
845 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
846 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x10, 0x00,
847 0x02, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
848 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
849 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
850 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
851 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
852 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
853 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00,
854 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
855 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
856 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
857 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
858 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
859 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
860 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
861 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
862 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
863 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
864 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
865 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
866 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
867 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
868 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
869 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
870 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
871 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
872 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
873};
874
875/** Match a whitespace: [ \t\n\r]. */
876static_inline bool char_is_space(u8 c) {
877 return !!(char_table1[c] & CHAR_TYPE_SPACE);
878}
879
880/** Match an extended whitespace: [ \t\n\r\\v\\f], JSON5 whitespace. */
881static_inline bool char_is_space_ext(u8 c) {
882 return !!(char_table1[c] & CHAR_TYPE_SPACE_EXT);
883}
884
885/** Match a JSON number: [.-+0-9]. */
886static_inline bool char_is_num(u8 c) {
887 return !!(char_table1[c] & CHAR_TYPE_NUM);
888}
889
890/** Match an ASCII character in string: ["\], [0x00-0x1F, 0x80-0xFF]. */
891static_inline bool char_is_ascii_skip(u8 c) {
892 return !!(char_table1[c] & CHAR_TYPE_ASCII);
893}
894
895/** Match an ASCII character single-quoted: ['\], [0x00-0x1F, 0x80-0xFF]. */
896static_inline bool char_is_ascii_skip_sq(u8 c) {
897 return !!(char_table1[c] & CHAR_TYPE_ASCII_SQ);
898}
899
900/** Match a trivia character: extended whitespace or comment. */
901static_inline bool char_is_trivia(u8 c) {
902 return !!(char_table1[c] & (CHAR_TYPE_SPACE_EXT | CHAR_TYPE_COMMENT));
903}
904
905/** Match a line end character: [\r\n]. */
906static_inline bool char_is_eol(u8 c) {
907 return !!(char_table2[c] & CHAR_TYPE_EOL);
908}
909
910/** Match an extended line end character: [\r\n], JSON5 line terminator. */
911static_inline bool char_is_eol_ext(u8 c) {
912 return !!(char_table2[c] & CHAR_TYPE_EOL_EXT);
913}
914
915/** Match an identifier name start: [_$A-Za-z\], U+0080+. */
916static_inline bool char_is_id_start(u8 c) {
917 return !!(char_table2[c] & CHAR_TYPE_ID_START);
918}
919
920/** Match an identifier name next: [_$A-Za-z0-9\], U+0080+. */
921static_inline bool char_is_id_next(u8 c) {
922 return !!(char_table2[c] & CHAR_TYPE_ID_NEXT);
923}
924
925/** Match an identifier name ASCII: [_$A-Za-z0-9]. */
926static_inline bool char_is_id_ascii(u8 c) {
927 return !!(char_table2[c] & CHAR_TYPE_ID_ASCII);
928}
929
930/** Match a sign: [+-] */
931static_inline bool char_is_sign(u8 d) {
932 return !!(char_table3[d] & CHAR_TYPE_SIGN);
933}
934
935/** Match a none-zero digit: [1-9] */
936static_inline bool char_is_nonzero(u8 d) {
937 return !!(char_table3[d] & CHAR_TYPE_NONZERO);
938}
939
940/** Match a digit: [0-9] */
941static_inline bool char_is_digit(u8 d) {
942 return !!(char_table3[d] & CHAR_TYPE_DIGIT);
943}
944
945/** Match an exponent sign: [eE]. */
946static_inline bool char_is_exp(u8 d) {
947 return !!(char_table3[d] & CHAR_TYPE_EXP);
948}
949
950/** Match a floating point indicator: [.eE]. */
951static_inline bool char_is_fp(u8 d) {
952 return !!(char_table3[d] & (CHAR_TYPE_DOT | CHAR_TYPE_EXP));
953}
954
955/** Match a digit or floating point indicator: [0-9.eE]. */
956static_inline bool char_is_digit_or_fp(u8 d) {
957 return !!(char_table3[d] & (CHAR_TYPE_DIGIT | CHAR_TYPE_DOT |
958 CHAR_TYPE_EXP));
959}
960
961/** Match a JSON container: `{` or `[`. */
962static_inline bool char_is_ctn(u8 c) {
963 return (c & 0xDF) == 0x5B; /* '[': 0x5B, '{': 0x7B */
964}
965
966/** Convert ASCII letter to lowercase; valid only for [A-Za-z]. */
967static_inline u8 char_to_lower(u8 c) {
968 return c | 0x20;
969}
970
971/** Match UTF-8 byte order mask. */
972static_inline bool is_utf8_bom(const u8 *cur) {
973 return byte_load_3(cur) == byte_load_3("\xEF\xBB\xBF");
974}
975
976/** Match UTF-16 byte order mask. */
977static_inline bool is_utf16_bom(const u8 *cur) {
978 return byte_load_2(cur) == byte_load_2("\xFE\xFF") ||
979 byte_load_2(cur) == byte_load_2("\xFF\xFE");
980}
981
982/** Match UTF-32 byte order mask, need length check to avoid zero padding. */
983static_inline bool is_utf32_bom(const u8 *cur) {
984 return byte_load_4(cur) == byte_load_4("\x00\x00\xFE\xFF") ||
985 byte_load_4(cur) == byte_load_4("\xFF\xFE\x00\x00");
986}
987
988/** Get the extended line end length. Used with `char_is_eol_ext`. */
989static_inline usize ext_eol_len(const u8 *cur) {
990 if (cur[0] < 0x80) return 1;
991 if (cur[1] == 0x80 && (cur[2] == 0xA8 || cur[2] == 0xA9)) return 3;
992 return 0;
993}
994
995/** Get the extended whitespace length. Used with `char_is_space_ext`. */
996static_inline usize ext_space_len(const u8 *cur) {
997 if (cur[0] < 0x80) {
998 return 1;
999 } else if (byte_load_2(cur) == byte_load_2("\xC2\xA0")) {
1000 return 2;
1001 } else if (byte_load_2(cur) == byte_load_2("\xE2\x80")) {
1002 if (cur[2] >= 0x80 && cur[2] <= 0x8A) return 3;
1003 if (cur[2] == 0xA8 || cur[2] == 0xA9 || cur[2] == 0xAF) return 3;
1004 } else {
1005 u32 uni = byte_load_3(cur);
1006 if (uni == byte_load_3("\xE1\x9A\x80") ||
1007 uni == byte_load_3("\xE2\x81\x9F") ||
1008 uni == byte_load_3("\xE3\x80\x80") ||
1009 uni == byte_load_3("\xEF\xBB\xBF")) return 3;
1010 }
1011 return 0;
1012}
1013
1014
1015
1016/*==============================================================================
1017 * MARK: - Hex Character Reader (Private)
1018 * This function is used by JSON reader to read escaped characters.
1019 *============================================================================*/
1020
1021/**
1022 This table is used to convert 4 hex character sequence to a number.
1023 A valid hex character [0-9A-Fa-f] will mapped to it's raw number [0x00, 0x0F],
1024 an invalid hex character will mapped to [0xF0].
1025 (generate with misc/make_tables.c)
1026 */
1027static const u8 hex_conv_table[256] = {
1028 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1029 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1030 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1031 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1032 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1033 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1034 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
1035 0x08, 0x09, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1036 0xF0, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xF0,
1037 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1038 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1039 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1040 0xF0, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xF0,
1041 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1042 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1043 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1044 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1045 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1046 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1047 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1048 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1049 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1050 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1051 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1052 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1053 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1054 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1055 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1056 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1057 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1058 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
1059 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
1060};
1061
1062/** Load 4 hex characters to `u16`, return true on valid input. */
1063static_inline bool hex_load_4(const u8 *src, u16 *dst) {
1064 u16 c0 = hex_conv_table[src[0]];
1065 u16 c1 = hex_conv_table[src[1]];
1066 u16 c2 = hex_conv_table[src[2]];
1067 u16 c3 = hex_conv_table[src[3]];
1068 u16 t0 = (u16)((c0 << 8) | c2);
1069 u16 t1 = (u16)((c1 << 8) | c3);
1070 *dst = (u16)((t0 << 4) | t1);
1071 return ((t0 | t1) & (u16)0xF0F0) == 0;
1072}
1073
1074/** Load 2 hex characters to `u8`, return true on valid input. */
1075static_inline bool hex_load_2(const u8 *src, u8 *dst) {
1076 u8 c0 = hex_conv_table[src[0]];
1077 u8 c1 = hex_conv_table[src[1]];
1078 *dst = (u8)((c0 << 4) | c1);
1079 return ((c0 | c1) & 0xF0) == 0;
1080}
1081
1082/** Match a hexadecimal numeric character: [0-9a-fA-F]. */
1083static_inline bool char_is_hex(u8 c) {
1084 return hex_conv_table[c] != 0xF0;
1085}
1086
1087
1088
1089/*==============================================================================
1090 * MARK: - UTF8 Validation (Private)
1091 * Each Unicode code point is encoded using 1 to 4 bytes in UTF-8.
1092 * Validation is performed using a 4-byte mask and pattern-based approach,
1093 * which requires the input data to be padded with four zero bytes at the end.
1094 *============================================================================*/
1095
1096/* Macro for concatenating four u8 into a u32 and keeping the byte order. */
1097#if YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN
1098# define utf8_seq_def(name, a, b, c, d) \
1099 static const u32 utf8_seq_##name = 0x##d##c##b##a##UL;
1100# define utf8_seq(name) utf8_seq_##name
1101#elif YYJSON_ENDIAN == YYJSON_BIG_ENDIAN
1102# define utf8_seq_def(name, a, b, c, d) \
1103 static const u32 utf8_seq_##name = 0x##a##b##c##d##UL;
1104# define utf8_seq(name) utf8_seq_##name
1105#else
1106# define utf8_seq_def(name, a, b, c, d) \
1107 static const v32_uni utf8_uni_##name = {{ 0x##a, 0x##b, 0x##c, 0x##d }};
1108# define utf8_seq(name) utf8_uni_##name.u
1109#endif
1110
1111/*
1112 1-byte sequence (U+0000 to U+007F)
1113 bit min [.......0] (U+0000)
1114 bit max [.1111111] (U+007F)
1115 bit mask [x.......] (80)
1116 bit pattern [0.......] (00)
1117 */
1118utf8_seq_def(b1_mask, 80, 00, 00, 00)
1119utf8_seq_def(b1_patt, 00, 00, 00, 00)
1120#define is_utf8_seq1(uni) ( \
1121 ((uni & utf8_seq(b1_mask)) == utf8_seq(b1_patt)) )
1122
1123/*
1124 2-byte sequence (U+0080 to U+07FF)
1125 bit min [......10 ..000000] (U+0080)
1126 bit max [...11111 ..111111] (U+07FF)
1127 bit mask [xxx..... xx......] (E0 C0)
1128 bit pattern [110..... 10......] (C0 80)
1129 bit require [...xxxx. ........] (1E 00)
1130 */
1131utf8_seq_def(b2_mask, E0, C0, 00, 00)
1132utf8_seq_def(b2_patt, C0, 80, 00, 00)
1133utf8_seq_def(b2_requ, 1E, 00, 00, 00)
1134#define is_utf8_seq2(uni) ( \
1135 ((uni & utf8_seq(b2_mask)) == utf8_seq(b2_patt)) && \
1136 ((uni & utf8_seq(b2_requ))) )
1137
1138/*
1139 3-byte sequence (U+0800 to U+FFFF)
1140 bit min [........ ..100000 ..000000] (U+0800)
1141 bit max [....1111 ..111111 ..111111] (U+FFFF)
1142 bit mask [xxxx.... xx...... xx......] (F0 C0 C0)
1143 bit pattern [1110.... 10...... 10......] (E0 80 80)
1144 bit require [....xxxx ..x..... ........] (0F 20 00)
1145
1146 3-byte invalid sequence, reserved for surrogate halves (U+D800 to U+DFFF)
1147 bit min [....1101 ..100000 ..000000] (U+D800)
1148 bit max [....1101 ..111111 ..111111] (U+DFFF)
1149 bit mask [....xxxx ..x..... ........] (0F 20 00)
1150 bit pattern [....1101 ..1..... ........] (0D 20 00)
1151 */
1152utf8_seq_def(b3_mask, F0, C0, C0, 00)
1153utf8_seq_def(b3_patt, E0, 80, 80, 00)
1154utf8_seq_def(b3_requ, 0F, 20, 00, 00)
1155utf8_seq_def(b3_erro, 0D, 20, 00, 00)
1156#define is_utf8_seq3(uni) ( \
1157 ((uni & utf8_seq(b3_mask)) == utf8_seq(b3_patt)) && \
1158 ((tmp = (uni & utf8_seq(b3_requ)))) && \
1159 ((tmp != utf8_seq(b3_erro))) )
1160
1161/*
1162 4-byte sequence (U+10000 to U+10FFFF)
1163 bit min [........ ...10000 ..000000 ..000000] (U+10000)
1164 bit max [.....100 ..001111 ..111111 ..111111] (U+10FFFF)
1165 bit mask [xxxxx... xx...... xx...... xx......] (F8 C0 C0 C0)
1166 bit pattern [11110... 10...... 10...... 10......] (F0 80 80 80)
1167 bit require [.....xxx ..xx.... ........ ........] (07 30 00 00)
1168 bit require 1 [.....x.. ........ ........ ........] (04 00 00 00)
1169 bit require 2 [......xx ..xx.... ........ ........] (03 30 00 00)
1170 */
1171utf8_seq_def(b4_mask, F8, C0, C0, C0)
1172utf8_seq_def(b4_patt, F0, 80, 80, 80)
1173utf8_seq_def(b4_requ, 07, 30, 00, 00)
1174utf8_seq_def(b4_req1, 04, 00, 00, 00)
1175utf8_seq_def(b4_req2, 03, 30, 00, 00)
1176#define is_utf8_seq4(uni) ( \
1177 ((uni & utf8_seq(b4_mask)) == utf8_seq(b4_patt)) && \
1178 ((tmp = (uni & utf8_seq(b4_requ)))) && \
1179 ((tmp & utf8_seq(b4_req1)) == 0 || (tmp & utf8_seq(b4_req2)) == 0) )
1180
1181
1182
1183/*==============================================================================
1184 * MARK: - Power10 Lookup Table (Private)
1185 * These data are used by the floating-point number reader and writer.
1186 *============================================================================*/
1187
1188#if !YYJSON_DISABLE_FAST_FP_CONV
1189
1190/** Maximum pow10 exponent that can be represented exactly as a float64. */
1191#define F64_POW10_MAX_EXACT_EXP 22
1192
1193#if YYJSON_DOUBLE_MATH_CORRECT
1194/** Cached pow10 table. */
1195static const f64 f64_pow10_table[F64_POW10_MAX_EXACT_EXP + 1] = {
1196 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12,
1197 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22
1198};
1199#endif
1200
1201/** Maximum pow10 exponent that can be represented exactly as a uint64. */
1202#define U64_POW10_MAX_EXACT_EXP 19
1203
1204/** Table: [ 10^0, ..., 10^19 ] (generate with misc/make_tables.c) */
1205static const u64 u64_pow10_table[U64_POW10_MAX_EXACT_EXP + 1] = {
1206 U64(0x00000000, 0x00000001), U64(0x00000000, 0x0000000A),
1207 U64(0x00000000, 0x00000064), U64(0x00000000, 0x000003E8),
1208 U64(0x00000000, 0x00002710), U64(0x00000000, 0x000186A0),
1209 U64(0x00000000, 0x000F4240), U64(0x00000000, 0x00989680),
1210 U64(0x00000000, 0x05F5E100), U64(0x00000000, 0x3B9ACA00),
1211 U64(0x00000002, 0x540BE400), U64(0x00000017, 0x4876E800),
1212 U64(0x000000E8, 0xD4A51000), U64(0x00000918, 0x4E72A000),
1213 U64(0x00005AF3, 0x107A4000), U64(0x00038D7E, 0xA4C68000),
1214 U64(0x002386F2, 0x6FC10000), U64(0x01634578, 0x5D8A0000),
1215 U64(0x0DE0B6B3, 0xA7640000), U64(0x8AC72304, 0x89E80000)
1216};
1217
1218/** Minimum decimal exponent in pow10_sig_table. */
1219#define POW10_SIG_TABLE_MIN_EXP -343
1220
1221/** Maximum decimal exponent in pow10_sig_table. */
1222#define POW10_SIG_TABLE_MAX_EXP 324
1223
1224/** Minimum exact decimal exponent in pow10_sig_table */
1225#define POW10_SIG_TABLE_MIN_EXACT_EXP 0
1226
1227/** Maximum exact decimal exponent in pow10_sig_table */
1228#define POW10_SIG_TABLE_MAX_EXACT_EXP 55
1229
1230/** Normalized significant 128 bits of pow10, no rounded up (size: 10.4KB).
1231 This lookup table is used by both the double number reader and writer.
1232 (generate with misc/make_tables.c) */
1233static const u64 pow10_sig_table[] = {
1234 U64(0xBF29DCAB, 0xA82FDEAE), U64(0x7432EE87, 0x3880FC33), /* ~= 10^-343 */
1235 U64(0xEEF453D6, 0x923BD65A), U64(0x113FAA29, 0x06A13B3F), /* ~= 10^-342 */
1236 U64(0x9558B466, 0x1B6565F8), U64(0x4AC7CA59, 0xA424C507), /* ~= 10^-341 */
1237 U64(0xBAAEE17F, 0xA23EBF76), U64(0x5D79BCF0, 0x0D2DF649), /* ~= 10^-340 */
1238 U64(0xE95A99DF, 0x8ACE6F53), U64(0xF4D82C2C, 0x107973DC), /* ~= 10^-339 */
1239 U64(0x91D8A02B, 0xB6C10594), U64(0x79071B9B, 0x8A4BE869), /* ~= 10^-338 */
1240 U64(0xB64EC836, 0xA47146F9), U64(0x9748E282, 0x6CDEE284), /* ~= 10^-337 */
1241 U64(0xE3E27A44, 0x4D8D98B7), U64(0xFD1B1B23, 0x08169B25), /* ~= 10^-336 */
1242 U64(0x8E6D8C6A, 0xB0787F72), U64(0xFE30F0F5, 0xE50E20F7), /* ~= 10^-335 */
1243 U64(0xB208EF85, 0x5C969F4F), U64(0xBDBD2D33, 0x5E51A935), /* ~= 10^-334 */
1244 U64(0xDE8B2B66, 0xB3BC4723), U64(0xAD2C7880, 0x35E61382), /* ~= 10^-333 */
1245 U64(0x8B16FB20, 0x3055AC76), U64(0x4C3BCB50, 0x21AFCC31), /* ~= 10^-332 */
1246 U64(0xADDCB9E8, 0x3C6B1793), U64(0xDF4ABE24, 0x2A1BBF3D), /* ~= 10^-331 */
1247 U64(0xD953E862, 0x4B85DD78), U64(0xD71D6DAD, 0x34A2AF0D), /* ~= 10^-330 */
1248 U64(0x87D4713D, 0x6F33AA6B), U64(0x8672648C, 0x40E5AD68), /* ~= 10^-329 */
1249 U64(0xA9C98D8C, 0xCB009506), U64(0x680EFDAF, 0x511F18C2), /* ~= 10^-328 */
1250 U64(0xD43BF0EF, 0xFDC0BA48), U64(0x0212BD1B, 0x2566DEF2), /* ~= 10^-327 */
1251 U64(0x84A57695, 0xFE98746D), U64(0x014BB630, 0xF7604B57), /* ~= 10^-326 */
1252 U64(0xA5CED43B, 0x7E3E9188), U64(0x419EA3BD, 0x35385E2D), /* ~= 10^-325 */
1253 U64(0xCF42894A, 0x5DCE35EA), U64(0x52064CAC, 0x828675B9), /* ~= 10^-324 */
1254 U64(0x818995CE, 0x7AA0E1B2), U64(0x7343EFEB, 0xD1940993), /* ~= 10^-323 */
1255 U64(0xA1EBFB42, 0x19491A1F), U64(0x1014EBE6, 0xC5F90BF8), /* ~= 10^-322 */
1256 U64(0xCA66FA12, 0x9F9B60A6), U64(0xD41A26E0, 0x77774EF6), /* ~= 10^-321 */
1257 U64(0xFD00B897, 0x478238D0), U64(0x8920B098, 0x955522B4), /* ~= 10^-320 */
1258 U64(0x9E20735E, 0x8CB16382), U64(0x55B46E5F, 0x5D5535B0), /* ~= 10^-319 */
1259 U64(0xC5A89036, 0x2FDDBC62), U64(0xEB2189F7, 0x34AA831D), /* ~= 10^-318 */
1260 U64(0xF712B443, 0xBBD52B7B), U64(0xA5E9EC75, 0x01D523E4), /* ~= 10^-317 */
1261 U64(0x9A6BB0AA, 0x55653B2D), U64(0x47B233C9, 0x2125366E), /* ~= 10^-316 */
1262 U64(0xC1069CD4, 0xEABE89F8), U64(0x999EC0BB, 0x696E840A), /* ~= 10^-315 */
1263 U64(0xF148440A, 0x256E2C76), U64(0xC00670EA, 0x43CA250D), /* ~= 10^-314 */
1264 U64(0x96CD2A86, 0x5764DBCA), U64(0x38040692, 0x6A5E5728), /* ~= 10^-313 */
1265 U64(0xBC807527, 0xED3E12BC), U64(0xC6050837, 0x04F5ECF2), /* ~= 10^-312 */
1266 U64(0xEBA09271, 0xE88D976B), U64(0xF7864A44, 0xC633682E), /* ~= 10^-311 */
1267 U64(0x93445B87, 0x31587EA3), U64(0x7AB3EE6A, 0xFBE0211D), /* ~= 10^-310 */
1268 U64(0xB8157268, 0xFDAE9E4C), U64(0x5960EA05, 0xBAD82964), /* ~= 10^-309 */
1269 U64(0xE61ACF03, 0x3D1A45DF), U64(0x6FB92487, 0x298E33BD), /* ~= 10^-308 */
1270 U64(0x8FD0C162, 0x06306BAB), U64(0xA5D3B6D4, 0x79F8E056), /* ~= 10^-307 */
1271 U64(0xB3C4F1BA, 0x87BC8696), U64(0x8F48A489, 0x9877186C), /* ~= 10^-306 */
1272 U64(0xE0B62E29, 0x29ABA83C), U64(0x331ACDAB, 0xFE94DE87), /* ~= 10^-305 */
1273 U64(0x8C71DCD9, 0xBA0B4925), U64(0x9FF0C08B, 0x7F1D0B14), /* ~= 10^-304 */
1274 U64(0xAF8E5410, 0x288E1B6F), U64(0x07ECF0AE, 0x5EE44DD9), /* ~= 10^-303 */
1275 U64(0xDB71E914, 0x32B1A24A), U64(0xC9E82CD9, 0xF69D6150), /* ~= 10^-302 */
1276 U64(0x892731AC, 0x9FAF056E), U64(0xBE311C08, 0x3A225CD2), /* ~= 10^-301 */
1277 U64(0xAB70FE17, 0xC79AC6CA), U64(0x6DBD630A, 0x48AAF406), /* ~= 10^-300 */
1278 U64(0xD64D3D9D, 0xB981787D), U64(0x092CBBCC, 0xDAD5B108), /* ~= 10^-299 */
1279 U64(0x85F04682, 0x93F0EB4E), U64(0x25BBF560, 0x08C58EA5), /* ~= 10^-298 */
1280 U64(0xA76C5823, 0x38ED2621), U64(0xAF2AF2B8, 0x0AF6F24E), /* ~= 10^-297 */
1281 U64(0xD1476E2C, 0x07286FAA), U64(0x1AF5AF66, 0x0DB4AEE1), /* ~= 10^-296 */
1282 U64(0x82CCA4DB, 0x847945CA), U64(0x50D98D9F, 0xC890ED4D), /* ~= 10^-295 */
1283 U64(0xA37FCE12, 0x6597973C), U64(0xE50FF107, 0xBAB528A0), /* ~= 10^-294 */
1284 U64(0xCC5FC196, 0xFEFD7D0C), U64(0x1E53ED49, 0xA96272C8), /* ~= 10^-293 */
1285 U64(0xFF77B1FC, 0xBEBCDC4F), U64(0x25E8E89C, 0x13BB0F7A), /* ~= 10^-292 */
1286 U64(0x9FAACF3D, 0xF73609B1), U64(0x77B19161, 0x8C54E9AC), /* ~= 10^-291 */
1287 U64(0xC795830D, 0x75038C1D), U64(0xD59DF5B9, 0xEF6A2417), /* ~= 10^-290 */
1288 U64(0xF97AE3D0, 0xD2446F25), U64(0x4B057328, 0x6B44AD1D), /* ~= 10^-289 */
1289 U64(0x9BECCE62, 0x836AC577), U64(0x4EE367F9, 0x430AEC32), /* ~= 10^-288 */
1290 U64(0xC2E801FB, 0x244576D5), U64(0x229C41F7, 0x93CDA73F), /* ~= 10^-287 */
1291 U64(0xF3A20279, 0xED56D48A), U64(0x6B435275, 0x78C1110F), /* ~= 10^-286 */
1292 U64(0x9845418C, 0x345644D6), U64(0x830A1389, 0x6B78AAA9), /* ~= 10^-285 */
1293 U64(0xBE5691EF, 0x416BD60C), U64(0x23CC986B, 0xC656D553), /* ~= 10^-284 */
1294 U64(0xEDEC366B, 0x11C6CB8F), U64(0x2CBFBE86, 0xB7EC8AA8), /* ~= 10^-283 */
1295 U64(0x94B3A202, 0xEB1C3F39), U64(0x7BF7D714, 0x32F3D6A9), /* ~= 10^-282 */
1296 U64(0xB9E08A83, 0xA5E34F07), U64(0xDAF5CCD9, 0x3FB0CC53), /* ~= 10^-281 */
1297 U64(0xE858AD24, 0x8F5C22C9), U64(0xD1B3400F, 0x8F9CFF68), /* ~= 10^-280 */
1298 U64(0x91376C36, 0xD99995BE), U64(0x23100809, 0xB9C21FA1), /* ~= 10^-279 */
1299 U64(0xB5854744, 0x8FFFFB2D), U64(0xABD40A0C, 0x2832A78A), /* ~= 10^-278 */
1300 U64(0xE2E69915, 0xB3FFF9F9), U64(0x16C90C8F, 0x323F516C), /* ~= 10^-277 */
1301 U64(0x8DD01FAD, 0x907FFC3B), U64(0xAE3DA7D9, 0x7F6792E3), /* ~= 10^-276 */
1302 U64(0xB1442798, 0xF49FFB4A), U64(0x99CD11CF, 0xDF41779C), /* ~= 10^-275 */
1303 U64(0xDD95317F, 0x31C7FA1D), U64(0x40405643, 0xD711D583), /* ~= 10^-274 */
1304 U64(0x8A7D3EEF, 0x7F1CFC52), U64(0x482835EA, 0x666B2572), /* ~= 10^-273 */
1305 U64(0xAD1C8EAB, 0x5EE43B66), U64(0xDA324365, 0x0005EECF), /* ~= 10^-272 */
1306 U64(0xD863B256, 0x369D4A40), U64(0x90BED43E, 0x40076A82), /* ~= 10^-271 */
1307 U64(0x873E4F75, 0xE2224E68), U64(0x5A7744A6, 0xE804A291), /* ~= 10^-270 */
1308 U64(0xA90DE353, 0x5AAAE202), U64(0x711515D0, 0xA205CB36), /* ~= 10^-269 */
1309 U64(0xD3515C28, 0x31559A83), U64(0x0D5A5B44, 0xCA873E03), /* ~= 10^-268 */
1310 U64(0x8412D999, 0x1ED58091), U64(0xE858790A, 0xFE9486C2), /* ~= 10^-267 */
1311 U64(0xA5178FFF, 0x668AE0B6), U64(0x626E974D, 0xBE39A872), /* ~= 10^-266 */
1312 U64(0xCE5D73FF, 0x402D98E3), U64(0xFB0A3D21, 0x2DC8128F), /* ~= 10^-265 */
1313 U64(0x80FA687F, 0x881C7F8E), U64(0x7CE66634, 0xBC9D0B99), /* ~= 10^-264 */
1314 U64(0xA139029F, 0x6A239F72), U64(0x1C1FFFC1, 0xEBC44E80), /* ~= 10^-263 */
1315 U64(0xC9874347, 0x44AC874E), U64(0xA327FFB2, 0x66B56220), /* ~= 10^-262 */
1316 U64(0xFBE91419, 0x15D7A922), U64(0x4BF1FF9F, 0x0062BAA8), /* ~= 10^-261 */
1317 U64(0x9D71AC8F, 0xADA6C9B5), U64(0x6F773FC3, 0x603DB4A9), /* ~= 10^-260 */
1318 U64(0xC4CE17B3, 0x99107C22), U64(0xCB550FB4, 0x384D21D3), /* ~= 10^-259 */
1319 U64(0xF6019DA0, 0x7F549B2B), U64(0x7E2A53A1, 0x46606A48), /* ~= 10^-258 */
1320 U64(0x99C10284, 0x4F94E0FB), U64(0x2EDA7444, 0xCBFC426D), /* ~= 10^-257 */
1321 U64(0xC0314325, 0x637A1939), U64(0xFA911155, 0xFEFB5308), /* ~= 10^-256 */
1322 U64(0xF03D93EE, 0xBC589F88), U64(0x793555AB, 0x7EBA27CA), /* ~= 10^-255 */
1323 U64(0x96267C75, 0x35B763B5), U64(0x4BC1558B, 0x2F3458DE), /* ~= 10^-254 */
1324 U64(0xBBB01B92, 0x83253CA2), U64(0x9EB1AAED, 0xFB016F16), /* ~= 10^-253 */
1325 U64(0xEA9C2277, 0x23EE8BCB), U64(0x465E15A9, 0x79C1CADC), /* ~= 10^-252 */
1326 U64(0x92A1958A, 0x7675175F), U64(0x0BFACD89, 0xEC191EC9), /* ~= 10^-251 */
1327 U64(0xB749FAED, 0x14125D36), U64(0xCEF980EC, 0x671F667B), /* ~= 10^-250 */
1328 U64(0xE51C79A8, 0x5916F484), U64(0x82B7E127, 0x80E7401A), /* ~= 10^-249 */
1329 U64(0x8F31CC09, 0x37AE58D2), U64(0xD1B2ECB8, 0xB0908810), /* ~= 10^-248 */
1330 U64(0xB2FE3F0B, 0x8599EF07), U64(0x861FA7E6, 0xDCB4AA15), /* ~= 10^-247 */
1331 U64(0xDFBDCECE, 0x67006AC9), U64(0x67A791E0, 0x93E1D49A), /* ~= 10^-246 */
1332 U64(0x8BD6A141, 0x006042BD), U64(0xE0C8BB2C, 0x5C6D24E0), /* ~= 10^-245 */
1333 U64(0xAECC4991, 0x4078536D), U64(0x58FAE9F7, 0x73886E18), /* ~= 10^-244 */
1334 U64(0xDA7F5BF5, 0x90966848), U64(0xAF39A475, 0x506A899E), /* ~= 10^-243 */
1335 U64(0x888F9979, 0x7A5E012D), U64(0x6D8406C9, 0x52429603), /* ~= 10^-242 */
1336 U64(0xAAB37FD7, 0xD8F58178), U64(0xC8E5087B, 0xA6D33B83), /* ~= 10^-241 */
1337 U64(0xD5605FCD, 0xCF32E1D6), U64(0xFB1E4A9A, 0x90880A64), /* ~= 10^-240 */
1338 U64(0x855C3BE0, 0xA17FCD26), U64(0x5CF2EEA0, 0x9A55067F), /* ~= 10^-239 */
1339 U64(0xA6B34AD8, 0xC9DFC06F), U64(0xF42FAA48, 0xC0EA481E), /* ~= 10^-238 */
1340 U64(0xD0601D8E, 0xFC57B08B), U64(0xF13B94DA, 0xF124DA26), /* ~= 10^-237 */
1341 U64(0x823C1279, 0x5DB6CE57), U64(0x76C53D08, 0xD6B70858), /* ~= 10^-236 */
1342 U64(0xA2CB1717, 0xB52481ED), U64(0x54768C4B, 0x0C64CA6E), /* ~= 10^-235 */
1343 U64(0xCB7DDCDD, 0xA26DA268), U64(0xA9942F5D, 0xCF7DFD09), /* ~= 10^-234 */
1344 U64(0xFE5D5415, 0x0B090B02), U64(0xD3F93B35, 0x435D7C4C), /* ~= 10^-233 */
1345 U64(0x9EFA548D, 0x26E5A6E1), U64(0xC47BC501, 0x4A1A6DAF), /* ~= 10^-232 */
1346 U64(0xC6B8E9B0, 0x709F109A), U64(0x359AB641, 0x9CA1091B), /* ~= 10^-231 */
1347 U64(0xF867241C, 0x8CC6D4C0), U64(0xC30163D2, 0x03C94B62), /* ~= 10^-230 */
1348 U64(0x9B407691, 0xD7FC44F8), U64(0x79E0DE63, 0x425DCF1D), /* ~= 10^-229 */
1349 U64(0xC2109436, 0x4DFB5636), U64(0x985915FC, 0x12F542E4), /* ~= 10^-228 */
1350 U64(0xF294B943, 0xE17A2BC4), U64(0x3E6F5B7B, 0x17B2939D), /* ~= 10^-227 */
1351 U64(0x979CF3CA, 0x6CEC5B5A), U64(0xA705992C, 0xEECF9C42), /* ~= 10^-226 */
1352 U64(0xBD8430BD, 0x08277231), U64(0x50C6FF78, 0x2A838353), /* ~= 10^-225 */
1353 U64(0xECE53CEC, 0x4A314EBD), U64(0xA4F8BF56, 0x35246428), /* ~= 10^-224 */
1354 U64(0x940F4613, 0xAE5ED136), U64(0x871B7795, 0xE136BE99), /* ~= 10^-223 */
1355 U64(0xB9131798, 0x99F68584), U64(0x28E2557B, 0x59846E3F), /* ~= 10^-222 */
1356 U64(0xE757DD7E, 0xC07426E5), U64(0x331AEADA, 0x2FE589CF), /* ~= 10^-221 */
1357 U64(0x9096EA6F, 0x3848984F), U64(0x3FF0D2C8, 0x5DEF7621), /* ~= 10^-220 */
1358 U64(0xB4BCA50B, 0x065ABE63), U64(0x0FED077A, 0x756B53A9), /* ~= 10^-219 */
1359 U64(0xE1EBCE4D, 0xC7F16DFB), U64(0xD3E84959, 0x12C62894), /* ~= 10^-218 */
1360 U64(0x8D3360F0, 0x9CF6E4BD), U64(0x64712DD7, 0xABBBD95C), /* ~= 10^-217 */
1361 U64(0xB080392C, 0xC4349DEC), U64(0xBD8D794D, 0x96AACFB3), /* ~= 10^-216 */
1362 U64(0xDCA04777, 0xF541C567), U64(0xECF0D7A0, 0xFC5583A0), /* ~= 10^-215 */
1363 U64(0x89E42CAA, 0xF9491B60), U64(0xF41686C4, 0x9DB57244), /* ~= 10^-214 */
1364 U64(0xAC5D37D5, 0xB79B6239), U64(0x311C2875, 0xC522CED5), /* ~= 10^-213 */
1365 U64(0xD77485CB, 0x25823AC7), U64(0x7D633293, 0x366B828B), /* ~= 10^-212 */
1366 U64(0x86A8D39E, 0xF77164BC), U64(0xAE5DFF9C, 0x02033197), /* ~= 10^-211 */
1367 U64(0xA8530886, 0xB54DBDEB), U64(0xD9F57F83, 0x0283FDFC), /* ~= 10^-210 */
1368 U64(0xD267CAA8, 0x62A12D66), U64(0xD072DF63, 0xC324FD7B), /* ~= 10^-209 */
1369 U64(0x8380DEA9, 0x3DA4BC60), U64(0x4247CB9E, 0x59F71E6D), /* ~= 10^-208 */
1370 U64(0xA4611653, 0x8D0DEB78), U64(0x52D9BE85, 0xF074E608), /* ~= 10^-207 */
1371 U64(0xCD795BE8, 0x70516656), U64(0x67902E27, 0x6C921F8B), /* ~= 10^-206 */
1372 U64(0x806BD971, 0x4632DFF6), U64(0x00BA1CD8, 0xA3DB53B6), /* ~= 10^-205 */
1373 U64(0xA086CFCD, 0x97BF97F3), U64(0x80E8A40E, 0xCCD228A4), /* ~= 10^-204 */
1374 U64(0xC8A883C0, 0xFDAF7DF0), U64(0x6122CD12, 0x8006B2CD), /* ~= 10^-203 */
1375 U64(0xFAD2A4B1, 0x3D1B5D6C), U64(0x796B8057, 0x20085F81), /* ~= 10^-202 */
1376 U64(0x9CC3A6EE, 0xC6311A63), U64(0xCBE33036, 0x74053BB0), /* ~= 10^-201 */
1377 U64(0xC3F490AA, 0x77BD60FC), U64(0xBEDBFC44, 0x11068A9C), /* ~= 10^-200 */
1378 U64(0xF4F1B4D5, 0x15ACB93B), U64(0xEE92FB55, 0x15482D44), /* ~= 10^-199 */
1379 U64(0x99171105, 0x2D8BF3C5), U64(0x751BDD15, 0x2D4D1C4A), /* ~= 10^-198 */
1380 U64(0xBF5CD546, 0x78EEF0B6), U64(0xD262D45A, 0x78A0635D), /* ~= 10^-197 */
1381 U64(0xEF340A98, 0x172AACE4), U64(0x86FB8971, 0x16C87C34), /* ~= 10^-196 */
1382 U64(0x9580869F, 0x0E7AAC0E), U64(0xD45D35E6, 0xAE3D4DA0), /* ~= 10^-195 */
1383 U64(0xBAE0A846, 0xD2195712), U64(0x89748360, 0x59CCA109), /* ~= 10^-194 */
1384 U64(0xE998D258, 0x869FACD7), U64(0x2BD1A438, 0x703FC94B), /* ~= 10^-193 */
1385 U64(0x91FF8377, 0x5423CC06), U64(0x7B6306A3, 0x4627DDCF), /* ~= 10^-192 */
1386 U64(0xB67F6455, 0x292CBF08), U64(0x1A3BC84C, 0x17B1D542), /* ~= 10^-191 */
1387 U64(0xE41F3D6A, 0x7377EECA), U64(0x20CABA5F, 0x1D9E4A93), /* ~= 10^-190 */
1388 U64(0x8E938662, 0x882AF53E), U64(0x547EB47B, 0x7282EE9C), /* ~= 10^-189 */
1389 U64(0xB23867FB, 0x2A35B28D), U64(0xE99E619A, 0x4F23AA43), /* ~= 10^-188 */
1390 U64(0xDEC681F9, 0xF4C31F31), U64(0x6405FA00, 0xE2EC94D4), /* ~= 10^-187 */
1391 U64(0x8B3C113C, 0x38F9F37E), U64(0xDE83BC40, 0x8DD3DD04), /* ~= 10^-186 */
1392 U64(0xAE0B158B, 0x4738705E), U64(0x9624AB50, 0xB148D445), /* ~= 10^-185 */
1393 U64(0xD98DDAEE, 0x19068C76), U64(0x3BADD624, 0xDD9B0957), /* ~= 10^-184 */
1394 U64(0x87F8A8D4, 0xCFA417C9), U64(0xE54CA5D7, 0x0A80E5D6), /* ~= 10^-183 */
1395 U64(0xA9F6D30A, 0x038D1DBC), U64(0x5E9FCF4C, 0xCD211F4C), /* ~= 10^-182 */
1396 U64(0xD47487CC, 0x8470652B), U64(0x7647C320, 0x0069671F), /* ~= 10^-181 */
1397 U64(0x84C8D4DF, 0xD2C63F3B), U64(0x29ECD9F4, 0x0041E073), /* ~= 10^-180 */
1398 U64(0xA5FB0A17, 0xC777CF09), U64(0xF4681071, 0x00525890), /* ~= 10^-179 */
1399 U64(0xCF79CC9D, 0xB955C2CC), U64(0x7182148D, 0x4066EEB4), /* ~= 10^-178 */
1400 U64(0x81AC1FE2, 0x93D599BF), U64(0xC6F14CD8, 0x48405530), /* ~= 10^-177 */
1401 U64(0xA21727DB, 0x38CB002F), U64(0xB8ADA00E, 0x5A506A7C), /* ~= 10^-176 */
1402 U64(0xCA9CF1D2, 0x06FDC03B), U64(0xA6D90811, 0xF0E4851C), /* ~= 10^-175 */
1403 U64(0xFD442E46, 0x88BD304A), U64(0x908F4A16, 0x6D1DA663), /* ~= 10^-174 */
1404 U64(0x9E4A9CEC, 0x15763E2E), U64(0x9A598E4E, 0x043287FE), /* ~= 10^-173 */
1405 U64(0xC5DD4427, 0x1AD3CDBA), U64(0x40EFF1E1, 0x853F29FD), /* ~= 10^-172 */
1406 U64(0xF7549530, 0xE188C128), U64(0xD12BEE59, 0xE68EF47C), /* ~= 10^-171 */
1407 U64(0x9A94DD3E, 0x8CF578B9), U64(0x82BB74F8, 0x301958CE), /* ~= 10^-170 */
1408 U64(0xC13A148E, 0x3032D6E7), U64(0xE36A5236, 0x3C1FAF01), /* ~= 10^-169 */
1409 U64(0xF18899B1, 0xBC3F8CA1), U64(0xDC44E6C3, 0xCB279AC1), /* ~= 10^-168 */
1410 U64(0x96F5600F, 0x15A7B7E5), U64(0x29AB103A, 0x5EF8C0B9), /* ~= 10^-167 */
1411 U64(0xBCB2B812, 0xDB11A5DE), U64(0x7415D448, 0xF6B6F0E7), /* ~= 10^-166 */
1412 U64(0xEBDF6617, 0x91D60F56), U64(0x111B495B, 0x3464AD21), /* ~= 10^-165 */
1413 U64(0x936B9FCE, 0xBB25C995), U64(0xCAB10DD9, 0x00BEEC34), /* ~= 10^-164 */
1414 U64(0xB84687C2, 0x69EF3BFB), U64(0x3D5D514F, 0x40EEA742), /* ~= 10^-163 */
1415 U64(0xE65829B3, 0x046B0AFA), U64(0x0CB4A5A3, 0x112A5112), /* ~= 10^-162 */
1416 U64(0x8FF71A0F, 0xE2C2E6DC), U64(0x47F0E785, 0xEABA72AB), /* ~= 10^-161 */
1417 U64(0xB3F4E093, 0xDB73A093), U64(0x59ED2167, 0x65690F56), /* ~= 10^-160 */
1418 U64(0xE0F218B8, 0xD25088B8), U64(0x306869C1, 0x3EC3532C), /* ~= 10^-159 */
1419 U64(0x8C974F73, 0x83725573), U64(0x1E414218, 0xC73A13FB), /* ~= 10^-158 */
1420 U64(0xAFBD2350, 0x644EEACF), U64(0xE5D1929E, 0xF90898FA), /* ~= 10^-157 */
1421 U64(0xDBAC6C24, 0x7D62A583), U64(0xDF45F746, 0xB74ABF39), /* ~= 10^-156 */
1422 U64(0x894BC396, 0xCE5DA772), U64(0x6B8BBA8C, 0x328EB783), /* ~= 10^-155 */
1423 U64(0xAB9EB47C, 0x81F5114F), U64(0x066EA92F, 0x3F326564), /* ~= 10^-154 */
1424 U64(0xD686619B, 0xA27255A2), U64(0xC80A537B, 0x0EFEFEBD), /* ~= 10^-153 */
1425 U64(0x8613FD01, 0x45877585), U64(0xBD06742C, 0xE95F5F36), /* ~= 10^-152 */
1426 U64(0xA798FC41, 0x96E952E7), U64(0x2C481138, 0x23B73704), /* ~= 10^-151 */
1427 U64(0xD17F3B51, 0xFCA3A7A0), U64(0xF75A1586, 0x2CA504C5), /* ~= 10^-150 */
1428 U64(0x82EF8513, 0x3DE648C4), U64(0x9A984D73, 0xDBE722FB), /* ~= 10^-149 */
1429 U64(0xA3AB6658, 0x0D5FDAF5), U64(0xC13E60D0, 0xD2E0EBBA), /* ~= 10^-148 */
1430 U64(0xCC963FEE, 0x10B7D1B3), U64(0x318DF905, 0x079926A8), /* ~= 10^-147 */
1431 U64(0xFFBBCFE9, 0x94E5C61F), U64(0xFDF17746, 0x497F7052), /* ~= 10^-146 */
1432 U64(0x9FD561F1, 0xFD0F9BD3), U64(0xFEB6EA8B, 0xEDEFA633), /* ~= 10^-145 */
1433 U64(0xC7CABA6E, 0x7C5382C8), U64(0xFE64A52E, 0xE96B8FC0), /* ~= 10^-144 */
1434 U64(0xF9BD690A, 0x1B68637B), U64(0x3DFDCE7A, 0xA3C673B0), /* ~= 10^-143 */
1435 U64(0x9C1661A6, 0x51213E2D), U64(0x06BEA10C, 0xA65C084E), /* ~= 10^-142 */
1436 U64(0xC31BFA0F, 0xE5698DB8), U64(0x486E494F, 0xCFF30A62), /* ~= 10^-141 */
1437 U64(0xF3E2F893, 0xDEC3F126), U64(0x5A89DBA3, 0xC3EFCCFA), /* ~= 10^-140 */
1438 U64(0x986DDB5C, 0x6B3A76B7), U64(0xF8962946, 0x5A75E01C), /* ~= 10^-139 */
1439 U64(0xBE895233, 0x86091465), U64(0xF6BBB397, 0xF1135823), /* ~= 10^-138 */
1440 U64(0xEE2BA6C0, 0x678B597F), U64(0x746AA07D, 0xED582E2C), /* ~= 10^-137 */
1441 U64(0x94DB4838, 0x40B717EF), U64(0xA8C2A44E, 0xB4571CDC), /* ~= 10^-136 */
1442 U64(0xBA121A46, 0x50E4DDEB), U64(0x92F34D62, 0x616CE413), /* ~= 10^-135 */
1443 U64(0xE896A0D7, 0xE51E1566), U64(0x77B020BA, 0xF9C81D17), /* ~= 10^-134 */
1444 U64(0x915E2486, 0xEF32CD60), U64(0x0ACE1474, 0xDC1D122E), /* ~= 10^-133 */
1445 U64(0xB5B5ADA8, 0xAAFF80B8), U64(0x0D819992, 0x132456BA), /* ~= 10^-132 */
1446 U64(0xE3231912, 0xD5BF60E6), U64(0x10E1FFF6, 0x97ED6C69), /* ~= 10^-131 */
1447 U64(0x8DF5EFAB, 0xC5979C8F), U64(0xCA8D3FFA, 0x1EF463C1), /* ~= 10^-130 */
1448 U64(0xB1736B96, 0xB6FD83B3), U64(0xBD308FF8, 0xA6B17CB2), /* ~= 10^-129 */
1449 U64(0xDDD0467C, 0x64BCE4A0), U64(0xAC7CB3F6, 0xD05DDBDE), /* ~= 10^-128 */
1450 U64(0x8AA22C0D, 0xBEF60EE4), U64(0x6BCDF07A, 0x423AA96B), /* ~= 10^-127 */
1451 U64(0xAD4AB711, 0x2EB3929D), U64(0x86C16C98, 0xD2C953C6), /* ~= 10^-126 */
1452 U64(0xD89D64D5, 0x7A607744), U64(0xE871C7BF, 0x077BA8B7), /* ~= 10^-125 */
1453 U64(0x87625F05, 0x6C7C4A8B), U64(0x11471CD7, 0x64AD4972), /* ~= 10^-124 */
1454 U64(0xA93AF6C6, 0xC79B5D2D), U64(0xD598E40D, 0x3DD89BCF), /* ~= 10^-123 */
1455 U64(0xD389B478, 0x79823479), U64(0x4AFF1D10, 0x8D4EC2C3), /* ~= 10^-122 */
1456 U64(0x843610CB, 0x4BF160CB), U64(0xCEDF722A, 0x585139BA), /* ~= 10^-121 */
1457 U64(0xA54394FE, 0x1EEDB8FE), U64(0xC2974EB4, 0xEE658828), /* ~= 10^-120 */
1458 U64(0xCE947A3D, 0xA6A9273E), U64(0x733D2262, 0x29FEEA32), /* ~= 10^-119 */
1459 U64(0x811CCC66, 0x8829B887), U64(0x0806357D, 0x5A3F525F), /* ~= 10^-118 */
1460 U64(0xA163FF80, 0x2A3426A8), U64(0xCA07C2DC, 0xB0CF26F7), /* ~= 10^-117 */
1461 U64(0xC9BCFF60, 0x34C13052), U64(0xFC89B393, 0xDD02F0B5), /* ~= 10^-116 */
1462 U64(0xFC2C3F38, 0x41F17C67), U64(0xBBAC2078, 0xD443ACE2), /* ~= 10^-115 */
1463 U64(0x9D9BA783, 0x2936EDC0), U64(0xD54B944B, 0x84AA4C0D), /* ~= 10^-114 */
1464 U64(0xC5029163, 0xF384A931), U64(0x0A9E795E, 0x65D4DF11), /* ~= 10^-113 */
1465 U64(0xF64335BC, 0xF065D37D), U64(0x4D4617B5, 0xFF4A16D5), /* ~= 10^-112 */
1466 U64(0x99EA0196, 0x163FA42E), U64(0x504BCED1, 0xBF8E4E45), /* ~= 10^-111 */
1467 U64(0xC06481FB, 0x9BCF8D39), U64(0xE45EC286, 0x2F71E1D6), /* ~= 10^-110 */
1468 U64(0xF07DA27A, 0x82C37088), U64(0x5D767327, 0xBB4E5A4C), /* ~= 10^-109 */
1469 U64(0x964E858C, 0x91BA2655), U64(0x3A6A07F8, 0xD510F86F), /* ~= 10^-108 */
1470 U64(0xBBE226EF, 0xB628AFEA), U64(0x890489F7, 0x0A55368B), /* ~= 10^-107 */
1471 U64(0xEADAB0AB, 0xA3B2DBE5), U64(0x2B45AC74, 0xCCEA842E), /* ~= 10^-106 */
1472 U64(0x92C8AE6B, 0x464FC96F), U64(0x3B0B8BC9, 0x0012929D), /* ~= 10^-105 */
1473 U64(0xB77ADA06, 0x17E3BBCB), U64(0x09CE6EBB, 0x40173744), /* ~= 10^-104 */
1474 U64(0xE5599087, 0x9DDCAABD), U64(0xCC420A6A, 0x101D0515), /* ~= 10^-103 */
1475 U64(0x8F57FA54, 0xC2A9EAB6), U64(0x9FA94682, 0x4A12232D), /* ~= 10^-102 */
1476 U64(0xB32DF8E9, 0xF3546564), U64(0x47939822, 0xDC96ABF9), /* ~= 10^-101 */
1477 U64(0xDFF97724, 0x70297EBD), U64(0x59787E2B, 0x93BC56F7), /* ~= 10^-100 */
1478 U64(0x8BFBEA76, 0xC619EF36), U64(0x57EB4EDB, 0x3C55B65A), /* ~= 10^-99 */
1479 U64(0xAEFAE514, 0x77A06B03), U64(0xEDE62292, 0x0B6B23F1), /* ~= 10^-98 */
1480 U64(0xDAB99E59, 0x958885C4), U64(0xE95FAB36, 0x8E45ECED), /* ~= 10^-97 */
1481 U64(0x88B402F7, 0xFD75539B), U64(0x11DBCB02, 0x18EBB414), /* ~= 10^-96 */
1482 U64(0xAAE103B5, 0xFCD2A881), U64(0xD652BDC2, 0x9F26A119), /* ~= 10^-95 */
1483 U64(0xD59944A3, 0x7C0752A2), U64(0x4BE76D33, 0x46F0495F), /* ~= 10^-94 */
1484 U64(0x857FCAE6, 0x2D8493A5), U64(0x6F70A440, 0x0C562DDB), /* ~= 10^-93 */
1485 U64(0xA6DFBD9F, 0xB8E5B88E), U64(0xCB4CCD50, 0x0F6BB952), /* ~= 10^-92 */
1486 U64(0xD097AD07, 0xA71F26B2), U64(0x7E2000A4, 0x1346A7A7), /* ~= 10^-91 */
1487 U64(0x825ECC24, 0xC873782F), U64(0x8ED40066, 0x8C0C28C8), /* ~= 10^-90 */
1488 U64(0xA2F67F2D, 0xFA90563B), U64(0x72890080, 0x2F0F32FA), /* ~= 10^-89 */
1489 U64(0xCBB41EF9, 0x79346BCA), U64(0x4F2B40A0, 0x3AD2FFB9), /* ~= 10^-88 */
1490 U64(0xFEA126B7, 0xD78186BC), U64(0xE2F610C8, 0x4987BFA8), /* ~= 10^-87 */
1491 U64(0x9F24B832, 0xE6B0F436), U64(0x0DD9CA7D, 0x2DF4D7C9), /* ~= 10^-86 */
1492 U64(0xC6EDE63F, 0xA05D3143), U64(0x91503D1C, 0x79720DBB), /* ~= 10^-85 */
1493 U64(0xF8A95FCF, 0x88747D94), U64(0x75A44C63, 0x97CE912A), /* ~= 10^-84 */
1494 U64(0x9B69DBE1, 0xB548CE7C), U64(0xC986AFBE, 0x3EE11ABA), /* ~= 10^-83 */
1495 U64(0xC24452DA, 0x229B021B), U64(0xFBE85BAD, 0xCE996168), /* ~= 10^-82 */
1496 U64(0xF2D56790, 0xAB41C2A2), U64(0xFAE27299, 0x423FB9C3), /* ~= 10^-81 */
1497 U64(0x97C560BA, 0x6B0919A5), U64(0xDCCD879F, 0xC967D41A), /* ~= 10^-80 */
1498 U64(0xBDB6B8E9, 0x05CB600F), U64(0x5400E987, 0xBBC1C920), /* ~= 10^-79 */
1499 U64(0xED246723, 0x473E3813), U64(0x290123E9, 0xAAB23B68), /* ~= 10^-78 */
1500 U64(0x9436C076, 0x0C86E30B), U64(0xF9A0B672, 0x0AAF6521), /* ~= 10^-77 */
1501 U64(0xB9447093, 0x8FA89BCE), U64(0xF808E40E, 0x8D5B3E69), /* ~= 10^-76 */
1502 U64(0xE7958CB8, 0x7392C2C2), U64(0xB60B1D12, 0x30B20E04), /* ~= 10^-75 */
1503 U64(0x90BD77F3, 0x483BB9B9), U64(0xB1C6F22B, 0x5E6F48C2), /* ~= 10^-74 */
1504 U64(0xB4ECD5F0, 0x1A4AA828), U64(0x1E38AEB6, 0x360B1AF3), /* ~= 10^-73 */
1505 U64(0xE2280B6C, 0x20DD5232), U64(0x25C6DA63, 0xC38DE1B0), /* ~= 10^-72 */
1506 U64(0x8D590723, 0x948A535F), U64(0x579C487E, 0x5A38AD0E), /* ~= 10^-71 */
1507 U64(0xB0AF48EC, 0x79ACE837), U64(0x2D835A9D, 0xF0C6D851), /* ~= 10^-70 */
1508 U64(0xDCDB1B27, 0x98182244), U64(0xF8E43145, 0x6CF88E65), /* ~= 10^-69 */
1509 U64(0x8A08F0F8, 0xBF0F156B), U64(0x1B8E9ECB, 0x641B58FF), /* ~= 10^-68 */
1510 U64(0xAC8B2D36, 0xEED2DAC5), U64(0xE272467E, 0x3D222F3F), /* ~= 10^-67 */
1511 U64(0xD7ADF884, 0xAA879177), U64(0x5B0ED81D, 0xCC6ABB0F), /* ~= 10^-66 */
1512 U64(0x86CCBB52, 0xEA94BAEA), U64(0x98E94712, 0x9FC2B4E9), /* ~= 10^-65 */
1513 U64(0xA87FEA27, 0xA539E9A5), U64(0x3F2398D7, 0x47B36224), /* ~= 10^-64 */
1514 U64(0xD29FE4B1, 0x8E88640E), U64(0x8EEC7F0D, 0x19A03AAD), /* ~= 10^-63 */
1515 U64(0x83A3EEEE, 0xF9153E89), U64(0x1953CF68, 0x300424AC), /* ~= 10^-62 */
1516 U64(0xA48CEAAA, 0xB75A8E2B), U64(0x5FA8C342, 0x3C052DD7), /* ~= 10^-61 */
1517 U64(0xCDB02555, 0x653131B6), U64(0x3792F412, 0xCB06794D), /* ~= 10^-60 */
1518 U64(0x808E1755, 0x5F3EBF11), U64(0xE2BBD88B, 0xBEE40BD0), /* ~= 10^-59 */
1519 U64(0xA0B19D2A, 0xB70E6ED6), U64(0x5B6ACEAE, 0xAE9D0EC4), /* ~= 10^-58 */
1520 U64(0xC8DE0475, 0x64D20A8B), U64(0xF245825A, 0x5A445275), /* ~= 10^-57 */
1521 U64(0xFB158592, 0xBE068D2E), U64(0xEED6E2F0, 0xF0D56712), /* ~= 10^-56 */
1522 U64(0x9CED737B, 0xB6C4183D), U64(0x55464DD6, 0x9685606B), /* ~= 10^-55 */
1523 U64(0xC428D05A, 0xA4751E4C), U64(0xAA97E14C, 0x3C26B886), /* ~= 10^-54 */
1524 U64(0xF5330471, 0x4D9265DF), U64(0xD53DD99F, 0x4B3066A8), /* ~= 10^-53 */
1525 U64(0x993FE2C6, 0xD07B7FAB), U64(0xE546A803, 0x8EFE4029), /* ~= 10^-52 */
1526 U64(0xBF8FDB78, 0x849A5F96), U64(0xDE985204, 0x72BDD033), /* ~= 10^-51 */
1527 U64(0xEF73D256, 0xA5C0F77C), U64(0x963E6685, 0x8F6D4440), /* ~= 10^-50 */
1528 U64(0x95A86376, 0x27989AAD), U64(0xDDE70013, 0x79A44AA8), /* ~= 10^-49 */
1529 U64(0xBB127C53, 0xB17EC159), U64(0x5560C018, 0x580D5D52), /* ~= 10^-48 */
1530 U64(0xE9D71B68, 0x9DDE71AF), U64(0xAAB8F01E, 0x6E10B4A6), /* ~= 10^-47 */
1531 U64(0x92267121, 0x62AB070D), U64(0xCAB39613, 0x04CA70E8), /* ~= 10^-46 */
1532 U64(0xB6B00D69, 0xBB55C8D1), U64(0x3D607B97, 0xC5FD0D22), /* ~= 10^-45 */
1533 U64(0xE45C10C4, 0x2A2B3B05), U64(0x8CB89A7D, 0xB77C506A), /* ~= 10^-44 */
1534 U64(0x8EB98A7A, 0x9A5B04E3), U64(0x77F3608E, 0x92ADB242), /* ~= 10^-43 */
1535 U64(0xB267ED19, 0x40F1C61C), U64(0x55F038B2, 0x37591ED3), /* ~= 10^-42 */
1536 U64(0xDF01E85F, 0x912E37A3), U64(0x6B6C46DE, 0xC52F6688), /* ~= 10^-41 */
1537 U64(0x8B61313B, 0xBABCE2C6), U64(0x2323AC4B, 0x3B3DA015), /* ~= 10^-40 */
1538 U64(0xAE397D8A, 0xA96C1B77), U64(0xABEC975E, 0x0A0D081A), /* ~= 10^-39 */
1539 U64(0xD9C7DCED, 0x53C72255), U64(0x96E7BD35, 0x8C904A21), /* ~= 10^-38 */
1540 U64(0x881CEA14, 0x545C7575), U64(0x7E50D641, 0x77DA2E54), /* ~= 10^-37 */
1541 U64(0xAA242499, 0x697392D2), U64(0xDDE50BD1, 0xD5D0B9E9), /* ~= 10^-36 */
1542 U64(0xD4AD2DBF, 0xC3D07787), U64(0x955E4EC6, 0x4B44E864), /* ~= 10^-35 */
1543 U64(0x84EC3C97, 0xDA624AB4), U64(0xBD5AF13B, 0xEF0B113E), /* ~= 10^-34 */
1544 U64(0xA6274BBD, 0xD0FADD61), U64(0xECB1AD8A, 0xEACDD58E), /* ~= 10^-33 */
1545 U64(0xCFB11EAD, 0x453994BA), U64(0x67DE18ED, 0xA5814AF2), /* ~= 10^-32 */
1546 U64(0x81CEB32C, 0x4B43FCF4), U64(0x80EACF94, 0x8770CED7), /* ~= 10^-31 */
1547 U64(0xA2425FF7, 0x5E14FC31), U64(0xA1258379, 0xA94D028D), /* ~= 10^-30 */
1548 U64(0xCAD2F7F5, 0x359A3B3E), U64(0x096EE458, 0x13A04330), /* ~= 10^-29 */
1549 U64(0xFD87B5F2, 0x8300CA0D), U64(0x8BCA9D6E, 0x188853FC), /* ~= 10^-28 */
1550 U64(0x9E74D1B7, 0x91E07E48), U64(0x775EA264, 0xCF55347D), /* ~= 10^-27 */
1551 U64(0xC6120625, 0x76589DDA), U64(0x95364AFE, 0x032A819D), /* ~= 10^-26 */
1552 U64(0xF79687AE, 0xD3EEC551), U64(0x3A83DDBD, 0x83F52204), /* ~= 10^-25 */
1553 U64(0x9ABE14CD, 0x44753B52), U64(0xC4926A96, 0x72793542), /* ~= 10^-24 */
1554 U64(0xC16D9A00, 0x95928A27), U64(0x75B7053C, 0x0F178293), /* ~= 10^-23 */
1555 U64(0xF1C90080, 0xBAF72CB1), U64(0x5324C68B, 0x12DD6338), /* ~= 10^-22 */
1556 U64(0x971DA050, 0x74DA7BEE), U64(0xD3F6FC16, 0xEBCA5E03), /* ~= 10^-21 */
1557 U64(0xBCE50864, 0x92111AEA), U64(0x88F4BB1C, 0xA6BCF584), /* ~= 10^-20 */
1558 U64(0xEC1E4A7D, 0xB69561A5), U64(0x2B31E9E3, 0xD06C32E5), /* ~= 10^-19 */
1559 U64(0x9392EE8E, 0x921D5D07), U64(0x3AFF322E, 0x62439FCF), /* ~= 10^-18 */
1560 U64(0xB877AA32, 0x36A4B449), U64(0x09BEFEB9, 0xFAD487C2), /* ~= 10^-17 */
1561 U64(0xE69594BE, 0xC44DE15B), U64(0x4C2EBE68, 0x7989A9B3), /* ~= 10^-16 */
1562 U64(0x901D7CF7, 0x3AB0ACD9), U64(0x0F9D3701, 0x4BF60A10), /* ~= 10^-15 */
1563 U64(0xB424DC35, 0x095CD80F), U64(0x538484C1, 0x9EF38C94), /* ~= 10^-14 */
1564 U64(0xE12E1342, 0x4BB40E13), U64(0x2865A5F2, 0x06B06FB9), /* ~= 10^-13 */
1565 U64(0x8CBCCC09, 0x6F5088CB), U64(0xF93F87B7, 0x442E45D3), /* ~= 10^-12 */
1566 U64(0xAFEBFF0B, 0xCB24AAFE), U64(0xF78F69A5, 0x1539D748), /* ~= 10^-11 */
1567 U64(0xDBE6FECE, 0xBDEDD5BE), U64(0xB573440E, 0x5A884D1B), /* ~= 10^-10 */
1568 U64(0x89705F41, 0x36B4A597), U64(0x31680A88, 0xF8953030), /* ~= 10^-9 */
1569 U64(0xABCC7711, 0x8461CEFC), U64(0xFDC20D2B, 0x36BA7C3D), /* ~= 10^-8 */
1570 U64(0xD6BF94D5, 0xE57A42BC), U64(0x3D329076, 0x04691B4C), /* ~= 10^-7 */
1571 U64(0x8637BD05, 0xAF6C69B5), U64(0xA63F9A49, 0xC2C1B10F), /* ~= 10^-6 */
1572 U64(0xA7C5AC47, 0x1B478423), U64(0x0FCF80DC, 0x33721D53), /* ~= 10^-5 */
1573 U64(0xD1B71758, 0xE219652B), U64(0xD3C36113, 0x404EA4A8), /* ~= 10^-4 */
1574 U64(0x83126E97, 0x8D4FDF3B), U64(0x645A1CAC, 0x083126E9), /* ~= 10^-3 */
1575 U64(0xA3D70A3D, 0x70A3D70A), U64(0x3D70A3D7, 0x0A3D70A3), /* ~= 10^-2 */
1576 U64(0xCCCCCCCC, 0xCCCCCCCC), U64(0xCCCCCCCC, 0xCCCCCCCC), /* ~= 10^-1 */
1577 U64(0x80000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^0 */
1578 U64(0xA0000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^1 */
1579 U64(0xC8000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^2 */
1580 U64(0xFA000000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^3 */
1581 U64(0x9C400000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^4 */
1582 U64(0xC3500000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^5 */
1583 U64(0xF4240000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^6 */
1584 U64(0x98968000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^7 */
1585 U64(0xBEBC2000, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^8 */
1586 U64(0xEE6B2800, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^9 */
1587 U64(0x9502F900, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^10 */
1588 U64(0xBA43B740, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^11 */
1589 U64(0xE8D4A510, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^12 */
1590 U64(0x9184E72A, 0x00000000), U64(0x00000000, 0x00000000), /* == 10^13 */
1591 U64(0xB5E620F4, 0x80000000), U64(0x00000000, 0x00000000), /* == 10^14 */
1592 U64(0xE35FA931, 0xA0000000), U64(0x00000000, 0x00000000), /* == 10^15 */
1593 U64(0x8E1BC9BF, 0x04000000), U64(0x00000000, 0x00000000), /* == 10^16 */
1594 U64(0xB1A2BC2E, 0xC5000000), U64(0x00000000, 0x00000000), /* == 10^17 */
1595 U64(0xDE0B6B3A, 0x76400000), U64(0x00000000, 0x00000000), /* == 10^18 */
1596 U64(0x8AC72304, 0x89E80000), U64(0x00000000, 0x00000000), /* == 10^19 */
1597 U64(0xAD78EBC5, 0xAC620000), U64(0x00000000, 0x00000000), /* == 10^20 */
1598 U64(0xD8D726B7, 0x177A8000), U64(0x00000000, 0x00000000), /* == 10^21 */
1599 U64(0x87867832, 0x6EAC9000), U64(0x00000000, 0x00000000), /* == 10^22 */
1600 U64(0xA968163F, 0x0A57B400), U64(0x00000000, 0x00000000), /* == 10^23 */
1601 U64(0xD3C21BCE, 0xCCEDA100), U64(0x00000000, 0x00000000), /* == 10^24 */
1602 U64(0x84595161, 0x401484A0), U64(0x00000000, 0x00000000), /* == 10^25 */
1603 U64(0xA56FA5B9, 0x9019A5C8), U64(0x00000000, 0x00000000), /* == 10^26 */
1604 U64(0xCECB8F27, 0xF4200F3A), U64(0x00000000, 0x00000000), /* == 10^27 */
1605 U64(0x813F3978, 0xF8940984), U64(0x40000000, 0x00000000), /* == 10^28 */
1606 U64(0xA18F07D7, 0x36B90BE5), U64(0x50000000, 0x00000000), /* == 10^29 */
1607 U64(0xC9F2C9CD, 0x04674EDE), U64(0xA4000000, 0x00000000), /* == 10^30 */
1608 U64(0xFC6F7C40, 0x45812296), U64(0x4D000000, 0x00000000), /* == 10^31 */
1609 U64(0x9DC5ADA8, 0x2B70B59D), U64(0xF0200000, 0x00000000), /* == 10^32 */
1610 U64(0xC5371912, 0x364CE305), U64(0x6C280000, 0x00000000), /* == 10^33 */
1611 U64(0xF684DF56, 0xC3E01BC6), U64(0xC7320000, 0x00000000), /* == 10^34 */
1612 U64(0x9A130B96, 0x3A6C115C), U64(0x3C7F4000, 0x00000000), /* == 10^35 */
1613 U64(0xC097CE7B, 0xC90715B3), U64(0x4B9F1000, 0x00000000), /* == 10^36 */
1614 U64(0xF0BDC21A, 0xBB48DB20), U64(0x1E86D400, 0x00000000), /* == 10^37 */
1615 U64(0x96769950, 0xB50D88F4), U64(0x13144480, 0x00000000), /* == 10^38 */
1616 U64(0xBC143FA4, 0xE250EB31), U64(0x17D955A0, 0x00000000), /* == 10^39 */
1617 U64(0xEB194F8E, 0x1AE525FD), U64(0x5DCFAB08, 0x00000000), /* == 10^40 */
1618 U64(0x92EFD1B8, 0xD0CF37BE), U64(0x5AA1CAE5, 0x00000000), /* == 10^41 */
1619 U64(0xB7ABC627, 0x050305AD), U64(0xF14A3D9E, 0x40000000), /* == 10^42 */
1620 U64(0xE596B7B0, 0xC643C719), U64(0x6D9CCD05, 0xD0000000), /* == 10^43 */
1621 U64(0x8F7E32CE, 0x7BEA5C6F), U64(0xE4820023, 0xA2000000), /* == 10^44 */
1622 U64(0xB35DBF82, 0x1AE4F38B), U64(0xDDA2802C, 0x8A800000), /* == 10^45 */
1623 U64(0xE0352F62, 0xA19E306E), U64(0xD50B2037, 0xAD200000), /* == 10^46 */
1624 U64(0x8C213D9D, 0xA502DE45), U64(0x4526F422, 0xCC340000), /* == 10^47 */
1625 U64(0xAF298D05, 0x0E4395D6), U64(0x9670B12B, 0x7F410000), /* == 10^48 */
1626 U64(0xDAF3F046, 0x51D47B4C), U64(0x3C0CDD76, 0x5F114000), /* == 10^49 */
1627 U64(0x88D8762B, 0xF324CD0F), U64(0xA5880A69, 0xFB6AC800), /* == 10^50 */
1628 U64(0xAB0E93B6, 0xEFEE0053), U64(0x8EEA0D04, 0x7A457A00), /* == 10^51 */
1629 U64(0xD5D238A4, 0xABE98068), U64(0x72A49045, 0x98D6D880), /* == 10^52 */
1630 U64(0x85A36366, 0xEB71F041), U64(0x47A6DA2B, 0x7F864750), /* == 10^53 */
1631 U64(0xA70C3C40, 0xA64E6C51), U64(0x999090B6, 0x5F67D924), /* == 10^54 */
1632 U64(0xD0CF4B50, 0xCFE20765), U64(0xFFF4B4E3, 0xF741CF6D), /* == 10^55 */
1633 U64(0x82818F12, 0x81ED449F), U64(0xBFF8F10E, 0x7A8921A4), /* ~= 10^56 */
1634 U64(0xA321F2D7, 0x226895C7), U64(0xAFF72D52, 0x192B6A0D), /* ~= 10^57 */
1635 U64(0xCBEA6F8C, 0xEB02BB39), U64(0x9BF4F8A6, 0x9F764490), /* ~= 10^58 */
1636 U64(0xFEE50B70, 0x25C36A08), U64(0x02F236D0, 0x4753D5B4), /* ~= 10^59 */
1637 U64(0x9F4F2726, 0x179A2245), U64(0x01D76242, 0x2C946590), /* ~= 10^60 */
1638 U64(0xC722F0EF, 0x9D80AAD6), U64(0x424D3AD2, 0xB7B97EF5), /* ~= 10^61 */
1639 U64(0xF8EBAD2B, 0x84E0D58B), U64(0xD2E08987, 0x65A7DEB2), /* ~= 10^62 */
1640 U64(0x9B934C3B, 0x330C8577), U64(0x63CC55F4, 0x9F88EB2F), /* ~= 10^63 */
1641 U64(0xC2781F49, 0xFFCFA6D5), U64(0x3CBF6B71, 0xC76B25FB), /* ~= 10^64 */
1642 U64(0xF316271C, 0x7FC3908A), U64(0x8BEF464E, 0x3945EF7A), /* ~= 10^65 */
1643 U64(0x97EDD871, 0xCFDA3A56), U64(0x97758BF0, 0xE3CBB5AC), /* ~= 10^66 */
1644 U64(0xBDE94E8E, 0x43D0C8EC), U64(0x3D52EEED, 0x1CBEA317), /* ~= 10^67 */
1645 U64(0xED63A231, 0xD4C4FB27), U64(0x4CA7AAA8, 0x63EE4BDD), /* ~= 10^68 */
1646 U64(0x945E455F, 0x24FB1CF8), U64(0x8FE8CAA9, 0x3E74EF6A), /* ~= 10^69 */
1647 U64(0xB975D6B6, 0xEE39E436), U64(0xB3E2FD53, 0x8E122B44), /* ~= 10^70 */
1648 U64(0xE7D34C64, 0xA9C85D44), U64(0x60DBBCA8, 0x7196B616), /* ~= 10^71 */
1649 U64(0x90E40FBE, 0xEA1D3A4A), U64(0xBC8955E9, 0x46FE31CD), /* ~= 10^72 */
1650 U64(0xB51D13AE, 0xA4A488DD), U64(0x6BABAB63, 0x98BDBE41), /* ~= 10^73 */
1651 U64(0xE264589A, 0x4DCDAB14), U64(0xC696963C, 0x7EED2DD1), /* ~= 10^74 */
1652 U64(0x8D7EB760, 0x70A08AEC), U64(0xFC1E1DE5, 0xCF543CA2), /* ~= 10^75 */
1653 U64(0xB0DE6538, 0x8CC8ADA8), U64(0x3B25A55F, 0x43294BCB), /* ~= 10^76 */
1654 U64(0xDD15FE86, 0xAFFAD912), U64(0x49EF0EB7, 0x13F39EBE), /* ~= 10^77 */
1655 U64(0x8A2DBF14, 0x2DFCC7AB), U64(0x6E356932, 0x6C784337), /* ~= 10^78 */
1656 U64(0xACB92ED9, 0x397BF996), U64(0x49C2C37F, 0x07965404), /* ~= 10^79 */
1657 U64(0xD7E77A8F, 0x87DAF7FB), U64(0xDC33745E, 0xC97BE906), /* ~= 10^80 */
1658 U64(0x86F0AC99, 0xB4E8DAFD), U64(0x69A028BB, 0x3DED71A3), /* ~= 10^81 */
1659 U64(0xA8ACD7C0, 0x222311BC), U64(0xC40832EA, 0x0D68CE0C), /* ~= 10^82 */
1660 U64(0xD2D80DB0, 0x2AABD62B), U64(0xF50A3FA4, 0x90C30190), /* ~= 10^83 */
1661 U64(0x83C7088E, 0x1AAB65DB), U64(0x792667C6, 0xDA79E0FA), /* ~= 10^84 */
1662 U64(0xA4B8CAB1, 0xA1563F52), U64(0x577001B8, 0x91185938), /* ~= 10^85 */
1663 U64(0xCDE6FD5E, 0x09ABCF26), U64(0xED4C0226, 0xB55E6F86), /* ~= 10^86 */
1664 U64(0x80B05E5A, 0xC60B6178), U64(0x544F8158, 0x315B05B4), /* ~= 10^87 */
1665 U64(0xA0DC75F1, 0x778E39D6), U64(0x696361AE, 0x3DB1C721), /* ~= 10^88 */
1666 U64(0xC913936D, 0xD571C84C), U64(0x03BC3A19, 0xCD1E38E9), /* ~= 10^89 */
1667 U64(0xFB587849, 0x4ACE3A5F), U64(0x04AB48A0, 0x4065C723), /* ~= 10^90 */
1668 U64(0x9D174B2D, 0xCEC0E47B), U64(0x62EB0D64, 0x283F9C76), /* ~= 10^91 */
1669 U64(0xC45D1DF9, 0x42711D9A), U64(0x3BA5D0BD, 0x324F8394), /* ~= 10^92 */
1670 U64(0xF5746577, 0x930D6500), U64(0xCA8F44EC, 0x7EE36479), /* ~= 10^93 */
1671 U64(0x9968BF6A, 0xBBE85F20), U64(0x7E998B13, 0xCF4E1ECB), /* ~= 10^94 */
1672 U64(0xBFC2EF45, 0x6AE276E8), U64(0x9E3FEDD8, 0xC321A67E), /* ~= 10^95 */
1673 U64(0xEFB3AB16, 0xC59B14A2), U64(0xC5CFE94E, 0xF3EA101E), /* ~= 10^96 */
1674 U64(0x95D04AEE, 0x3B80ECE5), U64(0xBBA1F1D1, 0x58724A12), /* ~= 10^97 */
1675 U64(0xBB445DA9, 0xCA61281F), U64(0x2A8A6E45, 0xAE8EDC97), /* ~= 10^98 */
1676 U64(0xEA157514, 0x3CF97226), U64(0xF52D09D7, 0x1A3293BD), /* ~= 10^99 */
1677 U64(0x924D692C, 0xA61BE758), U64(0x593C2626, 0x705F9C56), /* ~= 10^100 */
1678 U64(0xB6E0C377, 0xCFA2E12E), U64(0x6F8B2FB0, 0x0C77836C), /* ~= 10^101 */
1679 U64(0xE498F455, 0xC38B997A), U64(0x0B6DFB9C, 0x0F956447), /* ~= 10^102 */
1680 U64(0x8EDF98B5, 0x9A373FEC), U64(0x4724BD41, 0x89BD5EAC), /* ~= 10^103 */
1681 U64(0xB2977EE3, 0x00C50FE7), U64(0x58EDEC91, 0xEC2CB657), /* ~= 10^104 */
1682 U64(0xDF3D5E9B, 0xC0F653E1), U64(0x2F2967B6, 0x6737E3ED), /* ~= 10^105 */
1683 U64(0x8B865B21, 0x5899F46C), U64(0xBD79E0D2, 0x0082EE74), /* ~= 10^106 */
1684 U64(0xAE67F1E9, 0xAEC07187), U64(0xECD85906, 0x80A3AA11), /* ~= 10^107 */
1685 U64(0xDA01EE64, 0x1A708DE9), U64(0xE80E6F48, 0x20CC9495), /* ~= 10^108 */
1686 U64(0x884134FE, 0x908658B2), U64(0x3109058D, 0x147FDCDD), /* ~= 10^109 */
1687 U64(0xAA51823E, 0x34A7EEDE), U64(0xBD4B46F0, 0x599FD415), /* ~= 10^110 */
1688 U64(0xD4E5E2CD, 0xC1D1EA96), U64(0x6C9E18AC, 0x7007C91A), /* ~= 10^111 */
1689 U64(0x850FADC0, 0x9923329E), U64(0x03E2CF6B, 0xC604DDB0), /* ~= 10^112 */
1690 U64(0xA6539930, 0xBF6BFF45), U64(0x84DB8346, 0xB786151C), /* ~= 10^113 */
1691 U64(0xCFE87F7C, 0xEF46FF16), U64(0xE6126418, 0x65679A63), /* ~= 10^114 */
1692 U64(0x81F14FAE, 0x158C5F6E), U64(0x4FCB7E8F, 0x3F60C07E), /* ~= 10^115 */
1693 U64(0xA26DA399, 0x9AEF7749), U64(0xE3BE5E33, 0x0F38F09D), /* ~= 10^116 */
1694 U64(0xCB090C80, 0x01AB551C), U64(0x5CADF5BF, 0xD3072CC5), /* ~= 10^117 */
1695 U64(0xFDCB4FA0, 0x02162A63), U64(0x73D9732F, 0xC7C8F7F6), /* ~= 10^118 */
1696 U64(0x9E9F11C4, 0x014DDA7E), U64(0x2867E7FD, 0xDCDD9AFA), /* ~= 10^119 */
1697 U64(0xC646D635, 0x01A1511D), U64(0xB281E1FD, 0x541501B8), /* ~= 10^120 */
1698 U64(0xF7D88BC2, 0x4209A565), U64(0x1F225A7C, 0xA91A4226), /* ~= 10^121 */
1699 U64(0x9AE75759, 0x6946075F), U64(0x3375788D, 0xE9B06958), /* ~= 10^122 */
1700 U64(0xC1A12D2F, 0xC3978937), U64(0x0052D6B1, 0x641C83AE), /* ~= 10^123 */
1701 U64(0xF209787B, 0xB47D6B84), U64(0xC0678C5D, 0xBD23A49A), /* ~= 10^124 */
1702 U64(0x9745EB4D, 0x50CE6332), U64(0xF840B7BA, 0x963646E0), /* ~= 10^125 */
1703 U64(0xBD176620, 0xA501FBFF), U64(0xB650E5A9, 0x3BC3D898), /* ~= 10^126 */
1704 U64(0xEC5D3FA8, 0xCE427AFF), U64(0xA3E51F13, 0x8AB4CEBE), /* ~= 10^127 */
1705 U64(0x93BA47C9, 0x80E98CDF), U64(0xC66F336C, 0x36B10137), /* ~= 10^128 */
1706 U64(0xB8A8D9BB, 0xE123F017), U64(0xB80B0047, 0x445D4184), /* ~= 10^129 */
1707 U64(0xE6D3102A, 0xD96CEC1D), U64(0xA60DC059, 0x157491E5), /* ~= 10^130 */
1708 U64(0x9043EA1A, 0xC7E41392), U64(0x87C89837, 0xAD68DB2F), /* ~= 10^131 */
1709 U64(0xB454E4A1, 0x79DD1877), U64(0x29BABE45, 0x98C311FB), /* ~= 10^132 */
1710 U64(0xE16A1DC9, 0xD8545E94), U64(0xF4296DD6, 0xFEF3D67A), /* ~= 10^133 */
1711 U64(0x8CE2529E, 0x2734BB1D), U64(0x1899E4A6, 0x5F58660C), /* ~= 10^134 */
1712 U64(0xB01AE745, 0xB101E9E4), U64(0x5EC05DCF, 0xF72E7F8F), /* ~= 10^135 */
1713 U64(0xDC21A117, 0x1D42645D), U64(0x76707543, 0xF4FA1F73), /* ~= 10^136 */
1714 U64(0x899504AE, 0x72497EBA), U64(0x6A06494A, 0x791C53A8), /* ~= 10^137 */
1715 U64(0xABFA45DA, 0x0EDBDE69), U64(0x0487DB9D, 0x17636892), /* ~= 10^138 */
1716 U64(0xD6F8D750, 0x9292D603), U64(0x45A9D284, 0x5D3C42B6), /* ~= 10^139 */
1717 U64(0x865B8692, 0x5B9BC5C2), U64(0x0B8A2392, 0xBA45A9B2), /* ~= 10^140 */
1718 U64(0xA7F26836, 0xF282B732), U64(0x8E6CAC77, 0x68D7141E), /* ~= 10^141 */
1719 U64(0xD1EF0244, 0xAF2364FF), U64(0x3207D795, 0x430CD926), /* ~= 10^142 */
1720 U64(0x8335616A, 0xED761F1F), U64(0x7F44E6BD, 0x49E807B8), /* ~= 10^143 */
1721 U64(0xA402B9C5, 0xA8D3A6E7), U64(0x5F16206C, 0x9C6209A6), /* ~= 10^144 */
1722 U64(0xCD036837, 0x130890A1), U64(0x36DBA887, 0xC37A8C0F), /* ~= 10^145 */
1723 U64(0x80222122, 0x6BE55A64), U64(0xC2494954, 0xDA2C9789), /* ~= 10^146 */
1724 U64(0xA02AA96B, 0x06DEB0FD), U64(0xF2DB9BAA, 0x10B7BD6C), /* ~= 10^147 */
1725 U64(0xC83553C5, 0xC8965D3D), U64(0x6F928294, 0x94E5ACC7), /* ~= 10^148 */
1726 U64(0xFA42A8B7, 0x3ABBF48C), U64(0xCB772339, 0xBA1F17F9), /* ~= 10^149 */
1727 U64(0x9C69A972, 0x84B578D7), U64(0xFF2A7604, 0x14536EFB), /* ~= 10^150 */
1728 U64(0xC38413CF, 0x25E2D70D), U64(0xFEF51385, 0x19684ABA), /* ~= 10^151 */
1729 U64(0xF46518C2, 0xEF5B8CD1), U64(0x7EB25866, 0x5FC25D69), /* ~= 10^152 */
1730 U64(0x98BF2F79, 0xD5993802), U64(0xEF2F773F, 0xFBD97A61), /* ~= 10^153 */
1731 U64(0xBEEEFB58, 0x4AFF8603), U64(0xAAFB550F, 0xFACFD8FA), /* ~= 10^154 */
1732 U64(0xEEAABA2E, 0x5DBF6784), U64(0x95BA2A53, 0xF983CF38), /* ~= 10^155 */
1733 U64(0x952AB45C, 0xFA97A0B2), U64(0xDD945A74, 0x7BF26183), /* ~= 10^156 */
1734 U64(0xBA756174, 0x393D88DF), U64(0x94F97111, 0x9AEEF9E4), /* ~= 10^157 */
1735 U64(0xE912B9D1, 0x478CEB17), U64(0x7A37CD56, 0x01AAB85D), /* ~= 10^158 */
1736 U64(0x91ABB422, 0xCCB812EE), U64(0xAC62E055, 0xC10AB33A), /* ~= 10^159 */
1737 U64(0xB616A12B, 0x7FE617AA), U64(0x577B986B, 0x314D6009), /* ~= 10^160 */
1738 U64(0xE39C4976, 0x5FDF9D94), U64(0xED5A7E85, 0xFDA0B80B), /* ~= 10^161 */
1739 U64(0x8E41ADE9, 0xFBEBC27D), U64(0x14588F13, 0xBE847307), /* ~= 10^162 */
1740 U64(0xB1D21964, 0x7AE6B31C), U64(0x596EB2D8, 0xAE258FC8), /* ~= 10^163 */
1741 U64(0xDE469FBD, 0x99A05FE3), U64(0x6FCA5F8E, 0xD9AEF3BB), /* ~= 10^164 */
1742 U64(0x8AEC23D6, 0x80043BEE), U64(0x25DE7BB9, 0x480D5854), /* ~= 10^165 */
1743 U64(0xADA72CCC, 0x20054AE9), U64(0xAF561AA7, 0x9A10AE6A), /* ~= 10^166 */
1744 U64(0xD910F7FF, 0x28069DA4), U64(0x1B2BA151, 0x8094DA04), /* ~= 10^167 */
1745 U64(0x87AA9AFF, 0x79042286), U64(0x90FB44D2, 0xF05D0842), /* ~= 10^168 */
1746 U64(0xA99541BF, 0x57452B28), U64(0x353A1607, 0xAC744A53), /* ~= 10^169 */
1747 U64(0xD3FA922F, 0x2D1675F2), U64(0x42889B89, 0x97915CE8), /* ~= 10^170 */
1748 U64(0x847C9B5D, 0x7C2E09B7), U64(0x69956135, 0xFEBADA11), /* ~= 10^171 */
1749 U64(0xA59BC234, 0xDB398C25), U64(0x43FAB983, 0x7E699095), /* ~= 10^172 */
1750 U64(0xCF02B2C2, 0x1207EF2E), U64(0x94F967E4, 0x5E03F4BB), /* ~= 10^173 */
1751 U64(0x8161AFB9, 0x4B44F57D), U64(0x1D1BE0EE, 0xBAC278F5), /* ~= 10^174 */
1752 U64(0xA1BA1BA7, 0x9E1632DC), U64(0x6462D92A, 0x69731732), /* ~= 10^175 */
1753 U64(0xCA28A291, 0x859BBF93), U64(0x7D7B8F75, 0x03CFDCFE), /* ~= 10^176 */
1754 U64(0xFCB2CB35, 0xE702AF78), U64(0x5CDA7352, 0x44C3D43E), /* ~= 10^177 */
1755 U64(0x9DEFBF01, 0xB061ADAB), U64(0x3A088813, 0x6AFA64A7), /* ~= 10^178 */
1756 U64(0xC56BAEC2, 0x1C7A1916), U64(0x088AAA18, 0x45B8FDD0), /* ~= 10^179 */
1757 U64(0xF6C69A72, 0xA3989F5B), U64(0x8AAD549E, 0x57273D45), /* ~= 10^180 */
1758 U64(0x9A3C2087, 0xA63F6399), U64(0x36AC54E2, 0xF678864B), /* ~= 10^181 */
1759 U64(0xC0CB28A9, 0x8FCF3C7F), U64(0x84576A1B, 0xB416A7DD), /* ~= 10^182 */
1760 U64(0xF0FDF2D3, 0xF3C30B9F), U64(0x656D44A2, 0xA11C51D5), /* ~= 10^183 */
1761 U64(0x969EB7C4, 0x7859E743), U64(0x9F644AE5, 0xA4B1B325), /* ~= 10^184 */
1762 U64(0xBC4665B5, 0x96706114), U64(0x873D5D9F, 0x0DDE1FEE), /* ~= 10^185 */
1763 U64(0xEB57FF22, 0xFC0C7959), U64(0xA90CB506, 0xD155A7EA), /* ~= 10^186 */
1764 U64(0x9316FF75, 0xDD87CBD8), U64(0x09A7F124, 0x42D588F2), /* ~= 10^187 */
1765 U64(0xB7DCBF53, 0x54E9BECE), U64(0x0C11ED6D, 0x538AEB2F), /* ~= 10^188 */
1766 U64(0xE5D3EF28, 0x2A242E81), U64(0x8F1668C8, 0xA86DA5FA), /* ~= 10^189 */
1767 U64(0x8FA47579, 0x1A569D10), U64(0xF96E017D, 0x694487BC), /* ~= 10^190 */
1768 U64(0xB38D92D7, 0x60EC4455), U64(0x37C981DC, 0xC395A9AC), /* ~= 10^191 */
1769 U64(0xE070F78D, 0x3927556A), U64(0x85BBE253, 0xF47B1417), /* ~= 10^192 */
1770 U64(0x8C469AB8, 0x43B89562), U64(0x93956D74, 0x78CCEC8E), /* ~= 10^193 */
1771 U64(0xAF584166, 0x54A6BABB), U64(0x387AC8D1, 0x970027B2), /* ~= 10^194 */
1772 U64(0xDB2E51BF, 0xE9D0696A), U64(0x06997B05, 0xFCC0319E), /* ~= 10^195 */
1773 U64(0x88FCF317, 0xF22241E2), U64(0x441FECE3, 0xBDF81F03), /* ~= 10^196 */
1774 U64(0xAB3C2FDD, 0xEEAAD25A), U64(0xD527E81C, 0xAD7626C3), /* ~= 10^197 */
1775 U64(0xD60B3BD5, 0x6A5586F1), U64(0x8A71E223, 0xD8D3B074), /* ~= 10^198 */
1776 U64(0x85C70565, 0x62757456), U64(0xF6872D56, 0x67844E49), /* ~= 10^199 */
1777 U64(0xA738C6BE, 0xBB12D16C), U64(0xB428F8AC, 0x016561DB), /* ~= 10^200 */
1778 U64(0xD106F86E, 0x69D785C7), U64(0xE13336D7, 0x01BEBA52), /* ~= 10^201 */
1779 U64(0x82A45B45, 0x0226B39C), U64(0xECC00246, 0x61173473), /* ~= 10^202 */
1780 U64(0xA34D7216, 0x42B06084), U64(0x27F002D7, 0xF95D0190), /* ~= 10^203 */
1781 U64(0xCC20CE9B, 0xD35C78A5), U64(0x31EC038D, 0xF7B441F4), /* ~= 10^204 */
1782 U64(0xFF290242, 0xC83396CE), U64(0x7E670471, 0x75A15271), /* ~= 10^205 */
1783 U64(0x9F79A169, 0xBD203E41), U64(0x0F0062C6, 0xE984D386), /* ~= 10^206 */
1784 U64(0xC75809C4, 0x2C684DD1), U64(0x52C07B78, 0xA3E60868), /* ~= 10^207 */
1785 U64(0xF92E0C35, 0x37826145), U64(0xA7709A56, 0xCCDF8A82), /* ~= 10^208 */
1786 U64(0x9BBCC7A1, 0x42B17CCB), U64(0x88A66076, 0x400BB691), /* ~= 10^209 */
1787 U64(0xC2ABF989, 0x935DDBFE), U64(0x6ACFF893, 0xD00EA435), /* ~= 10^210 */
1788 U64(0xF356F7EB, 0xF83552FE), U64(0x0583F6B8, 0xC4124D43), /* ~= 10^211 */
1789 U64(0x98165AF3, 0x7B2153DE), U64(0xC3727A33, 0x7A8B704A), /* ~= 10^212 */
1790 U64(0xBE1BF1B0, 0x59E9A8D6), U64(0x744F18C0, 0x592E4C5C), /* ~= 10^213 */
1791 U64(0xEDA2EE1C, 0x7064130C), U64(0x1162DEF0, 0x6F79DF73), /* ~= 10^214 */
1792 U64(0x9485D4D1, 0xC63E8BE7), U64(0x8ADDCB56, 0x45AC2BA8), /* ~= 10^215 */
1793 U64(0xB9A74A06, 0x37CE2EE1), U64(0x6D953E2B, 0xD7173692), /* ~= 10^216 */
1794 U64(0xE8111C87, 0xC5C1BA99), U64(0xC8FA8DB6, 0xCCDD0437), /* ~= 10^217 */
1795 U64(0x910AB1D4, 0xDB9914A0), U64(0x1D9C9892, 0x400A22A2), /* ~= 10^218 */
1796 U64(0xB54D5E4A, 0x127F59C8), U64(0x2503BEB6, 0xD00CAB4B), /* ~= 10^219 */
1797 U64(0xE2A0B5DC, 0x971F303A), U64(0x2E44AE64, 0x840FD61D), /* ~= 10^220 */
1798 U64(0x8DA471A9, 0xDE737E24), U64(0x5CEAECFE, 0xD289E5D2), /* ~= 10^221 */
1799 U64(0xB10D8E14, 0x56105DAD), U64(0x7425A83E, 0x872C5F47), /* ~= 10^222 */
1800 U64(0xDD50F199, 0x6B947518), U64(0xD12F124E, 0x28F77719), /* ~= 10^223 */
1801 U64(0x8A5296FF, 0xE33CC92F), U64(0x82BD6B70, 0xD99AAA6F), /* ~= 10^224 */
1802 U64(0xACE73CBF, 0xDC0BFB7B), U64(0x636CC64D, 0x1001550B), /* ~= 10^225 */
1803 U64(0xD8210BEF, 0xD30EFA5A), U64(0x3C47F7E0, 0x5401AA4E), /* ~= 10^226 */
1804 U64(0x8714A775, 0xE3E95C78), U64(0x65ACFAEC, 0x34810A71), /* ~= 10^227 */
1805 U64(0xA8D9D153, 0x5CE3B396), U64(0x7F1839A7, 0x41A14D0D), /* ~= 10^228 */
1806 U64(0xD31045A8, 0x341CA07C), U64(0x1EDE4811, 0x1209A050), /* ~= 10^229 */
1807 U64(0x83EA2B89, 0x2091E44D), U64(0x934AED0A, 0xAB460432), /* ~= 10^230 */
1808 U64(0xA4E4B66B, 0x68B65D60), U64(0xF81DA84D, 0x5617853F), /* ~= 10^231 */
1809 U64(0xCE1DE406, 0x42E3F4B9), U64(0x36251260, 0xAB9D668E), /* ~= 10^232 */
1810 U64(0x80D2AE83, 0xE9CE78F3), U64(0xC1D72B7C, 0x6B426019), /* ~= 10^233 */
1811 U64(0xA1075A24, 0xE4421730), U64(0xB24CF65B, 0x8612F81F), /* ~= 10^234 */
1812 U64(0xC94930AE, 0x1D529CFC), U64(0xDEE033F2, 0x6797B627), /* ~= 10^235 */
1813 U64(0xFB9B7CD9, 0xA4A7443C), U64(0x169840EF, 0x017DA3B1), /* ~= 10^236 */
1814 U64(0x9D412E08, 0x06E88AA5), U64(0x8E1F2895, 0x60EE864E), /* ~= 10^237 */
1815 U64(0xC491798A, 0x08A2AD4E), U64(0xF1A6F2BA, 0xB92A27E2), /* ~= 10^238 */
1816 U64(0xF5B5D7EC, 0x8ACB58A2), U64(0xAE10AF69, 0x6774B1DB), /* ~= 10^239 */
1817 U64(0x9991A6F3, 0xD6BF1765), U64(0xACCA6DA1, 0xE0A8EF29), /* ~= 10^240 */
1818 U64(0xBFF610B0, 0xCC6EDD3F), U64(0x17FD090A, 0x58D32AF3), /* ~= 10^241 */
1819 U64(0xEFF394DC, 0xFF8A948E), U64(0xDDFC4B4C, 0xEF07F5B0), /* ~= 10^242 */
1820 U64(0x95F83D0A, 0x1FB69CD9), U64(0x4ABDAF10, 0x1564F98E), /* ~= 10^243 */
1821 U64(0xBB764C4C, 0xA7A4440F), U64(0x9D6D1AD4, 0x1ABE37F1), /* ~= 10^244 */
1822 U64(0xEA53DF5F, 0xD18D5513), U64(0x84C86189, 0x216DC5ED), /* ~= 10^245 */
1823 U64(0x92746B9B, 0xE2F8552C), U64(0x32FD3CF5, 0xB4E49BB4), /* ~= 10^246 */
1824 U64(0xB7118682, 0xDBB66A77), U64(0x3FBC8C33, 0x221DC2A1), /* ~= 10^247 */
1825 U64(0xE4D5E823, 0x92A40515), U64(0x0FABAF3F, 0xEAA5334A), /* ~= 10^248 */
1826 U64(0x8F05B116, 0x3BA6832D), U64(0x29CB4D87, 0xF2A7400E), /* ~= 10^249 */
1827 U64(0xB2C71D5B, 0xCA9023F8), U64(0x743E20E9, 0xEF511012), /* ~= 10^250 */
1828 U64(0xDF78E4B2, 0xBD342CF6), U64(0x914DA924, 0x6B255416), /* ~= 10^251 */
1829 U64(0x8BAB8EEF, 0xB6409C1A), U64(0x1AD089B6, 0xC2F7548E), /* ~= 10^252 */
1830 U64(0xAE9672AB, 0xA3D0C320), U64(0xA184AC24, 0x73B529B1), /* ~= 10^253 */
1831 U64(0xDA3C0F56, 0x8CC4F3E8), U64(0xC9E5D72D, 0x90A2741E), /* ~= 10^254 */
1832 U64(0x88658996, 0x17FB1871), U64(0x7E2FA67C, 0x7A658892), /* ~= 10^255 */
1833 U64(0xAA7EEBFB, 0x9DF9DE8D), U64(0xDDBB901B, 0x98FEEAB7), /* ~= 10^256 */
1834 U64(0xD51EA6FA, 0x85785631), U64(0x552A7422, 0x7F3EA565), /* ~= 10^257 */
1835 U64(0x8533285C, 0x936B35DE), U64(0xD53A8895, 0x8F87275F), /* ~= 10^258 */
1836 U64(0xA67FF273, 0xB8460356), U64(0x8A892ABA, 0xF368F137), /* ~= 10^259 */
1837 U64(0xD01FEF10, 0xA657842C), U64(0x2D2B7569, 0xB0432D85), /* ~= 10^260 */
1838 U64(0x8213F56A, 0x67F6B29B), U64(0x9C3B2962, 0x0E29FC73), /* ~= 10^261 */
1839 U64(0xA298F2C5, 0x01F45F42), U64(0x8349F3BA, 0x91B47B8F), /* ~= 10^262 */
1840 U64(0xCB3F2F76, 0x42717713), U64(0x241C70A9, 0x36219A73), /* ~= 10^263 */
1841 U64(0xFE0EFB53, 0xD30DD4D7), U64(0xED238CD3, 0x83AA0110), /* ~= 10^264 */
1842 U64(0x9EC95D14, 0x63E8A506), U64(0xF4363804, 0x324A40AA), /* ~= 10^265 */
1843 U64(0xC67BB459, 0x7CE2CE48), U64(0xB143C605, 0x3EDCD0D5), /* ~= 10^266 */
1844 U64(0xF81AA16F, 0xDC1B81DA), U64(0xDD94B786, 0x8E94050A), /* ~= 10^267 */
1845 U64(0x9B10A4E5, 0xE9913128), U64(0xCA7CF2B4, 0x191C8326), /* ~= 10^268 */
1846 U64(0xC1D4CE1F, 0x63F57D72), U64(0xFD1C2F61, 0x1F63A3F0), /* ~= 10^269 */
1847 U64(0xF24A01A7, 0x3CF2DCCF), U64(0xBC633B39, 0x673C8CEC), /* ~= 10^270 */
1848 U64(0x976E4108, 0x8617CA01), U64(0xD5BE0503, 0xE085D813), /* ~= 10^271 */
1849 U64(0xBD49D14A, 0xA79DBC82), U64(0x4B2D8644, 0xD8A74E18), /* ~= 10^272 */
1850 U64(0xEC9C459D, 0x51852BA2), U64(0xDDF8E7D6, 0x0ED1219E), /* ~= 10^273 */
1851 U64(0x93E1AB82, 0x52F33B45), U64(0xCABB90E5, 0xC942B503), /* ~= 10^274 */
1852 U64(0xB8DA1662, 0xE7B00A17), U64(0x3D6A751F, 0x3B936243), /* ~= 10^275 */
1853 U64(0xE7109BFB, 0xA19C0C9D), U64(0x0CC51267, 0x0A783AD4), /* ~= 10^276 */
1854 U64(0x906A617D, 0x450187E2), U64(0x27FB2B80, 0x668B24C5), /* ~= 10^277 */
1855 U64(0xB484F9DC, 0x9641E9DA), U64(0xB1F9F660, 0x802DEDF6), /* ~= 10^278 */
1856 U64(0xE1A63853, 0xBBD26451), U64(0x5E7873F8, 0xA0396973), /* ~= 10^279 */
1857 U64(0x8D07E334, 0x55637EB2), U64(0xDB0B487B, 0x6423E1E8), /* ~= 10^280 */
1858 U64(0xB049DC01, 0x6ABC5E5F), U64(0x91CE1A9A, 0x3D2CDA62), /* ~= 10^281 */
1859 U64(0xDC5C5301, 0xC56B75F7), U64(0x7641A140, 0xCC7810FB), /* ~= 10^282 */
1860 U64(0x89B9B3E1, 0x1B6329BA), U64(0xA9E904C8, 0x7FCB0A9D), /* ~= 10^283 */
1861 U64(0xAC2820D9, 0x623BF429), U64(0x546345FA, 0x9FBDCD44), /* ~= 10^284 */
1862 U64(0xD732290F, 0xBACAF133), U64(0xA97C1779, 0x47AD4095), /* ~= 10^285 */
1863 U64(0x867F59A9, 0xD4BED6C0), U64(0x49ED8EAB, 0xCCCC485D), /* ~= 10^286 */
1864 U64(0xA81F3014, 0x49EE8C70), U64(0x5C68F256, 0xBFFF5A74), /* ~= 10^287 */
1865 U64(0xD226FC19, 0x5C6A2F8C), U64(0x73832EEC, 0x6FFF3111), /* ~= 10^288 */
1866 U64(0x83585D8F, 0xD9C25DB7), U64(0xC831FD53, 0xC5FF7EAB), /* ~= 10^289 */
1867 U64(0xA42E74F3, 0xD032F525), U64(0xBA3E7CA8, 0xB77F5E55), /* ~= 10^290 */
1868 U64(0xCD3A1230, 0xC43FB26F), U64(0x28CE1BD2, 0xE55F35EB), /* ~= 10^291 */
1869 U64(0x80444B5E, 0x7AA7CF85), U64(0x7980D163, 0xCF5B81B3), /* ~= 10^292 */
1870 U64(0xA0555E36, 0x1951C366), U64(0xD7E105BC, 0xC332621F), /* ~= 10^293 */
1871 U64(0xC86AB5C3, 0x9FA63440), U64(0x8DD9472B, 0xF3FEFAA7), /* ~= 10^294 */
1872 U64(0xFA856334, 0x878FC150), U64(0xB14F98F6, 0xF0FEB951), /* ~= 10^295 */
1873 U64(0x9C935E00, 0xD4B9D8D2), U64(0x6ED1BF9A, 0x569F33D3), /* ~= 10^296 */
1874 U64(0xC3B83581, 0x09E84F07), U64(0x0A862F80, 0xEC4700C8), /* ~= 10^297 */
1875 U64(0xF4A642E1, 0x4C6262C8), U64(0xCD27BB61, 0x2758C0FA), /* ~= 10^298 */
1876 U64(0x98E7E9CC, 0xCFBD7DBD), U64(0x8038D51C, 0xB897789C), /* ~= 10^299 */
1877 U64(0xBF21E440, 0x03ACDD2C), U64(0xE0470A63, 0xE6BD56C3), /* ~= 10^300 */
1878 U64(0xEEEA5D50, 0x04981478), U64(0x1858CCFC, 0xE06CAC74), /* ~= 10^301 */
1879 U64(0x95527A52, 0x02DF0CCB), U64(0x0F37801E, 0x0C43EBC8), /* ~= 10^302 */
1880 U64(0xBAA718E6, 0x8396CFFD), U64(0xD3056025, 0x8F54E6BA), /* ~= 10^303 */
1881 U64(0xE950DF20, 0x247C83FD), U64(0x47C6B82E, 0xF32A2069), /* ~= 10^304 */
1882 U64(0x91D28B74, 0x16CDD27E), U64(0x4CDC331D, 0x57FA5441), /* ~= 10^305 */
1883 U64(0xB6472E51, 0x1C81471D), U64(0xE0133FE4, 0xADF8E952), /* ~= 10^306 */
1884 U64(0xE3D8F9E5, 0x63A198E5), U64(0x58180FDD, 0xD97723A6), /* ~= 10^307 */
1885 U64(0x8E679C2F, 0x5E44FF8F), U64(0x570F09EA, 0xA7EA7648), /* ~= 10^308 */
1886 U64(0xB201833B, 0x35D63F73), U64(0x2CD2CC65, 0x51E513DA), /* ~= 10^309 */
1887 U64(0xDE81E40A, 0x034BCF4F), U64(0xF8077F7E, 0xA65E58D1), /* ~= 10^310 */
1888 U64(0x8B112E86, 0x420F6191), U64(0xFB04AFAF, 0x27FAF782), /* ~= 10^311 */
1889 U64(0xADD57A27, 0xD29339F6), U64(0x79C5DB9A, 0xF1F9B563), /* ~= 10^312 */
1890 U64(0xD94AD8B1, 0xC7380874), U64(0x18375281, 0xAE7822BC), /* ~= 10^313 */
1891 U64(0x87CEC76F, 0x1C830548), U64(0x8F229391, 0x0D0B15B5), /* ~= 10^314 */
1892 U64(0xA9C2794A, 0xE3A3C69A), U64(0xB2EB3875, 0x504DDB22), /* ~= 10^315 */
1893 U64(0xD433179D, 0x9C8CB841), U64(0x5FA60692, 0xA46151EB), /* ~= 10^316 */
1894 U64(0x849FEEC2, 0x81D7F328), U64(0xDBC7C41B, 0xA6BCD333), /* ~= 10^317 */
1895 U64(0xA5C7EA73, 0x224DEFF3), U64(0x12B9B522, 0x906C0800), /* ~= 10^318 */
1896 U64(0xCF39E50F, 0xEAE16BEF), U64(0xD768226B, 0x34870A00), /* ~= 10^319 */
1897 U64(0x81842F29, 0xF2CCE375), U64(0xE6A11583, 0x00D46640), /* ~= 10^320 */
1898 U64(0xA1E53AF4, 0x6F801C53), U64(0x60495AE3, 0xC1097FD0), /* ~= 10^321 */
1899 U64(0xCA5E89B1, 0x8B602368), U64(0x385BB19C, 0xB14BDFC4), /* ~= 10^322 */
1900 U64(0xFCF62C1D, 0xEE382C42), U64(0x46729E03, 0xDD9ED7B5), /* ~= 10^323 */
1901 U64(0x9E19DB92, 0xB4E31BA9), U64(0x6C07A2C2, 0x6A8346D1) /* ~= 10^324 */
1902};
1903
1904/**
1905 Get the cached pow10 value from `pow10_sig_table`.
1906 @param exp10 The exponent of pow(10, e). This value must in range
1907 `POW10_SIG_TABLE_MIN_EXP` to `POW10_SIG_TABLE_MAX_EXP`.
1908 @param hi The highest 64 bits of pow(10, e).
1909 @param lo The lower 64 bits after `hi`.
1910 */
1911static_inline void pow10_table_get_sig(i32 exp10, u64 *hi, u64 *lo) {
1912 i32 idx = exp10 - (POW10_SIG_TABLE_MIN_EXP);
1913 *hi = pow10_sig_table[idx * 2];
1914 *lo = pow10_sig_table[idx * 2 + 1];
1915}
1916
1917/**
1918 Get the exponent (base 2) for highest 64 bits significand in `pow10_sig_table`.
1919 */
1920static_inline void pow10_table_get_exp(i32 exp10, i32 *exp2) {
1921 /* e2 = floor(log2(pow(10, e))) - 64 + 1 */
1922 /* = floor(e * log2(10) - 63) */
1923 *exp2 = (exp10 * 217706 - 4128768) >> 16;
1924}
1925
1926#endif
1927
1928
1929
1930/*==============================================================================
1931 * MARK: - Number and Bit Utils (Private)
1932 *============================================================================*/
1933
1934/** Convert bits to double. */
1935static_inline f64 f64_from_bits(u64 u) {
1936 f64 f;
1937 memcpy(&f, &u, sizeof(u));
1938 return f;
1939}
1940
1941/** Convert double to bits. */
1942static_inline u64 f64_to_bits(f64 f) {
1943 u64 u;
1944 memcpy(&u, &f, sizeof(u));
1945 return u;
1946}
1947
1948/** Convert double to bits. */
1949static_inline u32 f32_to_bits(f32 f) {
1950 u32 u;
1951 memcpy(&u, &f, sizeof(u));
1952 return u;
1953}
1954
1955/** Get 'infinity' bits with sign. */
1956static_inline u64 f64_bits_inf(bool sign) {
1957#if YYJSON_HAS_IEEE_754
1958 return F64_BITS_INF | ((u64)sign << 63);
1959#elif defined(INFINITY)
1960 return f64_to_bits(sign ? -INFINITY : INFINITY);
1961#else
1962 return f64_to_bits(sign ? -HUGE_VAL : HUGE_VAL);
1963#endif
1964}
1965
1966/** Get 'nan' bits with sign. */
1967static_inline u64 f64_bits_nan(bool sign) {
1968#if YYJSON_HAS_IEEE_754
1969 return F64_BITS_NAN | ((u64)sign << 63);
1970#elif defined(NAN)
1971 return f64_to_bits(sign ? (f64)-NAN : (f64)NAN);
1972#else
1973 return f64_to_bits((sign ? -0.0 : 0.0) / 0.0);
1974#endif
1975}
1976
1977/** Casting double to float, allow overflow. */
1978#if yyjson_has_attribute(no_sanitize)
1979__attribute__((no_sanitize("undefined")))
1980#elif yyjson_gcc_available(4, 9, 0)
1981__attribute__((__no_sanitize_undefined__))
1982#endif
1983static_inline f32 f64_to_f32(f64 val) {
1984 return (f32)val;
1985}
1986
1987/** Returns the number of leading 0-bits in value (input should not be 0). */
1988static_inline u32 u64_lz_bits(u64 v) {
1989#if GCC_HAS_CLZLL
1990 return (u32)__builtin_clzll(v);
1991#elif MSC_HAS_BIT_SCAN_64
1992 unsigned long r;
1993 _BitScanReverse64(&r, v);
1994 return (u32)63 - (u32)r;
1995#elif MSC_HAS_BIT_SCAN
1996 unsigned long hi, lo;
1997 bool hi_set = _BitScanReverse(&hi, (u32)(v >> 32)) != 0;
1998 _BitScanReverse(&lo, (u32)v);
1999 hi |= 32;
2000 return (u32)63 - (u32)(hi_set ? hi : lo);
2001#else
2002 /* branchless, use De Bruijn sequence */
2003 /* see: https://www.chessprogramming.org/BitScan */
2004 const u8 table[64] = {
2005 63, 16, 62, 7, 15, 36, 61, 3, 6, 14, 22, 26, 35, 47, 60, 2,
2006 9, 5, 28, 11, 13, 21, 42, 19, 25, 31, 34, 40, 46, 52, 59, 1,
2007 17, 8, 37, 4, 23, 27, 48, 10, 29, 12, 43, 20, 32, 41, 53, 18,
2008 38, 24, 49, 30, 44, 33, 54, 39, 50, 45, 55, 51, 56, 57, 58, 0
2009 };
2010 v |= v >> 1;
2011 v |= v >> 2;
2012 v |= v >> 4;
2013 v |= v >> 8;
2014 v |= v >> 16;
2015 v |= v >> 32;
2016 return table[(v * U64(0x03F79D71, 0xB4CB0A89)) >> 58];
2017#endif
2018}
2019
2020/** Returns the number of trailing 0-bits in value (input should not be 0). */
2021static_inline u32 u64_tz_bits(u64 v) {
2022#if GCC_HAS_CTZLL
2023 return (u32)__builtin_ctzll(v);
2024#elif MSC_HAS_BIT_SCAN_64
2025 unsigned long r;
2026 _BitScanForward64(&r, v);
2027 return (u32)r;
2028#elif MSC_HAS_BIT_SCAN
2029 unsigned long lo, hi;
2030 bool lo_set = _BitScanForward(&lo, (u32)(v)) != 0;
2031 _BitScanForward(&hi, (u32)(v >> 32));
2032 hi += 32;
2033 return lo_set ? lo : hi;
2034#else
2035 /* branchless, use De Bruijn sequence */
2036 /* see: https://www.chessprogramming.org/BitScan */
2037 const u8 table[64] = {
2038 0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
2039 62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
2040 63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
2041 51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12
2042 };
2043 return table[((v & (~v + 1)) * U64(0x022FDD63, 0xCC95386D)) >> 58];
2044#endif
2045}
2046
2047/** Multiplies two 64-bit unsigned integers (a * b),
2048 returns the 128-bit result as 'hi' and 'lo'. */
2049static_inline void u128_mul(u64 a, u64 b, u64 *hi, u64 *lo) {
2050#if YYJSON_HAS_INT128
2051 u128 m = (u128)a * b;
2052 *hi = (u64)(m >> 64);
2053 *lo = (u64)(m);
2054#elif MSC_HAS_UMUL128
2055 *lo = _umul128(a, b, hi);
2056#else
2057 u32 a0 = (u32)(a), a1 = (u32)(a >> 32);
2058 u32 b0 = (u32)(b), b1 = (u32)(b >> 32);
2059 u64 p00 = (u64)a0 * b0, p01 = (u64)a0 * b1;
2060 u64 p10 = (u64)a1 * b0, p11 = (u64)a1 * b1;
2061 u64 m0 = p01 + (p00 >> 32);
2062 u32 m00 = (u32)(m0), m01 = (u32)(m0 >> 32);
2063 u64 m1 = p10 + m00;
2064 u32 m10 = (u32)(m1), m11 = (u32)(m1 >> 32);
2065 *hi = p11 + m01 + m11;
2066 *lo = ((u64)m10 << 32) | (u32)p00;
2067#endif
2068}
2069
2070/** Multiplies two 64-bit unsigned integers and add a value (a * b + c),
2071 returns the 128-bit result as 'hi' and 'lo'. */
2072static_inline void u128_mul_add(u64 a, u64 b, u64 c, u64 *hi, u64 *lo) {
2073#if YYJSON_HAS_INT128
2074 u128 m = (u128)a * b + c;
2075 *hi = (u64)(m >> 64);
2076 *lo = (u64)(m);
2077#else
2078 u64 h, l, t;
2079 u128_mul(a, b, &h, &l);
2080 t = l + c;
2081 h += (u64)(((t < l) | (t < c)));
2082 *hi = h;
2083 *lo = t;
2084#endif
2085}
2086
2087
2088
2089/*==============================================================================
2090 * MARK: - File Utils (Private)
2091 * These functions are used to read and write JSON files.
2092 *============================================================================*/
2093
2094#define YYJSON_FOPEN_E
2095#if !defined(_MSC_VER) && defined(__GLIBC__) && defined(__GLIBC_PREREQ)
2096# if __GLIBC_PREREQ(2, 7)
2097# undef YYJSON_FOPEN_E
2098# define YYJSON_FOPEN_E "e" /* glibc extension to enable O_CLOEXEC */
2099# endif
2100#endif
2101
2102static_inline FILE *fopen_safe(const char *path, const char *mode) {
2103#if YYJSON_MSC_VER >= 1400
2104 FILE *file = NULL;
2105 if (fopen_s(&file, path, mode) != 0) return NULL;
2106 return file;
2107#else
2108 return fopen(path, mode);
2109#endif
2110}
2111
2112static_inline FILE *fopen_readonly(const char *path) {
2113 return fopen_safe(path, "rb" YYJSON_FOPEN_E);
2114}
2115
2116static_inline FILE *fopen_writeonly(const char *path) {
2117 return fopen_safe(path, "wb" YYJSON_FOPEN_E);
2118}
2119
2120static_inline usize fread_safe(void *buf, usize size, FILE *file) {
2121#if YYJSON_MSC_VER >= 1400
2122 return fread_s(buf, size, 1, size, file);
2123#else
2124 return fread(buf, 1, size, file);
2125#endif
2126}
2127
2128
2129
2130/*==============================================================================
2131 * MARK: - Size Utils (Private)
2132 * These functions are used for memory allocation.
2133 *============================================================================*/
2134
2135/** Returns whether the size is overflow after increment. */
2136static_inline bool size_add_is_overflow(usize size, usize add) {
2137 return size > (size + add);
2138}
2139
2140/** Returns whether the size is power of 2 (size should not be 0). */
2141static_inline bool size_is_pow2(usize size) {
2142 return (size & (size - 1)) == 0;
2143}
2144
2145/** Align size upwards (may overflow). */
2146static_inline usize size_align_up(usize size, usize align) {
2147 if (size_is_pow2(align)) {
2148 return (size + (align - 1)) & ~(align - 1);
2149 } else {
2150 return size + align - (size + align - 1) % align - 1;
2151 }
2152}
2153
2154/** Align size downwards. */
2155static_inline usize size_align_down(usize size, usize align) {
2156 if (size_is_pow2(align)) {
2157 return size & ~(align - 1);
2158 } else {
2159 return size - (size % align);
2160 }
2161}
2162
2163/** Align address upwards (may overflow). */
2164static_inline void *mem_align_up(void *mem, usize align) {
2165 usize size;
2166 memcpy(&size, &mem, sizeof(usize));
2167 size = size_align_up(size, align);
2168 memcpy(&mem, &size, sizeof(usize));
2169 return mem;
2170}
2171
2172
2173
2174/*==============================================================================
2175 * MARK: - Default Memory Allocator (Private)
2176 * This is a simple libc memory allocator wrapper.
2177 *============================================================================*/
2178
2179static void *default_malloc(void *ctx, usize size) {
2180 return malloc(size);
2181}
2182
2183static void *default_realloc(void *ctx, void *ptr, usize old_size, usize size) {
2184 return realloc(ptr, size);
2185}
2186
2187static void default_free(void *ctx, void *ptr) {
2188 free(ptr);
2189}
2190
2191static const yyjson_alc YYJSON_DEFAULT_ALC = {
2192 default_malloc, default_realloc, default_free, NULL
2193};
2194
2195
2196
2197/*==============================================================================
2198 * MARK: - Null Memory Allocator (Private)
2199 * This allocator is just a placeholder to ensure that the internal
2200 * malloc/realloc/free function pointers are not null.
2201 *============================================================================*/
2202
2203static void *null_malloc(void *ctx, usize size) {
2204 return NULL;
2205}
2206
2207static void *null_realloc(void *ctx, void *ptr, usize old_size, usize size) {
2208 return NULL;
2209}
2210
2211static void null_free(void *ctx, void *ptr) {
2212 return;
2213}
2214
2215static const yyjson_alc YYJSON_NULL_ALC = {
2216 null_malloc, null_realloc, null_free, NULL
2217};
2218
2219
2220
2221/*==============================================================================
2222 * MARK: - Pool Memory Allocator (Public)
2223 * This allocator is initialized with a fixed-size buffer.
2224 * The buffer is split into multiple memory chunks for memory allocation.
2225 *============================================================================*/
2226
2227/** memory chunk header */
2228typedef struct pool_chunk {
2229 usize size; /* chunk memory size, include chunk header */
2230 struct pool_chunk *next; /* linked list, nullable */
2231 /* char mem[]; flexible array member */
2232} pool_chunk;
2233
2234/** allocator ctx header */
2235typedef struct pool_ctx {
2236 usize size; /* total memory size, include ctx header */
2237 pool_chunk *free_list; /* linked list, nullable */
2238 /* pool_chunk chunks[]; flexible array member */
2239} pool_ctx;
2240
2241/** align up the input size to chunk size */
2242static_inline void pool_size_align(usize *size) {
2243 *size = size_align_up(*size, sizeof(pool_chunk)) + sizeof(pool_chunk);
2244}
2245
2246static void *pool_malloc(void *ctx_ptr, usize size) {
2247 /* assert(size != 0) */
2248 pool_ctx *ctx = (pool_ctx *)ctx_ptr;
2249 pool_chunk *next, *prev = NULL, *cur = ctx->free_list;
2250
2251 if (unlikely(size >= ctx->size)) return NULL;
2252 pool_size_align(&size);
2253
2254 while (cur) {
2255 if (cur->size < size) {
2256 /* not enough space, try next chunk */
2257 prev = cur;
2258 cur = cur->next;
2259 continue;
2260 }
2261 if (cur->size >= size + sizeof(pool_chunk) * 2) {
2262 /* too much space, split this chunk */
2263 next = (pool_chunk *)(void *)((u8 *)cur + size);
2264 next->size = cur->size - size;
2265 next->next = cur->next;
2266 cur->size = size;
2267 } else {
2268 /* just enough space, use whole chunk */
2269 next = cur->next;
2270 }
2271 if (prev) prev->next = next;
2272 else ctx->free_list = next;
2273 return (void *)(cur + 1);
2274 }
2275 return NULL;
2276}
2277
2278static void pool_free(void *ctx_ptr, void *ptr) {
2279 /* assert(ptr != NULL) */
2280 pool_ctx *ctx = (pool_ctx *)ctx_ptr;
2281 pool_chunk *cur = ((pool_chunk *)ptr) - 1;
2282 pool_chunk *prev = NULL, *next = ctx->free_list;
2283
2284 while (next && next < cur) {
2285 prev = next;
2286 next = next->next;
2287 }
2288 if (prev) prev->next = cur;
2289 else ctx->free_list = cur;
2290 cur->next = next;
2291
2292 if (next && ((u8 *)cur + cur->size) == (u8 *)next) {
2293 /* merge cur to higher chunk */
2294 cur->size += next->size;
2295 cur->next = next->next;
2296 }
2297 if (prev && ((u8 *)prev + prev->size) == (u8 *)cur) {
2298 /* merge cur to lower chunk */
2299 prev->size += cur->size;
2300 prev->next = cur->next;
2301 }
2302}
2303
2304static void *pool_realloc(void *ctx_ptr, void *ptr,
2305 usize old_size, usize size) {
2306 /* assert(ptr != NULL && size != 0 && old_size < size) */
2307 pool_ctx *ctx = (pool_ctx *)ctx_ptr;
2308 pool_chunk *cur = ((pool_chunk *)ptr) - 1, *prev, *next, *tmp;
2309
2310 /* check size */
2311 if (unlikely(size >= ctx->size)) return NULL;
2312 pool_size_align(&old_size);
2313 pool_size_align(&size);
2314 if (unlikely(old_size == size)) return ptr;
2315
2316 /* find next and prev chunk */
2317 prev = NULL;
2318 next = ctx->free_list;
2319 while (next && next < cur) {
2320 prev = next;
2321 next = next->next;
2322 }
2323
2324 if ((u8 *)cur + cur->size == (u8 *)next && cur->size + next->size >= size) {
2325 /* merge to higher chunk if they are contiguous */
2326 usize free_size = cur->size + next->size - size;
2327 if (free_size > sizeof(pool_chunk) * 2) {
2328 tmp = (pool_chunk *)(void *)((u8 *)cur + size);
2329 if (prev) prev->next = tmp;
2330 else ctx->free_list = tmp;
2331 tmp->next = next->next;
2332 tmp->size = free_size;
2333 cur->size = size;
2334 } else {
2335 if (prev) prev->next = next->next;
2336 else ctx->free_list = next->next;
2337 cur->size += next->size;
2338 }
2339 return ptr;
2340 } else {
2341 /* fallback to malloc and memcpy */
2342 void *new_ptr = pool_malloc(ctx_ptr, size - sizeof(pool_chunk));
2343 if (new_ptr) {
2344 memcpy(new_ptr, ptr, cur->size - sizeof(pool_chunk));
2345 pool_free(ctx_ptr, ptr);
2346 }
2347 return new_ptr;
2348 }
2349}
2350
2351bool yyjson_alc_pool_init(yyjson_alc *alc, void *buf, usize size) {
2352 pool_chunk *chunk;
2353 pool_ctx *ctx;
2354
2355 if (unlikely(!alc)) return false;
2356 *alc = YYJSON_NULL_ALC;
2357 if (size < sizeof(pool_ctx) * 4) return false;
2358 ctx = (pool_ctx *)mem_align_up(buf, sizeof(pool_ctx));
2359 if (unlikely(!ctx)) return false;
2360 size -= (usize)((u8 *)ctx - (u8 *)buf);
2361 size = size_align_down(size, sizeof(pool_ctx));
2362
2363 chunk = (pool_chunk *)(ctx + 1);
2364 chunk->size = size - sizeof(pool_ctx);
2365 chunk->next = NULL;
2366 ctx->size = size;
2367 ctx->free_list = chunk;
2368
2369 alc->malloc = pool_malloc;
2370 alc->realloc = pool_realloc;
2371 alc->free = pool_free;
2372 alc->ctx = (void *)ctx;
2373 return true;
2374}
2375
2376
2377
2378/*==============================================================================
2379 * MARK: - Dynamic Memory Allocator (Public)
2380 * This allocator allocates memory on demand and does not immediately release
2381 * unused memory. Instead, it places the unused memory into a freelist for
2382 * potential reuse in the future. It is only when the entire allocator is
2383 * destroyed that all previously allocated memory is released at once.
2384 *============================================================================*/
2385
2386/** memory chunk header */
2387typedef struct dyn_chunk {
2388 usize size; /* chunk size, include header */
2389 struct dyn_chunk *next;
2390 /* char mem[]; flexible array member */
2391} dyn_chunk;
2392
2393/** allocator ctx header */
2394typedef struct {
2395 dyn_chunk free_list; /* dummy header, sorted from small to large */
2396 dyn_chunk used_list; /* dummy header */
2397} dyn_ctx;
2398
2399/** align up the input size to chunk size */
2400static_inline bool dyn_size_align(usize *size) {
2401 usize alc_size = *size + sizeof(dyn_chunk);
2402 alc_size = size_align_up(alc_size, YYJSON_ALC_DYN_MIN_SIZE);
2403 if (unlikely(alc_size < *size)) return false; /* overflow */
2404 *size = alc_size;
2405 return true;
2406}
2407
2408/** remove a chunk from list (the chunk must already be in the list) */
2409static_inline void dyn_chunk_list_remove(dyn_chunk *list, dyn_chunk *chunk) {
2410 dyn_chunk *prev = list, *cur;
2411 for (cur = prev->next; cur; cur = cur->next) {
2412 if (cur == chunk) {
2413 prev->next = cur->next;
2414 cur->next = NULL;
2415 return;
2416 }
2417 prev = cur;
2418 }
2419}
2420
2421/** add a chunk to list header (the chunk must not be in the list) */
2422static_inline void dyn_chunk_list_add(dyn_chunk *list, dyn_chunk *chunk) {
2423 chunk->next = list->next;
2424 list->next = chunk;
2425}
2426
2427static void *dyn_malloc(void *ctx_ptr, usize size) {
2428 /* assert(size != 0) */
2429 const yyjson_alc def = YYJSON_DEFAULT_ALC;
2430 dyn_ctx *ctx = (dyn_ctx *)ctx_ptr;
2431 dyn_chunk *chunk, *prev;
2432 if (unlikely(!dyn_size_align(&size))) return NULL;
2433
2434 /* freelist is empty, create new chunk */
2435 if (!ctx->free_list.next) {
2436 chunk = (dyn_chunk *)def.malloc(def.ctx, size);
2437 if (unlikely(!chunk)) return NULL;
2438 chunk->size = size;
2439 chunk->next = NULL;
2440 dyn_chunk_list_add(&ctx->used_list, chunk);
2441 return (void *)(chunk + 1);
2442 }
2443
2444 /* find a large enough chunk, or resize the largest chunk */
2445 prev = &ctx->free_list;
2446 while (true) {
2447 chunk = prev->next;
2448 if (chunk->size >= size) { /* enough size, reuse this chunk */
2449 prev->next = chunk->next;
2450 dyn_chunk_list_add(&ctx->used_list, chunk);
2451 return (void *)(chunk + 1);
2452 }
2453 if (!chunk->next) { /* resize the largest chunk */
2454 chunk = (dyn_chunk *)def.realloc(def.ctx, chunk, chunk->size, size);
2455 if (unlikely(!chunk)) return NULL;
2456 prev->next = NULL;
2457 chunk->size = size;
2458 dyn_chunk_list_add(&ctx->used_list, chunk);
2459 return (void *)(chunk + 1);
2460 }
2461 prev = chunk;
2462 }
2463}
2464
2465static void *dyn_realloc(void *ctx_ptr, void *ptr,
2466 usize old_size, usize size) {
2467 /* assert(ptr != NULL && size != 0 && old_size < size) */
2468 const yyjson_alc def = YYJSON_DEFAULT_ALC;
2469 dyn_ctx *ctx = (dyn_ctx *)ctx_ptr;
2470 dyn_chunk *new_chunk, *chunk = (dyn_chunk *)ptr - 1;
2471 if (unlikely(!dyn_size_align(&size))) return NULL;
2472 if (chunk->size >= size) return ptr;
2473
2474 dyn_chunk_list_remove(&ctx->used_list, chunk);
2475 new_chunk = (dyn_chunk *)def.realloc(def.ctx, chunk, chunk->size, size);
2476 if (likely(new_chunk)) {
2477 new_chunk->size = size;
2478 chunk = new_chunk;
2479 }
2480 dyn_chunk_list_add(&ctx->used_list, chunk);
2481 return new_chunk ? (void *)(new_chunk + 1) : NULL;
2482}
2483
2484static void dyn_free(void *ctx_ptr, void *ptr) {
2485 /* assert(ptr != NULL) */
2486 dyn_ctx *ctx = (dyn_ctx *)ctx_ptr;
2487 dyn_chunk *chunk = (dyn_chunk *)ptr - 1, *prev;
2488
2489 dyn_chunk_list_remove(&ctx->used_list, chunk);
2490 for (prev = &ctx->free_list; prev; prev = prev->next) {
2491 if (!prev->next || prev->next->size >= chunk->size) {
2492 chunk->next = prev->next;
2493 prev->next = chunk;
2494 break;
2495 }
2496 }
2497}
2498
2499yyjson_alc *yyjson_alc_dyn_new(void) {
2500 const yyjson_alc def = YYJSON_DEFAULT_ALC;
2501 usize hdr_len = sizeof(yyjson_alc) + sizeof(dyn_ctx);
2502 yyjson_alc *alc = (yyjson_alc *)def.malloc(def.ctx, hdr_len);
2503 dyn_ctx *ctx = (dyn_ctx *)(void *)(alc + 1);
2504 if (unlikely(!alc)) return NULL;
2505 alc->malloc = dyn_malloc;
2506 alc->realloc = dyn_realloc;
2507 alc->free = dyn_free;
2508 alc->ctx = alc + 1;
2509 memset(ctx, 0, sizeof(*ctx));
2510 return alc;
2511}
2512
2513void yyjson_alc_dyn_free(yyjson_alc *alc) {
2514 const yyjson_alc def = YYJSON_DEFAULT_ALC;
2515 dyn_ctx *ctx = (dyn_ctx *)(void *)(alc + 1);
2516 dyn_chunk *chunk, *next;
2517 if (unlikely(!alc)) return;
2518 for (chunk = ctx->free_list.next; chunk; chunk = next) {
2519 next = chunk->next;
2520 def.free(def.ctx, chunk);
2521 }
2522 for (chunk = ctx->used_list.next; chunk; chunk = next) {
2523 next = chunk->next;
2524 def.free(def.ctx, chunk);
2525 }
2526 def.free(def.ctx, alc);
2527}
2528
2529
2530
2531/*==============================================================================
2532 * MARK: - JSON Struct Utils (Public)
2533 * These functions are used for creating, copying, releasing, and comparing
2534 * JSON documents and values. They are widely used throughout this library.
2535 *============================================================================*/
2536
2537static_inline void unsafe_yyjson_str_pool_release(yyjson_str_pool *pool,
2538 yyjson_alc *alc) {
2539 yyjson_str_chunk *chunk = pool->chunks, *next;
2540 while (chunk) {
2541 next = chunk->next;
2542 alc->free(alc->ctx, chunk);
2543 chunk = next;
2544 }
2545}
2546
2547static_inline void unsafe_yyjson_val_pool_release(yyjson_val_pool *pool,
2548 yyjson_alc *alc) {
2549 yyjson_val_chunk *chunk = pool->chunks, *next;
2550 while (chunk) {
2551 next = chunk->next;
2552 alc->free(alc->ctx, chunk);
2553 chunk = next;
2554 }
2555}
2556
2557bool unsafe_yyjson_str_pool_grow(yyjson_str_pool *pool,
2558 const yyjson_alc *alc, usize len) {
2559 yyjson_str_chunk *chunk;
2560 usize size, max_len;
2561
2562 /* create a new chunk */
2563 max_len = USIZE_MAX - sizeof(yyjson_str_chunk);
2564 if (unlikely(len > max_len)) return false;
2565 size = len + sizeof(yyjson_str_chunk);
2566 size = yyjson_max(pool->chunk_size, size);
2567 chunk = (yyjson_str_chunk *)alc->malloc(alc->ctx, size);
2568 if (unlikely(!chunk)) return false;
2569
2570 /* insert the new chunk as the head of the linked list */
2571 chunk->next = pool->chunks;
2572 chunk->chunk_size = size;
2573 pool->chunks = chunk;
2574 pool->cur = (char *)chunk + sizeof(yyjson_str_chunk);
2575 pool->end = (char *)chunk + size;
2576
2577 /* the next chunk is twice the size of the current one */
2578 size = yyjson_min(pool->chunk_size * 2, pool->chunk_size_max);
2579 if (size < pool->chunk_size) size = pool->chunk_size_max; /* overflow */
2580 pool->chunk_size = size;
2581 return true;
2582}
2583
2584bool unsafe_yyjson_val_pool_grow(yyjson_val_pool *pool,
2585 const yyjson_alc *alc, usize count) {
2586 yyjson_val_chunk *chunk;
2587 usize size, max_count;
2588
2589 /* create a new chunk */
2590 max_count = USIZE_MAX / sizeof(yyjson_mut_val) - 1;
2591 if (unlikely(count > max_count)) return false;
2592 size = (count + 1) * sizeof(yyjson_mut_val);
2593 size = yyjson_max(pool->chunk_size, size);
2594 chunk = (yyjson_val_chunk *)alc->malloc(alc->ctx, size);
2595 if (unlikely(!chunk)) return false;
2596
2597 /* insert the new chunk as the head of the linked list */
2598 chunk->next = pool->chunks;
2599 chunk->chunk_size = size;
2600 pool->chunks = chunk;
2601 pool->cur = (yyjson_mut_val *)(void *)((u8 *)chunk) + 1;
2602 pool->end = (yyjson_mut_val *)(void *)((u8 *)chunk + size);
2603
2604 /* the next chunk is twice the size of the current one */
2605 size = yyjson_min(pool->chunk_size * 2, pool->chunk_size_max);
2606 if (size < pool->chunk_size) size = pool->chunk_size_max; /* overflow */
2607 pool->chunk_size = size;
2608 return true;
2609}
2610
2611bool yyjson_mut_doc_set_str_pool_size(yyjson_mut_doc *doc, size_t len) {
2612 usize max_size = USIZE_MAX - sizeof(yyjson_str_chunk);
2613 if (!doc || !len || len > max_size) return false;
2614 doc->str_pool.chunk_size = len + sizeof(yyjson_str_chunk);
2615 return true;
2616}
2617
2618bool yyjson_mut_doc_set_val_pool_size(yyjson_mut_doc *doc, size_t count) {
2619 usize max_count = USIZE_MAX / sizeof(yyjson_mut_val) - 1;
2620 if (!doc || !count || count > max_count) return false;
2621 doc->val_pool.chunk_size = (count + 1) * sizeof(yyjson_mut_val);
2622 return true;
2623}
2624
2625void yyjson_mut_doc_free(yyjson_mut_doc *doc) {
2626 if (doc) {
2627 yyjson_alc alc = doc->alc;
2628 memset(&doc->alc, 0, sizeof(alc));
2629 unsafe_yyjson_str_pool_release(&doc->str_pool, &alc);
2630 unsafe_yyjson_val_pool_release(&doc->val_pool, &alc);
2631 alc.free(alc.ctx, doc);
2632 }
2633}
2634
2635yyjson_mut_doc *yyjson_mut_doc_new(const yyjson_alc *alc) {
2636 yyjson_mut_doc *doc;
2637 if (!alc) alc = &YYJSON_DEFAULT_ALC;
2638 doc = (yyjson_mut_doc *)alc->malloc(alc->ctx, sizeof(yyjson_mut_doc));
2639 if (!doc) return NULL;
2640 memset(doc, 0, sizeof(yyjson_mut_doc));
2641
2642 doc->alc = *alc;
2643 doc->str_pool.chunk_size = YYJSON_MUT_DOC_STR_POOL_INIT_SIZE;
2644 doc->str_pool.chunk_size_max = YYJSON_MUT_DOC_STR_POOL_MAX_SIZE;
2645 doc->val_pool.chunk_size = YYJSON_MUT_DOC_VAL_POOL_INIT_SIZE;
2646 doc->val_pool.chunk_size_max = YYJSON_MUT_DOC_VAL_POOL_MAX_SIZE;
2647 return doc;
2648}
2649
2650yyjson_mut_doc *yyjson_doc_mut_copy(yyjson_doc *doc, const yyjson_alc *alc) {
2651 yyjson_mut_doc *m_doc;
2652 yyjson_mut_val *m_val;
2653
2654 if (!doc || !doc->root) return NULL;
2655 m_doc = yyjson_mut_doc_new(alc);
2656 if (!m_doc) return NULL;
2657 m_val = yyjson_val_mut_copy(m_doc, doc->root);
2658 if (!m_val) {
2659 yyjson_mut_doc_free(m_doc);
2660 return NULL;
2661 }
2662 yyjson_mut_doc_set_root(m_doc, m_val);
2663 return m_doc;
2664}
2665
2666yyjson_mut_doc *yyjson_mut_doc_mut_copy(yyjson_mut_doc *doc,
2667 const yyjson_alc *alc) {
2668 yyjson_mut_doc *m_doc;
2669 yyjson_mut_val *m_val;
2670
2671 if (!doc) return NULL;
2672 if (!doc->root) return yyjson_mut_doc_new(alc);
2673
2674 m_doc = yyjson_mut_doc_new(alc);
2675 if (!m_doc) return NULL;
2676 m_val = yyjson_mut_val_mut_copy(m_doc, doc->root);
2677 if (!m_val) {
2678 yyjson_mut_doc_free(m_doc);
2679 return NULL;
2680 }
2681 yyjson_mut_doc_set_root(m_doc, m_val);
2682 return m_doc;
2683}
2684
2685yyjson_mut_val *yyjson_val_mut_copy(yyjson_mut_doc *m_doc,
2686 yyjson_val *i_vals) {
2687 /*
2688 The immutable object or array stores all sub-values in a contiguous memory,
2689 We copy them to another contiguous memory as mutable values,
2690 then reconnect the mutable values with the original relationship.
2691 */
2692 usize i_vals_len;
2693 yyjson_mut_val *m_vals, *m_val;
2694 yyjson_val *i_val, *i_end;
2695
2696 if (!m_doc || !i_vals) return NULL;
2697 i_end = unsafe_yyjson_get_next(i_vals);
2698 i_vals_len = (usize)(unsafe_yyjson_get_next(i_vals) - i_vals);
2699 m_vals = unsafe_yyjson_mut_val(m_doc, i_vals_len);
2700 if (!m_vals) return NULL;
2701 i_val = i_vals;
2702 m_val = m_vals;
2703
2704 for (; i_val < i_end; i_val++, m_val++) {
2705 yyjson_type type = unsafe_yyjson_get_type(i_val);
2706 m_val->tag = i_val->tag;
2707 m_val->uni.u64 = i_val->uni.u64;
2708 if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {
2709 const char *str = i_val->uni.str;
2710 usize str_len = unsafe_yyjson_get_len(i_val);
2711 m_val->uni.str = unsafe_yyjson_mut_strncpy(m_doc, str, str_len);
2712 if (!m_val->uni.str) return NULL;
2713 } else if (type == YYJSON_TYPE_ARR) {
2714 usize len = unsafe_yyjson_get_len(i_val);
2715 if (len > 0) {
2716 yyjson_val *ii_val = i_val + 1, *ii_next;
2717 yyjson_mut_val *mm_val = m_val + 1, *mm_ctn = m_val, *mm_next;
2718 while (len-- > 1) {
2719 ii_next = unsafe_yyjson_get_next(ii_val);
2720 mm_next = mm_val + (ii_next - ii_val);
2721 mm_val->next = mm_next;
2722 ii_val = ii_next;
2723 mm_val = mm_next;
2724 }
2725 mm_val->next = mm_ctn + 1;
2726 mm_ctn->uni.ptr = mm_val;
2727 }
2728 } else if (type == YYJSON_TYPE_OBJ) {
2729 usize len = unsafe_yyjson_get_len(i_val);
2730 if (len > 0) {
2731 yyjson_val *ii_key = i_val + 1, *ii_nextkey;
2732 yyjson_mut_val *mm_key = m_val + 1, *mm_ctn = m_val;
2733 yyjson_mut_val *mm_nextkey;
2734 while (len-- > 1) {
2735 ii_nextkey = unsafe_yyjson_get_next(ii_key + 1);
2736 mm_nextkey = mm_key + (ii_nextkey - ii_key);
2737 mm_key->next = mm_key + 1;
2738 mm_key->next->next = mm_nextkey;
2739 ii_key = ii_nextkey;
2740 mm_key = mm_nextkey;
2741 }
2742 mm_key->next = mm_key + 1;
2743 mm_key->next->next = mm_ctn + 1;
2744 mm_ctn->uni.ptr = mm_key;
2745 }
2746 }
2747 }
2748 return m_vals;
2749}
2750
2751static yyjson_mut_val *unsafe_yyjson_mut_val_mut_copy(yyjson_mut_doc *m_doc,
2752 yyjson_mut_val *m_vals) {
2753 /*
2754 The mutable object or array stores all sub-values in a circular linked
2755 list, so we can traverse them in the same loop. The traversal starts from
2756 the last item, continues with the first item in a list, and ends with the
2757 second to last item, which needs to be linked to the last item to close the
2758 circle.
2759 */
2760 yyjson_mut_val *m_val = unsafe_yyjson_mut_val(m_doc, 1);
2761 if (unlikely(!m_val)) return NULL;
2762 m_val->tag = m_vals->tag;
2763
2764 switch (unsafe_yyjson_get_type(m_vals)) {
2765 case YYJSON_TYPE_OBJ:
2766 case YYJSON_TYPE_ARR:
2767 if (unsafe_yyjson_get_len(m_vals) > 0) {
2768 yyjson_mut_val *last = (yyjson_mut_val *)m_vals->uni.ptr;
2769 yyjson_mut_val *next = last->next, *prev;
2770 prev = unsafe_yyjson_mut_val_mut_copy(m_doc, last);
2771 if (!prev) return NULL;
2772 m_val->uni.ptr = (void *)prev;
2773 while (next != last) {
2774 prev->next = unsafe_yyjson_mut_val_mut_copy(m_doc, next);
2775 if (!prev->next) return NULL;
2776 prev = prev->next;
2777 next = next->next;
2778 }
2779 prev->next = (yyjson_mut_val *)m_val->uni.ptr;
2780 }
2781 break;
2782 case YYJSON_TYPE_RAW:
2783 case YYJSON_TYPE_STR: {
2784 const char *str = m_vals->uni.str;
2785 usize str_len = unsafe_yyjson_get_len(m_vals);
2786 m_val->uni.str = unsafe_yyjson_mut_strncpy(m_doc, str, str_len);
2787 if (!m_val->uni.str) return NULL;
2788 break;
2789 }
2790 default:
2791 m_val->uni = m_vals->uni;
2792 break;
2793 }
2794 return m_val;
2795}
2796
2797yyjson_mut_val *yyjson_mut_val_mut_copy(yyjson_mut_doc *doc,
2798 yyjson_mut_val *val) {
2799 if (doc && val) return unsafe_yyjson_mut_val_mut_copy(doc, val);
2800 return NULL;
2801}
2802
2803/* Count the number of values and the total length of the strings. */
2804static void yyjson_mut_stat(yyjson_mut_val *val,
2805 usize *val_sum, usize *str_sum) {
2806 yyjson_type type = unsafe_yyjson_get_type(val);
2807 *val_sum += 1;
2808 if (type == YYJSON_TYPE_ARR || type == YYJSON_TYPE_OBJ) {
2809 yyjson_mut_val *child = (yyjson_mut_val *)val->uni.ptr;
2810 usize len = unsafe_yyjson_get_len(val), i;
2811 len <<= (u8)(type == YYJSON_TYPE_OBJ);
2812 *val_sum += len;
2813 for (i = 0; i < len; i++) {
2814 yyjson_type stype = unsafe_yyjson_get_type(child);
2815 if (stype == YYJSON_TYPE_STR || stype == YYJSON_TYPE_RAW) {
2816 *str_sum += unsafe_yyjson_get_len(child) + 1;
2817 } else if (stype == YYJSON_TYPE_ARR || stype == YYJSON_TYPE_OBJ) {
2818 yyjson_mut_stat(child, val_sum, str_sum);
2819 *val_sum -= 1;
2820 }
2821 child = child->next;
2822 }
2823 } else if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {
2824 *str_sum += unsafe_yyjson_get_len(val) + 1;
2825 }
2826}
2827
2828/* Copy mutable values to immutable value pool. */
2829static usize yyjson_imut_copy(yyjson_val **val_ptr, char **buf_ptr,
2830 yyjson_mut_val *mval) {
2831 yyjson_val *val = *val_ptr;
2832 yyjson_type type = unsafe_yyjson_get_type(mval);
2833 if (type == YYJSON_TYPE_ARR || type == YYJSON_TYPE_OBJ) {
2834 yyjson_mut_val *child = (yyjson_mut_val *)mval->uni.ptr;
2835 usize len = unsafe_yyjson_get_len(mval), i;
2836 usize val_sum = 1;
2837 if (type == YYJSON_TYPE_OBJ) {
2838 if (len) child = child->next->next;
2839 len <<= 1;
2840 } else {
2841 if (len) child = child->next;
2842 }
2843 *val_ptr = val + 1;
2844 for (i = 0; i < len; i++) {
2845 val_sum += yyjson_imut_copy(val_ptr, buf_ptr, child);
2846 child = child->next;
2847 }
2848 val->tag = mval->tag;
2849 val->uni.ofs = val_sum * sizeof(yyjson_val);
2850 return val_sum;
2851 } else if (type == YYJSON_TYPE_STR || type == YYJSON_TYPE_RAW) {
2852 char *buf = *buf_ptr;
2853 usize len = unsafe_yyjson_get_len(mval);
2854 memcpy((void *)buf, (const void *)mval->uni.str, len);
2855 buf[len] = '\0';
2856 val->tag = mval->tag;
2857 val->uni.str = buf;
2858 *val_ptr = val + 1;
2859 *buf_ptr = buf + len + 1;
2860 return 1;
2861 } else {
2862 val->tag = mval->tag;
2863 val->uni = mval->uni;
2864 *val_ptr = val + 1;
2865 return 1;
2866 }
2867}
2868
2869yyjson_doc *yyjson_mut_doc_imut_copy(yyjson_mut_doc *mdoc,
2870 const yyjson_alc *alc) {
2871 if (!mdoc) return NULL;
2872 return yyjson_mut_val_imut_copy(mdoc->root, alc);
2873}
2874
2875yyjson_doc *yyjson_mut_val_imut_copy(yyjson_mut_val *mval,
2876 const yyjson_alc *alc) {
2877 usize val_num = 0, str_sum = 0, hdr_size, buf_size;
2878 yyjson_doc *doc = NULL;
2879 yyjson_val *val_hdr = NULL;
2880
2881 /* This value should be NULL here. Setting a non-null value suppresses
2882 warning from the clang analyzer. */
2883 char *str_hdr = (char *)(void *)&str_sum;
2884 if (!mval) return NULL;
2885 if (!alc) alc = &YYJSON_DEFAULT_ALC;
2886
2887 /* traverse the input value to get pool size */
2888 yyjson_mut_stat(mval, &val_num, &str_sum);
2889
2890 /* create doc and val pool */
2891 hdr_size = size_align_up(sizeof(yyjson_doc), sizeof(yyjson_val));
2892 buf_size = hdr_size + val_num * sizeof(yyjson_val);
2893 doc = (yyjson_doc *)alc->malloc(alc->ctx, buf_size);
2894 if (!doc) return NULL;
2895 memset(doc, 0, sizeof(yyjson_doc));
2896 val_hdr = (yyjson_val *)(void *)((char *)(void *)doc + hdr_size);
2897 doc->root = val_hdr;
2898 doc->alc = *alc;
2899
2900 /* create str pool */
2901 if (str_sum > 0) {
2902 str_hdr = (char *)alc->malloc(alc->ctx, str_sum);
2903 doc->str_pool = str_hdr;
2904 if (!str_hdr) {
2905 alc->free(alc->ctx, (void *)doc);
2906 return NULL;
2907 }
2908 }
2909
2910 /* copy vals and strs */
2911 doc->val_read = yyjson_imut_copy(&val_hdr, &str_hdr, mval);
2912 doc->dat_read = str_sum + 1;
2913 return doc;
2914}
2915
2916static_inline bool unsafe_yyjson_num_equals(void *lhs, void *rhs) {
2917 yyjson_val_uni *luni = &((yyjson_val *)lhs)->uni;
2918 yyjson_val_uni *runi = &((yyjson_val *)rhs)->uni;
2919 yyjson_subtype lt = unsafe_yyjson_get_subtype(lhs);
2920 yyjson_subtype rt = unsafe_yyjson_get_subtype(rhs);
2921 if (lt == rt) return luni->u64 == runi->u64;
2922 if (lt == YYJSON_SUBTYPE_SINT && rt == YYJSON_SUBTYPE_UINT) {
2923 return luni->i64 >= 0 && luni->u64 == runi->u64;
2924 }
2925 if (lt == YYJSON_SUBTYPE_UINT && rt == YYJSON_SUBTYPE_SINT) {
2926 return runi->i64 >= 0 && luni->u64 == runi->u64;
2927 }
2928 return false;
2929}
2930
2931static_inline bool unsafe_yyjson_str_equals(void *lhs, void *rhs) {
2932 usize len = unsafe_yyjson_get_len(lhs);
2933 if (len != unsafe_yyjson_get_len(rhs)) return false;
2934 return !memcmp(unsafe_yyjson_get_str(lhs),
2935 unsafe_yyjson_get_str(rhs), len);
2936}
2937
2938bool unsafe_yyjson_equals(yyjson_val *lhs, yyjson_val *rhs) {
2939 yyjson_type type = unsafe_yyjson_get_type(lhs);
2940 if (type != unsafe_yyjson_get_type(rhs)) return false;
2941
2942 switch (type) {
2943 case YYJSON_TYPE_OBJ: {
2944 usize len = unsafe_yyjson_get_len(lhs);
2945 if (len != unsafe_yyjson_get_len(rhs)) return false;
2946 if (len > 0) {
2947 yyjson_obj_iter iter;
2948 yyjson_obj_iter_init(rhs, &iter);
2949 lhs = unsafe_yyjson_get_first(lhs);
2950 while (len-- > 0) {
2951 rhs = yyjson_obj_iter_getn(&iter, lhs->uni.str,
2952 unsafe_yyjson_get_len(lhs));
2953 if (!rhs) return false;
2954 if (!unsafe_yyjson_equals(lhs + 1, rhs)) return false;
2955 lhs = unsafe_yyjson_get_next(lhs + 1);
2956 }
2957 }
2958 /* yyjson allows duplicate keys, so the check may be inaccurate */
2959 return true;
2960 }
2961
2962 case YYJSON_TYPE_ARR: {
2963 usize len = unsafe_yyjson_get_len(lhs);
2964 if (len != unsafe_yyjson_get_len(rhs)) return false;
2965 if (len > 0) {
2966 lhs = unsafe_yyjson_get_first(lhs);
2967 rhs = unsafe_yyjson_get_first(rhs);
2968 while (len-- > 0) {
2969 if (!unsafe_yyjson_equals(lhs, rhs)) return false;
2970 lhs = unsafe_yyjson_get_next(lhs);
2971 rhs = unsafe_yyjson_get_next(rhs);
2972 }
2973 }
2974 return true;
2975 }
2976
2977 case YYJSON_TYPE_NUM:
2978 return unsafe_yyjson_num_equals(lhs, rhs);
2979
2980 case YYJSON_TYPE_RAW:
2981 case YYJSON_TYPE_STR:
2982 return unsafe_yyjson_str_equals(lhs, rhs);
2983
2984 case YYJSON_TYPE_NULL:
2985 case YYJSON_TYPE_BOOL:
2986 return lhs->tag == rhs->tag;
2987
2988 default:
2989 return false;
2990 }
2991}
2992
2993bool unsafe_yyjson_mut_equals(yyjson_mut_val *lhs, yyjson_mut_val *rhs) {
2994 yyjson_type type = unsafe_yyjson_get_type(lhs);
2995 if (type != unsafe_yyjson_get_type(rhs)) return false;
2996
2997 switch (type) {
2998 case YYJSON_TYPE_OBJ: {
2999 usize len = unsafe_yyjson_get_len(lhs);
3000 if (len != unsafe_yyjson_get_len(rhs)) return false;
3001 if (len > 0) {
3002 yyjson_mut_obj_iter iter;
3003 yyjson_mut_obj_iter_init(rhs, &iter);
3004 lhs = (yyjson_mut_val *)lhs->uni.ptr;
3005 while (len-- > 0) {
3006 rhs = yyjson_mut_obj_iter_getn(&iter, lhs->uni.str,
3007 unsafe_yyjson_get_len(lhs));
3008 if (!rhs) return false;
3009 if (!unsafe_yyjson_mut_equals(lhs->next, rhs)) return false;
3010 lhs = lhs->next->next;
3011 }
3012 }
3013 /* yyjson allows duplicate keys, so the check may be inaccurate */
3014 return true;
3015 }
3016
3017 case YYJSON_TYPE_ARR: {
3018 usize len = unsafe_yyjson_get_len(lhs);
3019 if (len != unsafe_yyjson_get_len(rhs)) return false;
3020 if (len > 0) {
3021 lhs = (yyjson_mut_val *)lhs->uni.ptr;
3022 rhs = (yyjson_mut_val *)rhs->uni.ptr;
3023 while (len-- > 0) {
3024 if (!unsafe_yyjson_mut_equals(lhs, rhs)) return false;
3025 lhs = lhs->next;
3026 rhs = rhs->next;
3027 }
3028 }
3029 return true;
3030 }
3031
3032 case YYJSON_TYPE_NUM:
3033 return unsafe_yyjson_num_equals(lhs, rhs);
3034
3035 case YYJSON_TYPE_RAW:
3036 case YYJSON_TYPE_STR:
3037 return unsafe_yyjson_str_equals(lhs, rhs);
3038
3039 case YYJSON_TYPE_NULL:
3040 case YYJSON_TYPE_BOOL:
3041 return lhs->tag == rhs->tag;
3042
3043 default:
3044 return false;
3045 }
3046}
3047
3048bool yyjson_locate_pos(const char *str, size_t len, size_t pos,
3049 size_t *line, size_t *col, size_t *chr) {
3050 usize line_sum = 0, line_pos = 0, chr_sum = 0;
3051 const u8 *cur = (const u8 *)str;
3052 const u8 *end = cur + pos;
3053
3054 if (!str || pos > len) {
3055 if (line) *line = 0;
3056 if (col) *col = 0;
3057 if (chr) *chr = 0;
3058 return false;
3059 }
3060
3061 if (pos >= 3 && is_utf8_bom(cur)) cur += 3; /* don't count BOM */
3062 while (cur < end) {
3063 u8 c = *cur;
3064 chr_sum += 1;
3065 if (likely(c < 0x80)) { /* 0xxxxxxx (0x00-0x7F) ASCII */
3066 if (c == '\n') {
3067 line_sum += 1;
3068 line_pos = chr_sum;
3069 }
3070 cur += 1;
3071 }
3072 else if (c < 0xC0) cur += 1; /* 10xxxxxx (0x80-0xBF) Invalid */
3073 else if (c < 0xE0) cur += 2; /* 110xxxxx (0xC0-0xDF) 2-byte UTF-8 */
3074 else if (c < 0xF0) cur += 3; /* 1110xxxx (0xE0-0xEF) 3-byte UTF-8 */
3075 else if (c < 0xF8) cur += 4; /* 11110xxx (0xF0-0xF7) 4-byte UTF-8 */
3076 else cur += 1; /* 11111xxx (0xF8-0xFF) Invalid */
3077 }
3078 if (line) *line = line_sum + 1;
3079 if (col) *col = chr_sum - line_pos + 1;
3080 if (chr) *chr = chr_sum;
3081 return true;
3082}
3083
3084
3085
3086#if !YYJSON_DISABLE_READER /* reader begin */
3087
3088/* Check read flag, avoids `always false` warning when disabled. */
3089#define has_flg(_flg) unlikely(has_rflag(flg, YYJSON_READ_##_flg, 0))
3090#define has_allow(_flg) unlikely(has_rflag(flg, YYJSON_READ_ALLOW_##_flg, 1))
3091#define YYJSON_READ_ALLOW_TRIVIA (YYJSON_READ_ALLOW_COMMENTS | \
3092 YYJSON_READ_ALLOW_EXT_WHITESPACE)
3093static_inline bool has_rflag(yyjson_read_flag flg, yyjson_read_flag chk,
3094 bool non_standard) {
3095#if YYJSON_DISABLE_NON_STANDARD
3096 if (non_standard) return false;
3097#endif
3098 return (flg & chk) != 0;
3099}
3100
3101
3102
3103/*==============================================================================
3104 * MARK: - JSON Reader Utils (Private)
3105 * These functions are used by JSON reader to read literals and comments.
3106 *============================================================================*/
3107
3108/** Read `true` literal, `*ptr[0]` should be `t`. */
3109static_inline bool read_true(u8 **ptr, yyjson_val *val) {
3110 u8 *cur = *ptr;
3111 if (likely(byte_match_4(cur, "true"))) {
3112 val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_TRUE;
3113 *ptr = cur + 4;
3114 return true;
3115 }
3116 return false;
3117}
3118
3119/** Read `false` literal, `*ptr[0]` should be `f`. */
3120static_inline bool read_false(u8 **ptr, yyjson_val *val) {
3121 u8 *cur = *ptr;
3122 if (likely(byte_match_4(cur + 1, "alse"))) {
3123 val->tag = YYJSON_TYPE_BOOL | YYJSON_SUBTYPE_FALSE;
3124 *ptr = cur + 5;
3125 return true;
3126 }
3127 return false;
3128}
3129
3130/** Read `null` literal, `*ptr[0]` should be `n`. */
3131static_inline bool read_null(u8 **ptr, yyjson_val *val) {
3132 u8 *cur = *ptr;
3133 if (likely(byte_match_4(cur, "null"))) {
3134 val->tag = YYJSON_TYPE_NULL;
3135 *ptr = cur + 4;
3136 return true;
3137 }
3138 return false;
3139}
3140
3141/** Read `Inf` or `Infinity` literal (ignoring case). */
3142static_inline bool read_inf(u8 **ptr, u8 **pre,
3143 yyjson_read_flag flg, yyjson_val *val) {
3144 u8 *hdr = *ptr;
3145 u8 *cur = *ptr;
3146 u8 **end = ptr;
3147 bool sign = (*cur == '-');
3148 if (*cur == '+' && !has_allow(EXT_NUMBER)) return false;
3149 cur += char_is_sign(*cur);
3150 if (char_to_lower(cur[0]) == 'i' &&
3151 char_to_lower(cur[1]) == 'n' &&
3152 char_to_lower(cur[2]) == 'f') {
3153 if (char_to_lower(cur[3]) == 'i') {
3154 if (char_to_lower(cur[4]) == 'n' &&
3155 char_to_lower(cur[5]) == 'i' &&
3156 char_to_lower(cur[6]) == 't' &&
3157 char_to_lower(cur[7]) == 'y') {
3158 cur += 8;
3159 } else {
3160 return false;
3161 }
3162 } else {
3163 cur += 3;
3164 }
3165 *end = cur;
3166 if (has_flg(NUMBER_AS_RAW)) {
3167 **pre = '\0'; /* add null-terminator for previous raw string */
3168 *pre = cur; /* save end position for current raw string */
3169 val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;
3170 val->uni.str = (const char *)hdr;
3171 } else {
3172 val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;
3173 val->uni.u64 = f64_bits_inf(sign);
3174 }
3175 return true;
3176 }
3177 return false;
3178}
3179
3180/** Read `NaN` literal (ignoring case). */
3181static_inline bool read_nan(u8 **ptr, u8 **pre,
3182 yyjson_read_flag flg, yyjson_val *val) {
3183 u8 *hdr = *ptr;
3184 u8 *cur = *ptr;
3185 u8 **end = ptr;
3186 bool sign = (*cur == '-');
3187 if (*cur == '+' && !has_allow(EXT_NUMBER)) return false;
3188 cur += char_is_sign(*cur);
3189 if (char_to_lower(cur[0]) == 'n' &&
3190 char_to_lower(cur[1]) == 'a' &&
3191 char_to_lower(cur[2]) == 'n') {
3192 cur += 3;
3193 *end = cur;
3194 if (has_flg(NUMBER_AS_RAW)) {
3195 **pre = '\0'; /* add null-terminator for previous raw string */
3196 *pre = cur; /* save end position for current raw string */
3197 val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;
3198 val->uni.str = (const char *)hdr;
3199 } else {
3200 val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;
3201 val->uni.u64 = f64_bits_nan(sign);
3202 }
3203 return true;
3204 }
3205 return false;
3206}
3207
3208/** Read `Inf`, `Infinity` or `NaN` literal (ignoring case). */
3209static_inline bool read_inf_or_nan(u8 **ptr, u8 **pre,
3210 yyjson_read_flag flg, yyjson_val *val) {
3211 if (read_inf(ptr, pre, flg, val)) return true;
3212 if (read_nan(ptr, pre, flg, val)) return true;
3213 return false;
3214}
3215
3216/** Read a JSON number as raw string. */
3217static_noinline bool read_num_raw(u8 **ptr, u8 **pre, yyjson_read_flag flg,
3218 yyjson_val *val, const char **msg) {
3219#define return_err(_pos, _msg) do { \
3220 *msg = _msg; *end = _pos; return false; \
3221} while (false)
3222
3223#define return_raw() do { \
3224 val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW; \
3225 val->uni.str = (const char *)hdr; \
3226 **pre = '\0'; *pre = cur; *end = cur; return true; \
3227} while (false)
3228
3229 u8 *hdr = *ptr;
3230 u8 *cur = *ptr;
3231 u8 **end = ptr;
3232
3233 /* skip sign */
3234 cur += (*cur == '-');
3235
3236 /* read first digit, check leading zero */
3237 while (unlikely(!char_is_digit(*cur))) {
3238 if (has_allow(EXT_NUMBER)) {
3239 if (*cur == '+' && cur == hdr) { /* leading `+` sign */
3240 cur++;
3241 continue;
3242 }
3243 if (*cur == '.' && char_is_digit(cur[1])) { /* e.g. '.123' */
3244 goto read_double;
3245 }
3246 }
3247 if (has_allow(INF_AND_NAN)) {
3248 if (read_inf_or_nan(ptr, pre, flg, val)) return true;
3249 }
3250 return_err(cur, "no digit after sign");
3251 }
3252
3253 /* read integral part */
3254 if (*cur == '0') {
3255 cur++;
3256 if (unlikely(char_is_digit(*cur))) {
3257 return_err(cur - 1, "number with leading zero is not allowed");
3258 }
3259 if (!char_is_fp(*cur)) {
3260 if (has_allow(EXT_NUMBER) && char_to_lower(*cur) == 'x') { /* hex */
3261 if (!char_is_hex(*++cur)) return_err(cur, "invalid hex number");
3262 while(char_is_hex(*cur)) cur++;
3263 }
3264 return_raw();
3265 }
3266 } else {
3267 while (char_is_digit(*cur)) cur++;
3268 if (!char_is_fp(*cur)) return_raw();
3269 }
3270
3271read_double:
3272 /* read fraction part */
3273 if (*cur == '.') {
3274 cur++;
3275 if (!char_is_digit(*cur)) {
3276 if (has_allow(EXT_NUMBER)) {
3277 if (!char_is_exp(*cur)) return_raw();
3278 } else {
3279 return_err(cur, "no digit after decimal point");
3280 }
3281 }
3282 while (char_is_digit(*cur)) cur++;
3283 }
3284
3285 /* read exponent part */
3286 if (char_is_exp(*cur)) {
3287 cur += 1 + char_is_sign(cur[1]);
3288 if (!char_is_digit(*cur++)) {
3289 return_err(cur, "no digit after exponent sign");
3290 }
3291 while (char_is_digit(*cur)) cur++;
3292 }
3293
3294 return_raw();
3295
3296#undef return_err
3297#undef return_raw
3298}
3299
3300/** Read a hex number. */
3301static_noinline bool read_num_hex(u8 **ptr, u8 **pre, yyjson_read_flag flg,
3302 yyjson_val *val, const char **msg) {
3303 u8 *hdr = *ptr;
3304 u8 *cur = *ptr;
3305 u8 **end = ptr;
3306 u64 sig = 0, i = 0;
3307 bool sign;
3308
3309 /* skip sign and '0x' */
3310 sign = (*cur == '-');
3311 cur += (*cur == '-' || *cur == '+') + 2;
3312
3313 /* read hex */
3314 for(; i < 16; i++) {
3315 u8 c = hex_conv_table[cur[i]];
3316 if (c == 0xF0) break;
3317 sig <<= 4;
3318 sig |= c;
3319 }
3320
3321 /* check error */
3322 if (unlikely(i == 0)) {
3323 *msg = "invalid hex number";
3324 return false;
3325 }
3326
3327 /* check overflow */
3328 if (unlikely(i == 16)) {
3329 if (char_is_hex(cur[16]) || (sign && sig > ((u64)1 << 63))) {
3330 if (!has_flg(BIGNUM_AS_RAW)) {
3331 *msg = "hex number overflow";
3332 return false;
3333 }
3334 cur += 16;
3335 while (char_is_hex(*cur)) cur++;
3336 **pre = '\0';
3337 val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW;
3338 val->uni.str = (const char *)hdr;
3339 *pre = cur; *end = cur;
3340 return true;
3341 }
3342 }
3343
3344 val->tag = YYJSON_TYPE_NUM | (u64)((u8)sign << 3);
3345 val->uni.u64 = (u64)(sign ? (u64)(~(sig) + 1) : (u64)(sig));
3346 *end = cur + i;
3347 return true;
3348}
3349
3350/**
3351 Skip trivia (whitespace and comments).
3352 This function should be used only when `char_is_trivia()` returns true.
3353 @param ptr (inout) Input current position, output end position.
3354 @param eof JSON end position.
3355 @param flg JSON read flags.
3356 @return true if at least one character was skipped.
3357 false if no characters were skipped,
3358 or if a multi-line comment is unterminated;
3359 in the latter case, `ptr` will be set to `eof`.
3360 */
3361static_noinline bool skip_trivia(u8 **ptr, u8 *eof, yyjson_read_flag flg) {
3362 u8 *hdr = *ptr, *cur = *ptr;
3363 usize len;
3364
3365 while (cur < eof) {
3366 u8 *loop_begin = cur;
3367
3368 /* skip standard whitespace */
3369 while(char_is_space(*cur)) cur++;
3370
3371 /* skip extended whitespace */
3372 if (has_allow(EXT_WHITESPACE)) {
3373 while (char_is_space_ext(*cur)) {
3374 cur += (len = ext_space_len(cur));
3375 if (!len) break;
3376 }
3377 }
3378
3379 /* skip comment, do not validate encoding */
3380 if (has_allow(COMMENTS) && cur[0] == '/') {
3381 if (cur[1] == '/') { /* single-line comment */
3382 cur += 2;
3383 if (has_allow(EXT_WHITESPACE)) {
3384 while (cur < eof) {
3385 if (char_is_eol_ext(*cur)) {
3386 cur += (len = ext_eol_len(cur));
3387 if (len) break;
3388 }
3389 cur++;
3390 }
3391 } else {
3392 while (cur < eof && !char_is_eol(*cur)) cur++;
3393 }
3394 } else if (cur[1] == '*') { /* multi-line comment */
3395 cur += 2;
3396 while (!byte_match_2(cur, "*/") && cur < eof) cur++;
3397 if (cur == eof) {
3398 *ptr = eof;
3399 return false; /* unclosed comment */
3400 }
3401 cur += 2;
3402 }
3403 }
3404 if (cur == loop_begin) break;
3405 }
3406 *ptr = cur;
3407 return cur > hdr;
3408}
3409
3410/**
3411 Check truncated UTF-8 character.
3412 Return true if `cur` starts a valid UTF-8 sequence that is truncated.
3413 */
3414static bool is_truncated_utf8(u8 *cur, u8 *eof) {
3415 u8 c0, c1, c2;
3416 usize len = (usize)(eof - cur);
3417 if (cur >= eof || len >= 4) return false;
3418 c0 = cur[0]; c1 = cur[1]; c2 = cur[2];
3419 /* 1-byte UTF-8, not truncated */
3420 if (c0 < 0x80) return false;
3421 if (len == 1) {
3422 /* 2-byte UTF-8, truncated */
3423 if ((c0 & 0xE0) == 0xC0 && (c0 & 0x1E) != 0x00) return true;
3424 /* 3-byte UTF-8, truncated */
3425 if ((c0 & 0xF0) == 0xE0) return true;
3426 /* 4-byte UTF-8, truncated */
3427 if ((c0 & 0xF8) == 0xF0 && (c0 & 0x07) <= 0x04) return true;
3428 } else if (len == 2) {
3429 /* 3-byte UTF-8, truncated */
3430 if ((c0 & 0xF0) == 0xE0 && (c1 & 0xC0) == 0x80) {
3431 u8 t = (u8)(((c0 & 0x0F) << 1) | ((c1 & 0x20) >> 5));
3432 return 0x01 <= t && t != 0x1B;
3433 }
3434 /* 4-byte UTF-8, truncated */
3435 if ((c0 & 0xF8) == 0xF0 && (c1 & 0xC0) == 0x80) {
3436 u8 t = (u8)(((c0 & 0x07) << 2) | ((c1 & 0x30) >> 4));
3437 return 0x01 <= t && t <= 0x10;
3438 }
3439 } else if (len == 3) {
3440 /* 4 bytes UTF-8, truncated */
3441 if ((c0 & 0xF8) == 0xF0 && (c1 & 0xC0) == 0x80 && (c2 & 0xC0) == 0x80) {
3442 u8 t = (u8)(((c0 & 0x07) << 2) | ((c1 & 0x30) >> 4));
3443 return 0x01 <= t && t <= 0x10;
3444 }
3445 }
3446 return false;
3447}
3448
3449/**
3450 Check truncated string.
3451 Returns true if `cur` match `str` but is truncated.
3452 The `str` should be lowercase ASCII letters.
3453 */
3454static bool is_truncated_str(u8 *cur, u8 *eof, const char *str,
3455 bool case_sensitive) {
3456 usize len = strlen(str);
3457 if (cur + len <= eof || eof <= cur) return false;
3458 if (case_sensitive) {
3459 return memcmp(cur, str, (usize)(eof - cur)) == 0;
3460 }
3461 for (; cur < eof; cur++, str++) {
3462 if (char_to_lower(*cur) != *(const u8 *)str) return false;
3463 }
3464 return true;
3465}
3466
3467/**
3468 Check truncated JSON on parsing errors.
3469 Returns true if the input is valid but truncated.
3470 */
3471static_noinline bool is_truncated_end(u8 *hdr, u8 *cur, u8 *eof,
3472 yyjson_read_code code,
3473 yyjson_read_flag flg) {
3474 if (cur >= eof) return true;
3475 if (code == YYJSON_READ_ERROR_LITERAL) {
3476 if (is_truncated_str(cur, eof, "true", true) ||
3477 is_truncated_str(cur, eof, "false", true) ||
3478 is_truncated_str(cur, eof, "null", true)) {
3479 return true;
3480 }
3481 }
3482 if (code == YYJSON_READ_ERROR_UNEXPECTED_CHARACTER ||
3483 code == YYJSON_READ_ERROR_INVALID_NUMBER ||
3484 code == YYJSON_READ_ERROR_LITERAL) {
3485 if (has_allow(INF_AND_NAN)) {
3486 if (*cur == '-') cur++;
3487 if (is_truncated_str(cur, eof, "infinity", false) ||
3488 is_truncated_str(cur, eof, "nan", false)) {
3489 return true;
3490 }
3491 }
3492 }
3493 if (code == YYJSON_READ_ERROR_UNEXPECTED_CONTENT) {
3494 if (has_allow(INF_AND_NAN)) {
3495 if (hdr + 3 <= cur &&
3496 is_truncated_str(cur - 3, eof, "infinity", false)) {
3497 return true; /* e.g. infin would be read as inf + in */
3498 }
3499 }
3500 }
3501 if (code == YYJSON_READ_ERROR_INVALID_STRING) {
3502 usize len = (usize)(eof - cur);
3503
3504 /* unicode escape sequence */
3505 if (*cur == '\\') {
3506 if (len == 1) return true;
3507 if (len <= 5) {
3508 if (*++cur != 'u') return false;
3509 for (++cur; cur < eof; cur++) {
3510 if (!char_is_hex(*cur)) return false;
3511 }
3512 return true;
3513 } else if (len <= 11) {
3514 /* incomplete surrogate pair? */
3515 u16 hi;
3516 if (*++cur != 'u') return false;
3517 if (!hex_load_4(++cur, &hi)) return false;
3518 if ((hi & 0xF800) != 0xD800) return false;
3519 cur += 4;
3520 if (cur >= eof) return true;
3521 /* valid low surrogate is DC00...DFFF */
3522 if (*cur != '\\') return false;
3523 if (++cur >= eof) return true;
3524 if (*cur != 'u') return false;
3525 if (++cur >= eof) return true;
3526 if (*cur != 'd' && *cur != 'D') return false;
3527 if (++cur >= eof) return true;
3528 if ((*cur < 'c' || *cur > 'f') && (*cur < 'C' || *cur > 'F'))
3529 return false;
3530 if (++cur >= eof) return true;
3531 if (!char_is_hex(*cur)) return false;
3532 return true;
3533 }
3534 return false;
3535 }
3536
3537 /* 2 to 4 bytes UTF-8 */
3538 if (is_truncated_utf8(cur, eof)) {
3539 return true;
3540 }
3541 }
3542 if (has_allow(COMMENTS)) {
3543 if (code == YYJSON_READ_ERROR_INVALID_COMMENT) {
3544 /* unclosed multiline comment */
3545 return true;
3546 }
3547 if (code == YYJSON_READ_ERROR_UNEXPECTED_CHARACTER &&
3548 *cur == '/' && cur + 1 == eof) {
3549 /* truncated beginning of comment */
3550 return true;
3551 }
3552 }
3553 if (code == YYJSON_READ_ERROR_UNEXPECTED_CHARACTER &&
3554 has_allow(BOM)) {
3555 /* truncated UTF-8 BOM */
3556 usize len = (usize)(eof - cur);
3557 if (cur == hdr && len < 3 && !memcmp(hdr, "\xEF\xBB\xBF", len)) {
3558 return true;
3559 }
3560 }
3561 return false;
3562}
3563
3564
3565
3566#if !YYJSON_DISABLE_FAST_FP_CONV /* FP_READER */
3567
3568/*==============================================================================
3569 * MARK: - BigInt For Floating Point Number Reader (Private)
3570 *
3571 * The bigint algorithm is used by floating-point number reader to get correctly
3572 * rounded result for numbers with lots of digits. This part of code is rarely
3573 * used for common numbers.
3574 *============================================================================*/
3575
3576/** Unsigned arbitrarily large integer */
3577typedef struct bigint {
3578 u32 used; /* used chunks count, should not be 0 */
3579 u64 bits[64]; /* chunks (58 is enough here) */
3580} bigint;
3581
3582/**
3583 Evaluate 'big += val'.
3584 @param big A big number (can be 0).
3585 @param val An unsigned integer (can be 0).
3586 */
3587static_inline void bigint_add_u64(bigint *big, u64 val) {
3588 u32 idx, max;
3589 u64 num = big->bits[0];
3590 u64 add = num + val;
3591 big->bits[0] = add;
3592 if (likely((add >= num) || (add >= val))) return;
3593 for ((void)(idx = 1), max = big->used; idx < max; idx++) {
3594 if (likely(big->bits[idx] != U64_MAX)) {
3595 big->bits[idx] += 1;
3596 return;
3597 }
3598 big->bits[idx] = 0;
3599 }
3600 big->bits[big->used++] = 1;
3601}
3602
3603/**
3604 Evaluate 'big *= val'.
3605 @param big A big number (can be 0).
3606 @param val An unsigned integer (cannot be 0).
3607 */
3608static_inline void bigint_mul_u64(bigint *big, u64 val) {
3609 u32 idx = 0, max = big->used;
3610 u64 hi, lo, carry = 0;
3611 for (; idx < max; idx++) {
3612 if (big->bits[idx]) break;
3613 }
3614 for (; idx < max; idx++) {
3615 u128_mul_add(big->bits[idx], val, carry, &hi, &lo);
3616 big->bits[idx] = lo;
3617 carry = hi;
3618 }
3619 if (carry) big->bits[big->used++] = carry;
3620}
3621
3622/**
3623 Evaluate 'big *= 2^exp'.
3624 @param big A big number (can be 0).
3625 @param exp An exponent integer (can be 0).
3626 */
3627static_inline void bigint_mul_pow2(bigint *big, u32 exp) {
3628 u32 shft = exp % 64;
3629 u32 move = exp / 64;
3630 u32 idx = big->used;
3631 if (unlikely(shft == 0)) {
3632 for (; idx > 0; idx--) {
3633 big->bits[idx + move - 1] = big->bits[idx - 1];
3634 }
3635 big->used += move;
3636 while (move) big->bits[--move] = 0;
3637 } else {
3638 big->bits[idx] = 0;
3639 for (; idx > 0; idx--) {
3640 u64 num = big->bits[idx] << shft;
3641 num |= big->bits[idx - 1] >> (64 - shft);
3642 big->bits[idx + move] = num;
3643 }
3644 big->bits[move] = big->bits[0] << shft;
3645 big->used += move + (big->bits[big->used + move] > 0);
3646 while (move) big->bits[--move] = 0;
3647 }
3648}
3649
3650/**
3651 Evaluate 'big *= 10^exp'.
3652 @param big A big number (can be 0).
3653 @param exp An exponent integer (cannot be 0).
3654 */
3655static_inline void bigint_mul_pow10(bigint *big, i32 exp) {
3656 for (; exp >= U64_POW10_MAX_EXACT_EXP; exp -= U64_POW10_MAX_EXACT_EXP) {
3657 bigint_mul_u64(big, u64_pow10_table[U64_POW10_MAX_EXACT_EXP]);
3658 }
3659 if (exp) {
3660 bigint_mul_u64(big, u64_pow10_table[exp]);
3661 }
3662}
3663
3664/**
3665 Compare two bigint.
3666 @return -1 if 'a < b', +1 if 'a > b', 0 if 'a == b'.
3667 */
3668static_inline i32 bigint_cmp(bigint *a, bigint *b) {
3669 u32 idx = a->used;
3670 if (a->used < b->used) return -1;
3671 if (a->used > b->used) return +1;
3672 while (idx-- > 0) {
3673 u64 av = a->bits[idx];
3674 u64 bv = b->bits[idx];
3675 if (av < bv) return -1;
3676 if (av > bv) return +1;
3677 }
3678 return 0;
3679}
3680
3681/**
3682 Evaluate 'big = val'.
3683 @param big A big number (can be 0).
3684 @param val An unsigned integer (can be 0).
3685 */
3686static_inline void bigint_set_u64(bigint *big, u64 val) {
3687 big->used = 1;
3688 big->bits[0] = val;
3689}
3690
3691/** Set a bigint with floating point number string. */
3692static_noinline void bigint_set_buf(bigint *big, u64 sig, i32 *exp,
3693 u8 *sig_cut, u8 *sig_end, u8 *dot_pos) {
3694
3695 if (unlikely(!sig_cut)) {
3696 /* no digit cut, set significant part only */
3697 bigint_set_u64(big, sig);
3698 return;
3699
3700 } else {
3701 /* some digits were cut, read them from 'sig_cut' to 'sig_end' */
3702 u8 *hdr = sig_cut;
3703 u8 *cur = hdr;
3704 u32 len = 0;
3705 u64 val = 0;
3706 bool dig_big_cut = false;
3707 bool has_dot = (hdr < dot_pos) & (dot_pos < sig_end);
3708 u32 dig_len_total = U64_SAFE_DIG + (u32)(sig_end - hdr) - has_dot;
3709
3710 sig -= (*sig_cut >= '5'); /* sig was rounded before */
3711 if (dig_len_total > F64_MAX_DEC_DIG) {
3712 dig_big_cut = true;
3713 sig_end -= dig_len_total - (F64_MAX_DEC_DIG + 1);
3714 sig_end -= (dot_pos + 1 == sig_end);
3715 dig_len_total = (F64_MAX_DEC_DIG + 1);
3716 }
3717 *exp -= (i32)dig_len_total - U64_SAFE_DIG;
3718
3719 big->used = 1;
3720 big->bits[0] = sig;
3721 while (cur < sig_end) {
3722 if (likely(cur != dot_pos)) {
3723 val = val * 10 + (u8)(*cur++ - '0');
3724 len++;
3725 if (unlikely(cur == sig_end && dig_big_cut)) {
3726 /* The last digit must be non-zero, */
3727 /* set it to '1' for correct rounding. */
3728 val = val - (val % 10) + 1;
3729 }
3730 if (len == U64_SAFE_DIG || cur == sig_end) {
3731 bigint_mul_pow10(big, (i32)len);
3732 bigint_add_u64(big, val);
3733 val = 0;
3734 len = 0;
3735 }
3736 } else {
3737 cur++;
3738 }
3739 }
3740 }
3741}
3742
3743
3744
3745/*==============================================================================
3746 * MARK: - Diy Floating Point (Private)
3747 *============================================================================*/
3748
3749/** "Do It Yourself Floating Point" struct. */
3750typedef struct diy_fp {
3751 u64 sig; /* significand */
3752 i32 exp; /* exponent, base 2 */
3753 i32 pad; /* padding, useless */
3754} diy_fp;
3755
3756/** Get cached rounded diy_fp with pow(10, e) The input value must in range
3757 [POW10_SIG_TABLE_MIN_EXP, POW10_SIG_TABLE_MAX_EXP]. */
3758static_inline diy_fp diy_fp_get_cached_pow10(i32 exp10) {
3759 diy_fp fp;
3760 u64 sig_ext;
3761 pow10_table_get_sig(exp10, &fp.sig, &sig_ext);
3762 pow10_table_get_exp(exp10, &fp.exp);
3763 fp.sig += (sig_ext >> 63);
3764 return fp;
3765}
3766
3767/** Returns fp * fp2. */
3768static_inline diy_fp diy_fp_mul(diy_fp fp, diy_fp fp2) {
3769 u64 hi, lo;
3770 u128_mul(fp.sig, fp2.sig, &hi, &lo);
3771 fp.sig = hi + (lo >> 63);
3772 fp.exp += fp2.exp + 64;
3773 return fp;
3774}
3775
3776/** Convert diy_fp to IEEE-754 raw value. */
3777static_inline u64 diy_fp_to_ieee_raw(diy_fp fp) {
3778 u64 sig = fp.sig;
3779 i32 exp = fp.exp;
3780 u32 lz_bits;
3781 if (unlikely(fp.sig == 0)) return 0;
3782
3783 lz_bits = u64_lz_bits(sig);
3784 sig <<= lz_bits;
3785 sig >>= F64_BITS - F64_SIG_FULL_BITS;
3786 exp -= (i32)lz_bits;
3787 exp += F64_BITS - F64_SIG_FULL_BITS;
3788 exp += F64_SIG_BITS;
3789
3790 if (unlikely(exp >= F64_MAX_BIN_EXP)) {
3791 /* overflow */
3792 return F64_BITS_INF;
3793 } else if (likely(exp >= F64_MIN_BIN_EXP - 1)) {
3794 /* normal */
3795 exp += F64_EXP_BIAS;
3796 return ((u64)exp << F64_SIG_BITS) | (sig & F64_SIG_MASK);
3797 } else if (likely(exp >= F64_MIN_BIN_EXP - F64_SIG_FULL_BITS)) {
3798 /* subnormal */
3799 return sig >> (F64_MIN_BIN_EXP - exp - 1);
3800 } else {
3801 /* underflow */
3802 return 0;
3803 }
3804}
3805
3806
3807
3808/*==============================================================================
3809 * MARK: - Number Reader (Private)
3810 *============================================================================*/
3811
3812/**
3813 Read a JSON number.
3814
3815 1. This function assume that the floating-point number is in IEEE-754 format.
3816 2. This function support uint64/int64/double number. If an integer number
3817 cannot fit in uint64/int64, it will returns as a double number. If a double
3818 number is infinite, the return value is based on flag.
3819 3. This function (with inline attribute) may generate a lot of instructions.
3820 */
3821static_inline bool read_num(u8 **ptr, u8 **pre, yyjson_read_flag flg,
3822 yyjson_val *val, const char **msg) {
3823#define return_err(_pos, _msg) do { \
3824 *msg = _msg; \
3825 *end = _pos; \
3826 return false; \
3827} while (false)
3828
3829#define return_0() do { \
3830 val->tag = YYJSON_TYPE_NUM | (u8)((u8)sign << 3); \
3831 val->uni.u64 = 0; \
3832 *end = cur; return true; \
3833} while (false)
3834
3835#define return_i64(_v) do { \
3836 val->tag = YYJSON_TYPE_NUM | (u8)((u8)sign << 3); \
3837 val->uni.u64 = (u64)(sign ? (u64)(~(_v) + 1) : (u64)(_v)); \
3838 *end = cur; return true; \
3839} while (false)
3840
3841#define return_f64(_v) do { \
3842 val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
3843 val->uni.f64 = sign ? -(f64)(_v) : (f64)(_v); \
3844 *end = cur; return true; \
3845} while (false)
3846
3847#define return_f64_bin(_v) do { \
3848 val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
3849 val->uni.u64 = ((u64)sign << 63) | (u64)(_v); \
3850 *end = cur; return true; \
3851} while (false)
3852
3853#define return_inf() do { \
3854 if (has_flg(BIGNUM_AS_RAW)) return_raw(); \
3855 if (has_allow(INF_AND_NAN)) return_f64_bin(F64_BITS_INF); \
3856 else return_err(hdr, "number is infinity when parsed as double"); \
3857} while (false)
3858
3859#define return_raw() do { \
3860 **pre = '\0'; /* add null-terminator for previous raw string */ \
3861 val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW; \
3862 val->uni.str = (const char *)hdr; \
3863 *pre = cur; *end = cur; return true; \
3864} while (false)
3865
3866 u8 *sig_cut = NULL; /* significant part cutting position for long number */
3867 u8 *sig_end = NULL; /* significant part ending position */
3868 u8 *dot_pos = NULL; /* decimal point position */
3869
3870 u64 sig = 0; /* significant part of the number */
3871 i32 exp = 0; /* exponent part of the number */
3872
3873 bool exp_sign; /* temporary exponent sign from literal part */
3874 i64 exp_sig = 0; /* temporary exponent number from significant part */
3875 i64 exp_lit = 0; /* temporary exponent number from exponent literal part */
3876 u64 num; /* temporary number for reading */
3877 u8 *tmp; /* temporary cursor for reading */
3878
3879 u8 *hdr = *ptr;
3880 u8 *cur = *ptr;
3881 u8 **end = ptr;
3882 bool sign;
3883
3884 /* read number as raw string if has `YYJSON_READ_NUMBER_AS_RAW` flag */
3885 if (has_flg(NUMBER_AS_RAW)) {
3886 return read_num_raw(ptr, pre, flg, val, msg);
3887 }
3888
3889 sign = (*hdr == '-');
3890 cur += sign;
3891
3892 /* begin with a leading zero or non-digit */
3893 while (unlikely(!char_is_nonzero(*cur))) { /* 0 or non-digit char */
3894 if (unlikely(*cur != '0')) { /* non-digit char */
3895 if (has_allow(EXT_NUMBER)) {
3896 if (*cur == '+' && cur == hdr) { /* leading `+` sign */
3897 cur++;
3898 continue;
3899 }
3900 if (*cur == '.' && char_is_digit(cur[1])) { /* e.g. '.123' */
3901 goto leading_dot;
3902 }
3903 }
3904 if (has_allow(INF_AND_NAN)) {
3905 if (read_inf_or_nan(ptr, pre, flg, val)) return true;
3906 }
3907 return_err(cur, "no digit after sign");
3908 }
3909 /* begin with 0 */
3910 if (likely(!char_is_digit_or_fp(*++cur))) {
3911 if (has_allow(EXT_NUMBER) && char_to_lower(*cur) == 'x') { /* hex */
3912 return read_num_hex(ptr, pre, flg, val, msg);
3913 }
3914 return_0();
3915 }
3916 if (likely(*cur == '.')) {
3917leading_dot:
3918 dot_pos = cur++;
3919 if (unlikely(!char_is_digit(*cur))) {
3920 if (has_allow(EXT_NUMBER)) {
3921 if (char_is_exp(*cur)) {
3922 goto digi_exp_more;
3923 } else {
3924 return_f64_bin(0);
3925 }
3926 }
3927 return_err(cur, "no digit after decimal point");
3928 }
3929 while (unlikely(*cur == '0')) cur++;
3930 if (likely(char_is_digit(*cur))) {
3931 /* first non-zero digit after decimal point */
3932 sig = (u64)(*cur - '0'); /* read first digit */
3933 cur--;
3934 goto digi_frac_1; /* continue read fraction part */
3935 }
3936 }
3937 if (unlikely(char_is_digit(*cur))) {
3938 return_err(cur - 1, "number with leading zero is not allowed");
3939 }
3940 if (unlikely(char_is_exp(*cur))) { /* 0 with any exponent is still 0 */
3941 cur += (usize)1 + char_is_sign(cur[1]);
3942 if (unlikely(!char_is_digit(*cur))) {
3943 return_err(cur, "no digit after exponent sign");
3944 }
3945 while (char_is_digit(*++cur));
3946 }
3947 return_f64_bin(0);
3948 }
3949
3950 /* begin with non-zero digit */
3951 sig = (u64)(*cur - '0');
3952
3953 /*
3954 Read integral part, same as the following code.
3955
3956 for (int i = 1; i <= 18; i++) {
3957 num = cur[i] - '0';
3958 if (num <= 9) sig = num + sig * 10;
3959 else goto digi_sepr_i;
3960 }
3961 */
3962#define expr_intg(i) \
3963 if (likely((num = (u64)(cur[i] - (u8)'0')) <= 9)) sig = num + sig * 10; \
3964 else { goto digi_sepr_##i; }
3965 repeat_in_1_18(expr_intg)
3966#undef expr_intg
3967
3968
3969 cur += 19; /* skip continuous 19 digits */
3970 if (!char_is_digit_or_fp(*cur)) {
3971 /* this number is an integer consisting of 19 digits */
3972 if (sign && (sig > ((u64)1 << 63))) { /* overflow */
3973 if (has_flg(BIGNUM_AS_RAW)) return_raw();
3974 return_f64(unsafe_yyjson_u64_to_f64(sig));
3975 }
3976 return_i64(sig);
3977 }
3978 goto digi_intg_more; /* read more digits in integral part */
3979
3980
3981 /* process first non-digit character */
3982#define expr_sepr(i) \
3983 digi_sepr_##i: \
3984 if (likely(!char_is_fp(cur[i]))) { cur += i; return_i64(sig); } \
3985 dot_pos = cur + i; \
3986 if (likely(cur[i] == '.')) goto digi_frac_##i; \
3987 cur += i; sig_end = cur; goto digi_exp_more;
3988 repeat_in_1_18(expr_sepr)
3989#undef expr_sepr
3990
3991
3992 /* read fraction part */
3993#define expr_frac(i) \
3994 digi_frac_##i: \
3995 if (likely((num = (u64)(cur[i + 1] - (u8)'0')) <= 9)) \
3996 sig = num + sig * 10; \
3997 else { goto digi_stop_##i; }
3998 repeat_in_1_18(expr_frac)
3999#undef expr_frac
4000
4001 cur += 20; /* skip 19 digits and 1 decimal point */
4002 if (!char_is_digit(*cur)) goto digi_frac_end; /* fraction part end */
4003 goto digi_frac_more; /* read more digits in fraction part */
4004
4005
4006 /* significant part end */
4007#define expr_stop(i) \
4008 digi_stop_##i: \
4009 cur += i + 1; \
4010 goto digi_frac_end;
4011 repeat_in_1_18(expr_stop)
4012#undef expr_stop
4013
4014
4015 /* read more digits in integral part */
4016digi_intg_more:
4017 if (char_is_digit(*cur)) {
4018 if (!char_is_digit_or_fp(cur[1])) {
4019 /* this number is an integer consisting of 20 digits */
4020 num = (u64)(*cur - '0');
4021 if ((sig < (U64_MAX / 10)) ||
4022 (sig == (U64_MAX / 10) && num <= (U64_MAX % 10))) {
4023 sig = num + sig * 10;
4024 cur++;
4025 /* convert to double if overflow */
4026 if (sign) {
4027 if (has_flg(BIGNUM_AS_RAW)) return_raw();
4028 return_f64(unsafe_yyjson_u64_to_f64(sig));
4029 }
4030 return_i64(sig);
4031 }
4032 }
4033 }
4034
4035 if (char_is_exp(*cur)) {
4036 dot_pos = cur;
4037 goto digi_exp_more;
4038 }
4039
4040 if (*cur == '.') {
4041 dot_pos = cur++;
4042 if (unlikely(!char_is_digit(*cur))) {
4043 if (has_allow(EXT_NUMBER)) {
4044 goto digi_frac_end;
4045 }
4046 return_err(cur, "no digit after decimal point");
4047 }
4048 }
4049
4050
4051 /* read more digits in fraction part */
4052digi_frac_more:
4053 sig_cut = cur; /* too large to fit in u64, excess digits need to be cut */
4054 sig += (*cur >= '5'); /* round */
4055 while (char_is_digit(*++cur));
4056 if (!dot_pos) {
4057 if (!char_is_fp(*cur) && has_flg(BIGNUM_AS_RAW)) {
4058 return_raw(); /* it's a large integer */
4059 }
4060 dot_pos = cur;
4061 if (*cur == '.') {
4062 if (unlikely(!char_is_digit(*++cur))) {
4063 if (!has_allow(EXT_NUMBER)) {
4064 return_err(cur, "no digit after decimal point");
4065 }
4066 }
4067 while (char_is_digit(*cur)) cur++;
4068 }
4069 }
4070 exp_sig = (i64)(dot_pos - sig_cut);
4071 exp_sig += (dot_pos < sig_cut);
4072
4073 /* ignore trailing zeros */
4074 tmp = cur - 1;
4075 while ((*tmp == '0' || *tmp == '.') && tmp > hdr) tmp--;
4076 if (tmp < sig_cut) {
4077 sig_cut = NULL;
4078 } else {
4079 sig_end = cur;
4080 }
4081
4082 if (char_is_exp(*cur)) goto digi_exp_more;
4083 goto digi_exp_finish;
4084
4085
4086 /* fraction part end */
4087digi_frac_end:
4088 if (unlikely(dot_pos + 1 == cur)) {
4089 if (!has_allow(EXT_NUMBER)) {
4090 return_err(cur, "no digit after decimal point");
4091 }
4092 }
4093 sig_end = cur;
4094 exp_sig = -(i64)((u64)(cur - dot_pos) - 1);
4095 if (likely(!char_is_exp(*cur))) {
4096 if (unlikely(exp_sig < F64_MIN_DEC_EXP - 19)) {
4097 return_f64_bin(0); /* underflow */
4098 }
4099 exp = (i32)exp_sig;
4100 goto digi_finish;
4101 } else {
4102 goto digi_exp_more;
4103 }
4104
4105
4106 /* read exponent part */
4107digi_exp_more:
4108 exp_sign = (*++cur == '-');
4109 cur += char_is_sign(*cur);
4110 if (unlikely(!char_is_digit(*cur))) {
4111 return_err(cur, "no digit after exponent sign");
4112 }
4113 while (*cur == '0') cur++;
4114
4115 /* read exponent literal */
4116 tmp = cur;
4117 while (char_is_digit(*cur)) {
4118 exp_lit = (i64)((u8)(*cur++ - '0') + (u64)exp_lit * 10);
4119 }
4120 if (unlikely(cur - tmp >= U64_SAFE_DIG)) {
4121 if (exp_sign) {
4122 return_f64_bin(0); /* underflow */
4123 } else {
4124 return_inf(); /* overflow */
4125 }
4126 }
4127 exp_sig += exp_sign ? -exp_lit : exp_lit;
4128
4129
4130 /* validate exponent value */
4131digi_exp_finish:
4132 if (unlikely(exp_sig < F64_MIN_DEC_EXP - 19)) {
4133 return_f64_bin(0); /* underflow */
4134 }
4135 if (unlikely(exp_sig > F64_MAX_DEC_EXP)) {
4136 return_inf(); /* overflow */
4137 }
4138 exp = (i32)exp_sig;
4139
4140
4141 /* all digit read finished */
4142digi_finish:
4143
4144 /*
4145 Fast path 1:
4146
4147 1. The floating-point number calculation should be accurate, see the
4148 comments of macro `YYJSON_DOUBLE_MATH_CORRECT`.
4149 2. Correct rounding should be performed (fegetround() == FE_TONEAREST).
4150 3. The input of floating point number calculation does not lose precision,
4151 which means: 64 - leading_zero(input) - trailing_zero(input) < 53.
4152
4153 We don't check all available inputs here, because that would make the code
4154 more complicated, and not friendly to branch predictor.
4155 */
4156#if YYJSON_DOUBLE_MATH_CORRECT
4157 if (sig < ((u64)1 << 53) &&
4158 exp >= -F64_POW10_MAX_EXACT_EXP &&
4159 exp <= +F64_POW10_MAX_EXACT_EXP) {
4160 f64 dbl = (f64)sig;
4161 if (exp < 0) {
4162 dbl /= f64_pow10_table[-exp];
4163 } else {
4164 dbl *= f64_pow10_table[+exp];
4165 }
4166 return_f64(dbl);
4167 }
4168#endif
4169
4170 /*
4171 Fast path 2:
4172
4173 To keep it simple, we only accept normal number here,
4174 let the slow path to handle subnormal and infinity number.
4175 */
4176 if (likely(!sig_cut &&
4177 exp > -F64_MAX_DEC_EXP + 1 &&
4178 exp < +F64_MAX_DEC_EXP - 20)) {
4179 /*
4180 The result value is exactly equal to (sig * 10^exp),
4181 the exponent part (10^exp) can be converted to (sig2 * 2^exp2).
4182
4183 The sig2 can be an infinite length number, only the highest 128 bits
4184 is cached in the pow10_sig_table.
4185
4186 Now we have these bits:
4187 sig1 (normalized 64bit) : aaaaaaaa
4188 sig2 (higher 64bit) : bbbbbbbb
4189 sig2_ext (lower 64bit) : cccccccc
4190 sig2_cut (extra unknown bits) : dddddddddddd....
4191
4192 And the calculation process is:
4193 ----------------------------------------
4194 aaaaaaaa *
4195 bbbbbbbbccccccccdddddddddddd....
4196 ----------------------------------------
4197 abababababababab +
4198 acacacacacacacac +
4199 adadadadadadadadadad....
4200 ----------------------------------------
4201 [hi____][lo____] +
4202 [hi2___][lo2___] +
4203 [unknown___________....]
4204 ----------------------------------------
4205
4206 The addition with carry may affect higher bits, but if there is a 0
4207 in higher bits, the bits higher than 0 will not be affected.
4208
4209 `lo2` + `unknown` may get a carry bit and may affect `hi2`, the max
4210 value of `hi2` is 0xFFFFFFFFFFFFFFFE, so `hi2` will not overflow.
4211
4212 `lo` + `hi2` may also get a carry bit and may affect `hi`, but only
4213 the highest significant 53 bits of `hi` is needed. If there is a 0
4214 in the lower bits of `hi`, then all the following bits can be dropped.
4215
4216 To convert the result to IEEE-754 double number, we need to perform
4217 correct rounding:
4218 1. if bit 54 is 0, round down,
4219 2. if bit 54 is 1 and any bit beyond bit 54 is 1, round up,
4220 3. if bit 54 is 1 and all bits beyond bit 54 are 0, round to even,
4221 as the extra bits is unknown, this case will not be handled here.
4222 */
4223
4224 u64 raw;
4225 u64 sig1, sig2, sig2_ext, hi, lo, hi2, lo2, add, bits;
4226 i32 exp2;
4227 u32 lz;
4228 bool exact = false, carry, round_up;
4229
4230 /* convert (10^exp) to (sig2 * 2^exp2) */
4231 pow10_table_get_sig(exp, &sig2, &sig2_ext);
4232 pow10_table_get_exp(exp, &exp2);
4233
4234 /* normalize and multiply */
4235 lz = u64_lz_bits(sig);
4236 sig1 = sig << lz;
4237 exp2 -= (i32)lz;
4238 u128_mul(sig1, sig2, &hi, &lo);
4239
4240 /*
4241 The `hi` is in range [0x4000000000000000, 0xFFFFFFFFFFFFFFFE],
4242 To get normalized value, `hi` should be shifted to the left by 0 or 1.
4243
4244 The highest significant 53 bits is used by IEEE-754 double number,
4245 and the bit 54 is used to detect rounding direction.
4246
4247 The lowest (64 - 54 - 1) bits is used to check whether it contains 0.
4248 */
4249 bits = hi & (((u64)1 << (64 - 54 - 1)) - 1);
4250 if (bits - 1 < (((u64)1 << (64 - 54 - 1)) - 2)) {
4251 /*
4252 (bits != 0 && bits != 0x1FF) => (bits - 1 < 0x1FF - 1)
4253 The `bits` is not zero, so we don't need to check `round to even`
4254 case. The `bits` contains bit `0`, so we can drop the extra bits
4255 after `0`.
4256 */
4257 exact = true;
4258
4259 } else {
4260 /*
4261 (bits == 0 || bits == 0x1FF)
4262 The `bits` is filled with all `0` or all `1`, so we need to check
4263 lower bits with another 64-bit multiplication.
4264 */
4265 u128_mul(sig1, sig2_ext, &hi2, &lo2);
4266
4267 add = lo + hi2;
4268 if (add + 1 > (u64)1) {
4269 /*
4270 (add != 0 && add != U64_MAX) => (add + 1 > 1)
4271 The `add` is not zero, so we don't need to check `round to
4272 even` case. The `add` contains bit `0`, so we can drop the
4273 extra bits after `0`. The `hi` cannot be U64_MAX, so it will
4274 not overflow.
4275 */
4276 carry = add < lo || add < hi2;
4277 hi += carry;
4278 exact = true;
4279 }
4280 }
4281
4282 if (exact) {
4283 /* normalize */
4284 lz = hi < ((u64)1 << 63);
4285 hi <<= lz;
4286 exp2 -= (i32)lz;
4287 exp2 += 64;
4288
4289 /* test the bit 54 and get rounding direction */
4290 round_up = (hi & ((u64)1 << (64 - 54))) > (u64)0;
4291 hi += (round_up ? ((u64)1 << (64 - 54)) : (u64)0);
4292
4293 /* test overflow */
4294 if (hi < ((u64)1 << (64 - 54))) {
4295 hi = ((u64)1 << 63);
4296 exp2 += 1;
4297 }
4298
4299 /* This is a normal number, convert it to IEEE-754 format. */
4300 hi >>= F64_BITS - F64_SIG_FULL_BITS;
4301 exp2 += F64_BITS - F64_SIG_FULL_BITS + F64_SIG_BITS;
4302 exp2 += F64_EXP_BIAS;
4303 raw = ((u64)exp2 << F64_SIG_BITS) | (hi & F64_SIG_MASK);
4304 return_f64_bin(raw);
4305 }
4306 }
4307
4308 /*
4309 Slow path: read double number exactly with diyfp.
4310 1. Use cached diyfp to get an approximation value.
4311 2. Use bigcomp to check the approximation value if needed.
4312
4313 This algorithm refers to google's double-conversion project:
4314 https://github.com/google/double-conversion
4315 */
4316 {
4317 const i32 ERR_ULP_LOG = 3;
4318 const i32 ERR_ULP = 1 << ERR_ULP_LOG;
4319 const i32 ERR_CACHED_POW = ERR_ULP / 2;
4320 const i32 ERR_MUL_FIXED = ERR_ULP / 2;
4321 const i32 DIY_SIG_BITS = 64;
4322 const i32 EXP_BIAS = F64_EXP_BIAS + F64_SIG_BITS;
4323 const i32 EXP_SUBNORMAL = -EXP_BIAS + 1;
4324
4325 u64 fp_err;
4326 u32 bits;
4327 i32 order_of_magnitude;
4328 i32 effective_significand_size;
4329 i32 precision_digits_count;
4330 u64 precision_bits;
4331 u64 half_way;
4332
4333 u64 raw;
4334 diy_fp fp, fp_upper;
4335 bigint big_full, big_comp;
4336 i32 cmp;
4337
4338 fp.sig = sig;
4339 fp.exp = 0;
4340 fp_err = sig_cut ? (u64)(ERR_ULP / 2) : (u64)0;
4341
4342 /* normalize */
4343 bits = u64_lz_bits(fp.sig);
4344 fp.sig <<= bits;
4345 fp.exp -= (i32)bits;
4346 fp_err <<= bits;
4347
4348 /* multiply and add error */
4349 fp = diy_fp_mul(fp, diy_fp_get_cached_pow10(exp));
4350 fp_err += (u64)ERR_CACHED_POW + (fp_err != 0) + (u64)ERR_MUL_FIXED;
4351
4352 /* normalize */
4353 bits = u64_lz_bits(fp.sig);
4354 fp.sig <<= bits;
4355 fp.exp -= (i32)bits;
4356 fp_err <<= bits;
4357
4358 /* effective significand */
4359 order_of_magnitude = DIY_SIG_BITS + fp.exp;
4360 if (likely(order_of_magnitude >= EXP_SUBNORMAL + F64_SIG_FULL_BITS)) {
4361 effective_significand_size = F64_SIG_FULL_BITS;
4362 } else if (order_of_magnitude <= EXP_SUBNORMAL) {
4363 effective_significand_size = 0;
4364 } else {
4365 effective_significand_size = order_of_magnitude - EXP_SUBNORMAL;
4366 }
4367
4368 /* precision digits count */
4369 precision_digits_count = DIY_SIG_BITS - effective_significand_size;
4370 if (unlikely(precision_digits_count + ERR_ULP_LOG >= DIY_SIG_BITS)) {
4371 i32 shr = (precision_digits_count + ERR_ULP_LOG) - DIY_SIG_BITS + 1;
4372 fp.sig >>= shr;
4373 fp.exp += shr;
4374 fp_err = (fp_err >> shr) + 1 + (u32)ERR_ULP;
4375 precision_digits_count -= shr;
4376 }
4377
4378 /* half way */
4379 precision_bits = fp.sig & (((u64)1 << precision_digits_count) - 1);
4380 precision_bits *= (u32)ERR_ULP;
4381 half_way = (u64)1 << (precision_digits_count - 1);
4382 half_way *= (u32)ERR_ULP;
4383
4384 /* rounding */
4385 fp.sig >>= precision_digits_count;
4386 fp.sig += (precision_bits >= half_way + fp_err);
4387 fp.exp += precision_digits_count;
4388
4389 /* get IEEE double raw value */
4390 raw = diy_fp_to_ieee_raw(fp);
4391 if (unlikely(raw == F64_BITS_INF)) return_inf();
4392 if (likely(precision_bits <= half_way - fp_err ||
4393 precision_bits >= half_way + fp_err)) {
4394 return_f64_bin(raw); /* number is accurate */
4395 }
4396 /* now the number is the correct value, or the next lower value */
4397
4398 /* upper boundary */
4399 if (raw & F64_EXP_MASK) {
4400 fp_upper.sig = (raw & F64_SIG_MASK) + ((u64)1 << F64_SIG_BITS);
4401 fp_upper.exp = (i32)((raw & F64_EXP_MASK) >> F64_SIG_BITS);
4402 } else {
4403 fp_upper.sig = (raw & F64_SIG_MASK);
4404 fp_upper.exp = 1;
4405 }
4406 fp_upper.exp -= F64_EXP_BIAS + F64_SIG_BITS;
4407 fp_upper.sig <<= 1;
4408 fp_upper.exp -= 1;
4409 fp_upper.sig += 1; /* add half ulp */
4410
4411 /* compare with bigint */
4412 bigint_set_buf(&big_full, sig, &exp, sig_cut, sig_end, dot_pos);
4413 bigint_set_u64(&big_comp, fp_upper.sig);
4414 if (exp >= 0) {
4415 bigint_mul_pow10(&big_full, +exp);
4416 } else {
4417 bigint_mul_pow10(&big_comp, -exp);
4418 }
4419 if (fp_upper.exp > 0) {
4420 bigint_mul_pow2(&big_comp, (u32)+fp_upper.exp);
4421 } else {
4422 bigint_mul_pow2(&big_full, (u32)-fp_upper.exp);
4423 }
4424 cmp = bigint_cmp(&big_full, &big_comp);
4425 if (likely(cmp != 0)) {
4426 /* round down or round up */
4427 raw += (cmp > 0);
4428 } else {
4429 /* falls midway, round to even */
4430 raw += (raw & 1);
4431 }
4432
4433 if (unlikely(raw == F64_BITS_INF)) return_inf();
4434 return_f64_bin(raw);
4435 }
4436
4437#undef return_err
4438#undef return_inf
4439#undef return_0
4440#undef return_i64
4441#undef return_f64
4442#undef return_f64_bin
4443#undef return_raw
4444}
4445
4446
4447
4448#else /* FP_READER */
4449
4450/**
4451 Read a JSON number.
4452 This is a fallback function if the custom number reader is disabled.
4453 This function use libc's strtod() to read floating-point number.
4454 */
4455static_inline bool read_num(u8 **ptr, u8 **pre, yyjson_read_flag flg,
4456 yyjson_val *val, const char **msg) {
4457#define return_err(_pos, _msg) do { \
4458 *msg = _msg; \
4459 *end = _pos; \
4460 return false; \
4461} while (false)
4462
4463#define return_0() do { \
4464 val->tag = YYJSON_TYPE_NUM | (u64)((u8)sign << 3); \
4465 val->uni.u64 = 0; \
4466 *end = cur; return true; \
4467} while (false)
4468
4469#define return_i64(_v) do { \
4470 val->tag = YYJSON_TYPE_NUM | (u64)((u8)sign << 3); \
4471 val->uni.u64 = (u64)(sign ? (u64)(~(_v) + 1) : (u64)(_v)); \
4472 *end = cur; return true; \
4473} while (false)
4474
4475#define return_f64(_v) do { \
4476 val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
4477 val->uni.f64 = sign ? -(f64)(_v) : (f64)(_v); \
4478 *end = cur; return true; \
4479} while (false)
4480
4481#define return_f64_bin(_v) do { \
4482 val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL; \
4483 val->uni.u64 = ((u64)sign << 63) | (u64)(_v); \
4484 *end = cur; return true; \
4485} while (false)
4486
4487#define return_inf() do { \
4488 if (has_flg(BIGNUM_AS_RAW)) return_raw(); \
4489 if (has_allow(INF_AND_NAN)) return_f64_bin(F64_BITS_INF); \
4490 else return_err(hdr, "number is infinity when parsed as double"); \
4491} while (false)
4492
4493#define return_raw() do { \
4494 val->tag = ((u64)(cur - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_RAW; \
4495 val->uni.str = (const char *)hdr; \
4496 **pre = '\0'; *pre = cur; *end = cur; return true; \
4497} while (false)
4498
4499 u64 sig, num;
4500 u8 *hdr = *ptr;
4501 u8 *cur = *ptr;
4502 u8 **end = ptr;
4503 u8 *dot = NULL;
4504 u8 *f64_end = NULL;
4505 bool sign;
4506
4507 /* read number as raw string if has `YYJSON_READ_NUMBER_AS_RAW` flag */
4508 if (has_flg(NUMBER_AS_RAW)) {
4509 return read_num_raw(ptr, pre, flg, val, msg);
4510 }
4511
4512 sign = (*hdr == '-');
4513 cur += sign;
4514 sig = (u8)(*cur - '0');
4515
4516 /* read first digit, check leading zero */
4517 while (unlikely(!char_is_digit(*cur))) {
4518 if (has_allow(EXT_NUMBER)) {
4519 if (*cur == '+' && cur == hdr) { /* leading `+` sign */
4520 cur++;
4521 sig = (u8)(*cur - '0');
4522 continue;
4523 }
4524 if (*cur == '.' && char_is_num(cur[1])) { /* no integer part */
4525 goto read_double; /* e.g. '.123' */
4526 }
4527 }
4528 if (has_allow(INF_AND_NAN)) {
4529 if (read_inf_or_nan(ptr, pre, flg, val)) return true;
4530 }
4531 return_err(cur, "no digit after sign");
4532 }
4533 if (*cur == '0') {
4534 cur++;
4535 if (unlikely(char_is_digit(*cur))) {
4536 return_err(cur - 1, "number with leading zero is not allowed");
4537 }
4538 if (!char_is_fp(*cur)) {
4539 if (has_allow(EXT_NUMBER) &&
4540 (*cur == 'x' || *cur == 'X')) { /* hex integer */
4541 return read_num_hex(ptr, pre, flg, val, msg);
4542 }
4543 return_0();
4544 }
4545 goto read_double;
4546 }
4547
4548 /* read continuous digits, up to 19 characters */
4549#define expr_intg(i) \
4550 if (likely((num = (u64)(cur[i] - (u8)'0')) <= 9)) sig = num + sig * 10; \
4551 else { cur += i; goto intg_end; }
4552 repeat_in_1_18(expr_intg)
4553#undef expr_intg
4554
4555 /* here are 19 continuous digits, skip them */
4556 cur += 19;
4557 if (char_is_digit(cur[0]) && !char_is_digit_or_fp(cur[1])) {
4558 /* this number is an integer consisting of 20 digits */
4559 num = (u8)(*cur - '0');
4560 if ((sig < (U64_MAX / 10)) ||
4561 (sig == (U64_MAX / 10) && num <= (U64_MAX % 10))) {
4562 sig = num + sig * 10;
4563 cur++;
4564 if (sign) {
4565 if (has_flg(BIGNUM_AS_RAW)) return_raw();
4566 return_f64(unsafe_yyjson_u64_to_f64(sig));
4567 }
4568 return_i64(sig);
4569 }
4570 }
4571
4572intg_end:
4573 /* continuous digits ended */
4574 if (!char_is_digit_or_fp(*cur)) {
4575 /* this number is an integer consisting of 1 to 19 digits */
4576 if (sign && (sig > ((u64)1 << 63))) {
4577 if (has_flg(BIGNUM_AS_RAW)) return_raw();
4578 return_f64(unsafe_yyjson_u64_to_f64(sig));
4579 }
4580 return_i64(sig);
4581 }
4582
4583read_double:
4584 /* this number should be read as double */
4585 while (char_is_digit(*cur)) cur++;
4586 if (!char_is_fp(*cur) && has_flg(BIGNUM_AS_RAW)) {
4587 return_raw(); /* it's a large integer */
4588 }
4589 while (*cur == '.') {
4590 /* skip fraction part */
4591 dot = cur;
4592 cur++;
4593 if (!char_is_digit(*cur)) {
4594 if (has_allow(EXT_NUMBER)) {
4595 break;
4596 } else {
4597 return_err(cur, "no digit after decimal point");
4598 }
4599 }
4600 cur++;
4601 while (char_is_digit(*cur)) cur++;
4602 break;
4603 }
4604 if (char_is_exp(*cur)) {
4605 /* skip exponent part */
4606 cur += 1 + char_is_sign(cur[1]);
4607 if (!char_is_digit(*cur)) {
4608 return_err(cur, "no digit after exponent sign");
4609 }
4610 cur++;
4611 while (char_is_digit(*cur)) cur++;
4612 }
4613
4614 /*
4615 libc's strtod() is used to parse the floating-point number.
4616
4617 Note that the decimal point character used by strtod() is locale-dependent,
4618 and the rounding direction may affected by fesetround().
4619
4620 For currently known locales, (en, zh, ja, ko, am, he, hi) use '.' as the
4621 decimal point, while other locales use ',' as the decimal point.
4622
4623 Here strtod() is called twice for different locales, but if another thread
4624 happens calls setlocale() between two strtod(), parsing may still fail.
4625 */
4626 val->uni.f64 = strtod((const char *)hdr, (char **)&f64_end);
4627 if (unlikely(f64_end != cur)) {
4628 /* replace '.' with ',' for locale */
4629 bool cut = (*cur == ',');
4630 if (cut) *cur = ' ';
4631 if (dot) *dot = ',';
4632 val->uni.f64 = strtod((const char *)hdr, (char **)&f64_end);
4633 /* restore ',' to '.' */
4634 if (cut) *cur = ',';
4635 if (dot) *dot = '.';
4636 if (unlikely(f64_end != cur)) {
4637 return_err(hdr, "strtod() failed to parse the number");
4638 }
4639 }
4640 if (unlikely(val->uni.f64 >= HUGE_VAL || val->uni.f64 <= -HUGE_VAL)) {
4641 return_inf();
4642 }
4643 val->tag = YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL;
4644 *end = cur;
4645 return true;
4646
4647#undef return_err
4648#undef return_0
4649#undef return_i64
4650#undef return_f64
4651#undef return_f64_bin
4652#undef return_inf
4653#undef return_raw
4654}
4655
4656#endif /* FP_READER */
4657
4658
4659
4660/*==============================================================================
4661 * MARK: - String Reader (Private)
4662 *============================================================================*/
4663
4664/** Read unicode escape sequence. */
4665static_inline bool read_uni_esc(u8 **src_ptr, u8 **dst_ptr, const char **msg) {
4666#define return_err(_end, _msg) *msg = _msg; *src_ptr = _end; return false
4667
4668 u8 *src = *src_ptr;
4669 u8 *dst = *dst_ptr;
4670 u16 hi, lo;
4671 u32 uni;
4672
4673 src += 2; /* skip `\u` */
4674 if (unlikely(!hex_load_4(src, &hi))) {
4675 return_err(src - 2, "invalid escaped sequence in string");
4676 }
4677 src += 4; /* skip hex */
4678 if (likely((hi & 0xF800) != 0xD800)) {
4679 /* a BMP character */
4680 if (hi >= 0x800) {
4681 *dst++ = (u8)(0xE0 | (hi >> 12));
4682 *dst++ = (u8)(0x80 | ((hi >> 6) & 0x3F));
4683 *dst++ = (u8)(0x80 | (hi & 0x3F));
4684 } else if (hi >= 0x80) {
4685 *dst++ = (u8)(0xC0 | (hi >> 6));
4686 *dst++ = (u8)(0x80 | (hi & 0x3F));
4687 } else {
4688 *dst++ = (u8)hi;
4689 }
4690 } else {
4691 /* a non-BMP character, represented as a surrogate pair */
4692 if (unlikely((hi & 0xFC00) != 0xD800)) {
4693 return_err(src - 6, "invalid high surrogate in string");
4694 }
4695 if (unlikely(!byte_match_2(src, "\\u"))) {
4696 return_err(src - 6, "no low surrogate in string");
4697 }
4698 if (unlikely(!hex_load_4(src + 2, &lo))) {
4699 return_err(src - 6, "invalid escape in string");
4700 }
4701 if (unlikely((lo & 0xFC00) != 0xDC00)) {
4702 return_err(src - 6, "invalid low surrogate in string");
4703 }
4704 uni = ((((u32)hi - 0xD800) << 10) |
4705 ((u32)lo - 0xDC00)) + 0x10000;
4706 *dst++ = (u8)(0xF0 | (uni >> 18));
4707 *dst++ = (u8)(0x80 | ((uni >> 12) & 0x3F));
4708 *dst++ = (u8)(0x80 | ((uni >> 6) & 0x3F));
4709 *dst++ = (u8)(0x80 | (uni & 0x3F));
4710 src += 6;
4711 }
4712 *src_ptr = src;
4713 *dst_ptr = dst;
4714 return true;
4715#undef return_err
4716}
4717
4718/**
4719 Read a JSON string.
4720 @param quo The quote character (single quote or double quote).
4721 @param ptr The head pointer of string before quote (inout).
4722 @param eof JSON end position.
4723 @param flg JSON read flag.
4724 @param val The string value to be written.
4725 @param msg The error message pointer.
4726 @param con Continuation for incremental parsing.
4727 @return Whether success.
4728 */
4729static_inline bool read_str_opt(u8 quo, u8 **ptr, u8 *eof, yyjson_read_flag flg,
4730 yyjson_val *val, const char **msg, u8 *con[2]) {
4731 /*
4732 GCC may sometimes load variables into registers too early, causing
4733 unnecessary instructions and performance degradation. This inline assembly
4734 serves as a hint to GCC: 'This variable will be modified, so avoid loading
4735 it too early.' Other compilers like MSVC, Clang, and ICC can generate the
4736 expected instructions without needing this hint.
4737
4738 Check out this example: https://godbolt.org/z/YG6a5W5Ec
4739 */
4740#define return_err(_end, _msg) do { \
4741 *msg = _msg; \
4742 *end = _end; \
4743 if (con) { con[0] = _end; con[1] = dst; } \
4744 return false; \
4745} while (false)
4746
4747 u8 *hdr = *ptr + 1;
4748 u8 **end = ptr;
4749 u8 *src = hdr, *dst = NULL, *pos;
4750 u16 hi, lo;
4751 u32 uni, tmp;
4752
4753 /* Resume incremental parsing. */
4754 if (con && unlikely(con[0])) {
4755 src = con[0];
4756 dst = con[1];
4757 if (dst) goto copy_ascii;
4758 }
4759
4760skip_ascii:
4761 /*
4762 Most strings have no escaped characters, so we can jump them quickly.
4763
4764 We want to make loop unrolling, as shown in the following code. Some
4765 compiler may not generate instructions as expected, so we rewrite it with
4766 explicit goto statements. We hope the compiler can generate instructions
4767 like this: https://godbolt.org/z/8vjsYq
4768
4769 while (true) repeat16({
4770 if (likely((char_is_ascii_skip(*src)))) src++;
4771 else break;
4772 })
4773 */
4774 if (quo == '"') {
4775#define expr_jump(i) \
4776 if (likely(char_is_ascii_skip(src[i]))) {} \
4777 else goto skip_ascii_stop##i;
4778
4779#define expr_stop(i) \
4780 skip_ascii_stop##i: \
4781 src += i; \
4782 goto skip_ascii_end;
4783
4784 repeat16_incr(expr_jump)
4785 src += 16;
4786 goto skip_ascii;
4787 repeat16_incr(expr_stop)
4788
4789#undef expr_jump
4790#undef expr_stop
4791 } else {
4792#define expr_jump(i) \
4793 if (likely(char_is_ascii_skip_sq(src[i]))) {} \
4794 else goto skip_ascii_stop_sq##i;
4795
4796#define expr_stop(i) \
4797 skip_ascii_stop_sq##i: \
4798 src += i; \
4799 goto skip_ascii_end;
4800
4801 repeat16_incr(expr_jump)
4802 src += 16;
4803 goto skip_ascii;
4804 repeat16_incr(expr_stop)
4805
4806#undef expr_jump
4807#undef expr_stop
4808 }
4809
4810skip_ascii_end:
4811 gcc_store_barrier(*src);
4812 if (likely(*src == quo)) {
4813 val->tag = ((u64)(src - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_STR |
4814 (quo == '"' ? YYJSON_SUBTYPE_NOESC : 0);
4815 val->uni.str = (const char *)hdr;
4816 *src = '\0';
4817 *end = src + 1;
4818 if (con) con[0] = con[1] = NULL;
4819 return true;
4820 }
4821
4822skip_utf8:
4823 if (*src & 0x80) { /* non-ASCII character */
4824 /*
4825 Non-ASCII character appears here, which means that the text is likely
4826 to be written in non-English or emoticons. According to some common
4827 data set statistics, byte sequences of the same length may appear
4828 consecutively. We process the byte sequences of the same length in each
4829 loop, which is more friendly to branch prediction.
4830 */
4831 pos = src;
4832#if YYJSON_DISABLE_UTF8_VALIDATION
4833 while (true) repeat8({
4834 if (likely((*src & 0xF0) == 0xE0)) src += 3;
4835 else break;
4836 })
4837 if (*src < 0x80) goto skip_ascii;
4838 while (true) repeat8({
4839 if (likely((*src & 0xE0) == 0xC0)) src += 2;
4840 else break;
4841 })
4842 while (true) repeat8({
4843 if (likely((*src & 0xF8) == 0xF0)) src += 4;
4844 else break;
4845 })
4846#else
4847 uni = byte_load_4(src);
4848 while (is_utf8_seq3(uni)) {
4849 src += 3;
4850 uni = byte_load_4(src);
4851 }
4852 if (is_utf8_seq1(uni)) goto skip_ascii;
4853 while (is_utf8_seq2(uni)) {
4854 src += 2;
4855 uni = byte_load_4(src);
4856 }
4857 while (is_utf8_seq4(uni)) {
4858 src += 4;
4859 uni = byte_load_4(src);
4860 }
4861#endif
4862 if (unlikely(pos == src)) {
4863 if (has_allow(INVALID_UNICODE)) ++src;
4864 else return_err(src, "invalid UTF-8 encoding in string");
4865 }
4866 goto skip_ascii;
4867 }
4868
4869 /* The escape character appears, we need to copy it. */
4870 dst = src;
4871copy_escape:
4872 if (likely(*src == '\\')) {
4873 switch (*++src) {
4874 case '"': *dst++ = '"'; src++; break;
4875 case '\\': *dst++ = '\\'; src++; break;
4876 case '/': *dst++ = '/'; src++; break;
4877 case 'b': *dst++ = '\b'; src++; break;
4878 case 'f': *dst++ = '\f'; src++; break;
4879 case 'n': *dst++ = '\n'; src++; break;
4880 case 'r': *dst++ = '\r'; src++; break;
4881 case 't': *dst++ = '\t'; src++; break;
4882 case 'u':
4883 src--;
4884 if (!read_uni_esc(&src, &dst, msg)) return_err(src, *msg);
4885 break;
4886 default: {
4887 if (has_allow(EXT_ESCAPE)) {
4888 /* read extended escape (non-standard) */
4889 switch (*src) {
4890 case '\'': *dst++ = '\''; src++; break;
4891 case 'a': *dst++ = '\a'; src++; break;
4892 case 'v': *dst++ = '\v'; src++; break;
4893 case '?': *dst++ = '\?'; src++; break;
4894 case 'e': *dst++ = 0x1B; src++; break;
4895 case '0':
4896 if (!char_is_digit(src[1])) {
4897 *dst++ = '\0'; src++; break;
4898 }
4899 return_err(src - 1, "octal escape is not allowed");
4900 case '1': case '2': case '3': case '4':
4901 case '5': case '6': case '7': case '8': case '9':
4902 return_err(src - 1, "invalid number escape");
4903 case 'x': {
4904 u8 c;
4905 if (hex_load_2(src + 1, &c)) {
4906 src += 3;
4907 if (c <= 0x7F) { /* 1-byte ASCII */
4908 *dst++ = c;
4909 } else { /* 2-byte UTF-8 */
4910 *dst++ = (u8)(0xC0 | (c >> 6));
4911 *dst++ = (u8)(0x80 | (c & 0x3F));
4912 }
4913 break;
4914 }
4915 return_err(src - 1, "invalid hex escape");
4916 }
4917 case '\n': src++; break;
4918 case '\r': src++; src += (*src == '\n'); break;
4919 case 0xE2: /* Line terminator: U+2028, U+2029 */
4920 if ((src[1] == 0x80 && src[2] == 0xA8) ||
4921 (src[1] == 0x80 && src[2] == 0xA9)) {
4922 src += 3;
4923 }
4924 break;
4925 default:
4926 break; /* skip */
4927 }
4928 } else if (quo == '\'' && *src == '\'') {
4929 *dst++ = '\''; src++; break;
4930 } else {
4931 return_err(src - 1, "invalid escaped sequence in string");
4932 }
4933 }
4934 }
4935 } else if (likely(*src == quo)) {
4936 val->tag = ((u64)(dst - hdr) << YYJSON_TAG_BIT) | YYJSON_TYPE_STR;
4937 val->uni.str = (const char *)hdr;
4938 *dst = '\0';
4939 *end = src + 1;
4940 if (con) con[0] = con[1] = NULL;
4941 return true;
4942 } else {
4943 if (!has_allow(INVALID_UNICODE)) {
4944 return_err(src, "unexpected control character in string");
4945 }
4946 if (src >= eof) return_err(src, "unclosed string");
4947 *dst++ = *src++;
4948 }
4949
4950copy_ascii:
4951 /*
4952 Copy continuous ASCII, loop unrolling, same as the following code:
4953
4954 while (true) repeat16({
4955 if (char_is_ascii_skip(*src)) *dst++ = *src++;
4956 else break;
4957 })
4958 */
4959 if (quo == '"') {
4960#define expr_jump(i) \
4961 if (likely((char_is_ascii_skip(src[i])))) {} \
4962 else { gcc_store_barrier(src[i]); goto copy_ascii_stop_##i; }
4963 repeat16_incr(expr_jump)
4964#undef expr_jump
4965 } else {
4966#define expr_jump(i) \
4967 if (likely((char_is_ascii_skip_sq(src[i])))) {} \
4968 else { gcc_store_barrier(src[i]); goto copy_ascii_stop_##i; }
4969 repeat16_incr(expr_jump)
4970#undef expr_jump
4971 }
4972
4973 byte_move_16(dst, src);
4974 dst += 16; src += 16;
4975 goto copy_ascii;
4976
4977 /*
4978 The memory is copied forward since `dst < src`.
4979 So it's safe to move one extra byte to reduce instruction count.
4980 */
4981#define expr_jump(i) \
4982 copy_ascii_stop_##i: \
4983 byte_move_forward(dst, src, i); \
4984 dst += i; src += i; \
4985 goto copy_utf8;
4986 repeat16_incr(expr_jump)
4987#undef expr_jump
4988
4989copy_utf8:
4990 if (*src & 0x80) { /* non-ASCII character */
4991 pos = src;
4992 uni = byte_load_4(src);
4993#if YYJSON_DISABLE_UTF8_VALIDATION
4994 while (true) repeat4({
4995 if ((uni & utf8_seq(b3_mask)) == utf8_seq(b3_patt)) {
4996 byte_copy_4(dst, &uni);
4997 dst += 3; src += 3;
4998 uni = byte_load_4(src);
4999 } else break;
5000 })
5001 if ((uni & utf8_seq(b1_mask)) == utf8_seq(b1_patt)) goto copy_ascii;
5002 while (true) repeat4({
5003 if ((uni & utf8_seq(b2_mask)) == utf8_seq(b2_patt)) {
5004 byte_copy_2(dst, &uni);
5005 dst += 2; src += 2;
5006 uni = byte_load_4(src);
5007 } else break;
5008 })
5009 while (true) repeat4({
5010 if ((uni & utf8_seq(b4_mask)) == utf8_seq(b4_patt)) {
5011 byte_copy_4(dst, &uni);
5012 dst += 4; src += 4;
5013 uni = byte_load_4(src);
5014 } else break;
5015 })
5016#else
5017 while (is_utf8_seq3(uni)) {
5018 byte_copy_4(dst, &uni);
5019 dst += 3; src += 3;
5020 uni = byte_load_4(src);
5021 }
5022 if (is_utf8_seq1(uni)) goto copy_ascii;
5023 while (is_utf8_seq2(uni)) {
5024 byte_copy_2(dst, &uni);
5025 dst += 2; src += 2;
5026 uni = byte_load_4(src);
5027 }
5028 while (is_utf8_seq4(uni)) {
5029 byte_copy_4(dst, &uni);
5030 dst += 4; src += 4;
5031 uni = byte_load_4(src);
5032 }
5033#endif
5034 if (unlikely(pos == src)) {
5035 if (!has_allow(INVALID_UNICODE)) {
5036 return_err(src, MSG_ERR_UTF8);
5037 }
5038 goto copy_ascii_stop_1;
5039 }
5040 goto copy_ascii;
5041 }
5042 goto copy_escape;
5043
5044#undef return_err
5045}
5046
5047static_inline bool read_str(u8 **ptr, u8 *eof, yyjson_read_flag flg,
5048 yyjson_val *val, const char **msg) {
5049 return read_str_opt('\"', ptr, eof, flg, val, msg, NULL);
5050}
5051
5052static_inline bool read_str_con(u8 **ptr, u8 *eof, yyjson_read_flag flg,
5053 yyjson_val *val, const char **msg, u8 **con) {
5054 return read_str_opt('\"', ptr, eof, flg, val, msg, con);
5055}
5056
5057static_noinline bool read_str_sq(u8 **ptr, u8 *eof, yyjson_read_flag flg,
5058 yyjson_val *val, const char **msg) {
5059 return read_str_opt('\'', ptr, eof, flg, val, msg, NULL);
5060}
5061
5062/** Read unquoted key (identifier name). */
5063static_noinline bool read_str_id(u8 **ptr, u8 *eof, yyjson_read_flag flg,
5064 u8 **pre, yyjson_val *val, const char **msg) {
5065#define return_err(_end, _msg) do { \
5066 *msg = _msg; \
5067 *end = _end; \
5068 return false; \
5069} while (false)
5070
5071#define return_suc(_str_end, _cur_end) do { \
5072 val->tag = ((u64)(_str_end - hdr) << YYJSON_TAG_BIT) | \
5073 (u64)(YYJSON_TYPE_STR); \
5074 val->uni.str = (const char *)hdr; \
5075 *pre = _str_end; *end = _cur_end; \
5076 return true; \
5077} while (false)
5078
5079 u8 *hdr = *ptr;
5080 u8 **end = ptr;
5081 u8 *src = hdr, *dst = NULL;
5082 u16 hi, lo;
5083 u32 uni, tmp;
5084
5085 /* add null-terminator for previous raw string */
5086 **pre = '\0';
5087
5088skip_ascii:
5089#define expr_jump(i) \
5090 if (likely(char_is_id_ascii(src[i]))) {} \
5091 else goto skip_ascii_stop##i;
5092
5093#define expr_stop(i) \
5094 skip_ascii_stop##i: \
5095 src += i; \
5096 goto skip_ascii_end;
5097
5098 repeat16_incr(expr_jump)
5099 src += 16;
5100 goto skip_ascii;
5101 repeat16_incr(expr_stop)
5102
5103#undef expr_jump
5104#undef expr_stop
5105
5106skip_ascii_end:
5107 gcc_store_barrier(*src);
5108 if (likely(!char_is_id_next(*src))) {
5109 return_suc(src, src);
5110 }
5111
5112skip_utf8:
5113 while (*src >= 0x80) {
5114 if (has_allow(EXT_WHITESPACE)) {
5115 if (char_is_space_ext(*src) && ext_space_len(src)) {
5116 return_suc(src, src);
5117 }
5118 }
5119 uni = byte_load_4(src);
5120 if (is_utf8_seq2(uni)) {
5121 src += 2;
5122 } else if (is_utf8_seq3(uni)) {
5123 src += 3;
5124 } else if (is_utf8_seq4(uni)) {
5125 src += 4;
5126 } else {
5127#if !YYJSON_DISABLE_UTF8_VALIDATION
5128 if (!has_allow(INVALID_UNICODE)) return_err(src, MSG_ERR_UTF8);
5129#endif
5130 src += 1;
5131 }
5132 }
5133 if (char_is_id_ascii(*src)) goto skip_ascii;
5134
5135 /* The escape character appears, we need to copy it. */
5136 dst = src;
5137copy_escape:
5138 if (byte_match_2(src, "\\u")) {
5139 if (!read_uni_esc(&src, &dst, msg)) return_err(src, *msg);
5140 } else {
5141 if (!char_is_id_next(*src)) return_suc(dst, src);
5142 return_err(src, "unexpected character in key");
5143 }
5144
5145copy_ascii:
5146 /*
5147 Copy continuous ASCII, loop unrolling, same as the following code:
5148
5149 while (true) repeat16({
5150 if (char_is_ascii_skip(*src)) *dst++ = *src++;
5151 else break;
5152 })
5153 */
5154#define expr_jump(i) \
5155 if (likely((char_is_id_ascii(src[i])))) {} \
5156 else { gcc_store_barrier(src[i]); goto copy_ascii_stop_##i; }
5157 repeat16_incr(expr_jump)
5158#undef expr_jump
5159
5160 byte_move_16(dst, src);
5161 dst += 16; src += 16;
5162 goto copy_ascii;
5163
5164#define expr_jump(i) \
5165 copy_ascii_stop_##i: \
5166 byte_move_forward(dst, src, i); \
5167 dst += i; src += i; \
5168 goto copy_utf8;
5169 repeat16_incr(expr_jump)
5170#undef expr_jump
5171
5172copy_utf8:
5173 while (*src >= 0x80) { /* non-ASCII character */
5174 if (has_allow(EXT_WHITESPACE)) {
5175 if (char_is_space_ext(*src) && ext_space_len(src)) {
5176 return_suc(dst, src);
5177 }
5178 }
5179 uni = byte_load_4(src);
5180 if (is_utf8_seq2(uni)) {
5181 byte_copy_2(dst, &uni);
5182 dst += 2; src += 2;
5183 } else if (is_utf8_seq3(uni)) {
5184 byte_copy_4(dst, &uni);
5185 dst += 3; src += 3;
5186 } else if (is_utf8_seq4(uni)) {
5187 byte_copy_4(dst, &uni);
5188 dst += 4; src += 4;
5189 } else {
5190#if !YYJSON_DISABLE_UTF8_VALIDATION
5191 if (!has_allow(INVALID_UNICODE)) return_err(src, MSG_ERR_UTF8);
5192#endif
5193 *dst = *src;
5194 dst += 1; src += 1;
5195 }
5196 }
5197 if (char_is_id_ascii(*src)) goto copy_ascii;
5198 goto copy_escape;
5199
5200#undef return_err
5201#undef return_suc
5202}
5203
5204
5205
5206/*==============================================================================
5207 * MARK: - JSON Reader Implementation (Private)
5208 *
5209 * We use goto statements to build the finite state machine (FSM).
5210 * The FSM's state was held by program counter (PC) and the 'goto' make the
5211 * state transitions.
5212 *============================================================================*/
5213
5214/** Read single value JSON document. */
5215static_noinline yyjson_doc *read_root_single(u8 *hdr, u8 *cur, u8 *eof,
5216 yyjson_alc alc,
5217 yyjson_read_flag flg,
5218 yyjson_read_err *err) {
5219#define return_err(_pos, _code, _msg) do { \
5220 if (is_truncated_end(hdr, _pos, eof, YYJSON_READ_ERROR_##_code, flg)) { \
5221 err->pos = (usize)(eof - hdr); \
5222 err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \
5223 err->msg = MSG_NOT_END; \
5224 } else { \
5225 err->pos = (usize)(_pos - hdr); \
5226 err->code = YYJSON_READ_ERROR_##_code; \
5227 err->msg = _msg; \
5228 } \
5229 if (val_hdr) alc.free(alc.ctx, val_hdr); \
5230 return NULL; \
5231} while (false)
5232
5233 usize hdr_len; /* value count used by doc */
5234 usize alc_num; /* value count capacity */
5235 yyjson_val *val_hdr; /* the head of allocated values */
5236 yyjson_val *val; /* current value */
5237 yyjson_doc *doc; /* the JSON document, equals to val_hdr */
5238 const char *msg; /* error message */
5239
5240 u8 raw_end[1]; /* raw end for null-terminator */
5241 u8 *raw_ptr = raw_end;
5242 u8 **pre = &raw_ptr; /* previous raw end pointer */
5243
5244 hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);
5245 hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;
5246 alc_num = hdr_len + 1; /* single value */
5247
5248 val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_num * sizeof(yyjson_val));
5249 if (unlikely(!val_hdr)) goto fail_alloc;
5250 val = val_hdr + hdr_len;
5251
5252 if (char_is_num(*cur)) {
5253 if (likely(read_num(&cur, pre, flg, val, &msg))) goto doc_end;
5254 goto fail_number;
5255 }
5256 if (*cur == '"') {
5257 if (likely(read_str(&cur, eof, flg, val, &msg))) goto doc_end;
5258 goto fail_string;
5259 }
5260 if (*cur == 't') {
5261 if (likely(read_true(&cur, val))) goto doc_end;
5262 goto fail_literal_true;
5263 }
5264 if (*cur == 'f') {
5265 if (likely(read_false(&cur, val))) goto doc_end;
5266 goto fail_literal_false;
5267 }
5268 if (*cur == 'n') {
5269 if (likely(read_null(&cur, val))) goto doc_end;
5270 if (has_allow(INF_AND_NAN)) {
5271 if (read_nan(&cur, pre, flg, val)) goto doc_end;
5272 }
5273 goto fail_literal_null;
5274 }
5275 if (has_allow(INF_AND_NAN)) {
5276 if (read_inf_or_nan(&cur, pre, flg, val)) goto doc_end;
5277 }
5278 if (has_allow(SINGLE_QUOTED_STR) && *cur == '\'') {
5279 if (likely(read_str_sq(&cur, eof, flg, val, &msg))) goto doc_end;
5280 goto fail_string;
5281 }
5282 goto fail_character;
5283
5284doc_end:
5285 /* check invalid contents after json document */
5286 if (unlikely(cur < eof) && !has_flg(STOP_WHEN_DONE)) {
5287 while (char_is_space(*cur)) cur++;
5288 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5289 if (!skip_trivia(&cur, eof, flg) && cur == eof) {
5290 goto fail_comment;
5291 }
5292 }
5293 if (unlikely(cur < eof)) goto fail_garbage;
5294 }
5295
5296 **pre = '\0';
5297 doc = (yyjson_doc *)val_hdr;
5298 doc->root = val_hdr + hdr_len;
5299 doc->alc = alc;
5300 doc->dat_read = (usize)(cur - hdr);
5301 doc->val_read = 1;
5302 doc->str_pool = has_flg(INSITU) ? NULL : (char *)hdr;
5303 return doc;
5304
5305fail_string: return_err(cur, INVALID_STRING, msg);
5306fail_number: return_err(cur, INVALID_NUMBER, msg);
5307fail_alloc: return_err(cur, MEMORY_ALLOCATION, MSG_MALLOC);
5308fail_literal_true: return_err(cur, LITERAL, MSG_CHAR_T);
5309fail_literal_false: return_err(cur, LITERAL, MSG_CHAR_F);
5310fail_literal_null: return_err(cur, LITERAL, MSG_CHAR_N);
5311fail_character: return_err(cur, UNEXPECTED_CHARACTER, MSG_CHAR);
5312fail_comment: return_err(cur, INVALID_COMMENT, MSG_COMMENT);
5313fail_garbage: return_err(cur, UNEXPECTED_CONTENT, MSG_GARBAGE);
5314fail_depth: return_err(cur, DEPTH, MSG_DEPTH);
5315
5316#undef return_err
5317}
5318
5319/** Read JSON document (accept all style, but optimized for minify). */
5320static_inline yyjson_doc *read_root_minify(u8 *hdr, u8 *cur, u8 *eof,
5321 yyjson_alc alc,
5322 yyjson_read_flag flg,
5323 yyjson_read_err *err) {
5324#define return_err(_pos, _code, _msg) do { \
5325 if (is_truncated_end(hdr, _pos, eof, YYJSON_READ_ERROR_##_code, flg)) { \
5326 err->pos = (usize)(eof - hdr); \
5327 err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \
5328 err->msg = MSG_NOT_END; \
5329 } else { \
5330 err->pos = (usize)(_pos - hdr); \
5331 err->code = YYJSON_READ_ERROR_##_code; \
5332 err->msg = _msg; \
5333 } \
5334 if (val_hdr) alc.free(alc.ctx, val_hdr); \
5335 return NULL; \
5336} while (false)
5337
5338#define val_incr() do { \
5339 val++; \
5340 if (unlikely(val >= val_end)) { \
5341 usize alc_old = alc_len; \
5342 usize val_ofs = (usize)(val - val_hdr); \
5343 usize ctn_ofs = (usize)(ctn - val_hdr); \
5344 alc_len += alc_len / 2; \
5345 if ((sizeof(usize) < 8) && (alc_len >= alc_max)) goto fail_alloc; \
5346 val_tmp = (yyjson_val *)alc.realloc(alc.ctx, (void *)val_hdr, \
5347 alc_old * sizeof(yyjson_val), \
5348 alc_len * sizeof(yyjson_val)); \
5349 if ((!val_tmp)) goto fail_alloc; \
5350 val = val_tmp + val_ofs; \
5351 ctn = val_tmp + ctn_ofs; \
5352 val_hdr = val_tmp; \
5353 val_end = val_tmp + (alc_len - 2); \
5354 } \
5355} while (false)
5356
5357 usize dat_len; /* data length in bytes, hint for allocator */
5358 usize hdr_len; /* value count used by yyjson_doc */
5359 usize alc_len; /* value count allocated */
5360 usize alc_max; /* maximum value count for allocator */
5361 usize ctn_len; /* the number of elements in current container */
5362 yyjson_val *val_hdr; /* the head of allocated values */
5363 yyjson_val *val_end; /* the end of allocated values */
5364 yyjson_val *val_tmp; /* temporary pointer for realloc */
5365 yyjson_val *val; /* current JSON value */
5366 yyjson_val *ctn; /* current container */
5367 yyjson_val *ctn_parent; /* parent of current container */
5368 yyjson_doc *doc; /* the JSON document, equals to val_hdr */
5369 const char *msg; /* error message */
5370
5371 u8 raw_end[1]; /* raw end for null-terminator */
5372 u8 *raw_ptr = raw_end;
5373 u8 **pre = &raw_ptr; /* previous raw end pointer */
5374
5375#if YYJSON_READER_DEPTH_LIMIT
5376 u32 container_depth = 0; /* current array/object depth */
5377#endif
5378
5379 dat_len = has_flg(STOP_WHEN_DONE) ? 256 : (usize)(eof - cur);
5380 hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);
5381 hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;
5382 alc_max = USIZE_MAX / sizeof(yyjson_val);
5383 alc_len = hdr_len + (dat_len / YYJSON_READER_ESTIMATED_MINIFY_RATIO) + 4;
5384 alc_len = yyjson_min(alc_len, alc_max);
5385
5386 val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_len * sizeof(yyjson_val));
5387 if (unlikely(!val_hdr)) goto fail_alloc;
5388 val_end = val_hdr + (alc_len - 2); /* padding for key-value pair reading */
5389 val = val_hdr + hdr_len;
5390 ctn = val;
5391 ctn_len = 0;
5392
5393 if (*cur++ == '{') {
5394 ctn->tag = YYJSON_TYPE_OBJ;
5395 ctn->uni.ofs = 0;
5396 goto obj_key_begin;
5397 } else {
5398 ctn->tag = YYJSON_TYPE_ARR;
5399 ctn->uni.ofs = 0;
5400 goto arr_val_begin;
5401 }
5402
5403arr_begin:
5404#if YYJSON_READER_DEPTH_LIMIT
5405 container_depth++;
5406 if (unlikely(container_depth >= YYJSON_READER_DEPTH_LIMIT)) {
5407 goto fail_depth;
5408 }
5409#endif
5410 /* save current container */
5411 ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
5412 (ctn->tag & YYJSON_TAG_MASK);
5413
5414 /* create a new array value, save parent container offset */
5415 val_incr();
5416 val->tag = YYJSON_TYPE_ARR;
5417 val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
5418
5419 /* push the new array value as current container */
5420 ctn = val;
5421 ctn_len = 0;
5422
5423arr_val_begin:
5424 if (*cur == '{') {
5425 cur++;
5426 goto obj_begin;
5427 }
5428 if (*cur == '[') {
5429 cur++;
5430 goto arr_begin;
5431 }
5432 if (char_is_num(*cur)) {
5433 val_incr();
5434 ctn_len++;
5435 if (likely(read_num(&cur, pre, flg, val, &msg))) goto arr_val_end;
5436 goto fail_number;
5437 }
5438 if (*cur == '"') {
5439 val_incr();
5440 ctn_len++;
5441 if (likely(read_str(&cur, eof, flg, val, &msg))) goto arr_val_end;
5442 goto fail_string;
5443 }
5444 if (*cur == 't') {
5445 val_incr();
5446 ctn_len++;
5447 if (likely(read_true(&cur, val))) goto arr_val_end;
5448 goto fail_literal_true;
5449 }
5450 if (*cur == 'f') {
5451 val_incr();
5452 ctn_len++;
5453 if (likely(read_false(&cur, val))) goto arr_val_end;
5454 goto fail_literal_false;
5455 }
5456 if (*cur == 'n') {
5457 val_incr();
5458 ctn_len++;
5459 if (likely(read_null(&cur, val))) goto arr_val_end;
5460 if (has_allow(INF_AND_NAN)) {
5461 if (read_nan(&cur, pre, flg, val)) goto arr_val_end;
5462 }
5463 goto fail_literal_null;
5464 }
5465 if (*cur == ']') {
5466 cur++;
5467 if (likely(ctn_len == 0)) goto arr_end;
5468 if (has_allow(TRAILING_COMMAS)) goto arr_end;
5469 while (*cur != ',') cur--;
5470 goto fail_trailing_comma;
5471 }
5472 if (char_is_space(*cur)) {
5473 while (char_is_space(*++cur));
5474 goto arr_val_begin;
5475 }
5476 if (has_allow(INF_AND_NAN) &&
5477 (*cur == 'i' || *cur == 'I' || *cur == 'N')) {
5478 val_incr();
5479 ctn_len++;
5480 if (read_inf_or_nan(&cur, pre, flg, val)) goto arr_val_end;
5481 goto fail_character_val;
5482 }
5483 if (has_allow(SINGLE_QUOTED_STR) && *cur == '\'') {
5484 val_incr();
5485 ctn_len++;
5486 if (likely(read_str_sq(&cur, eof, flg, val, &msg))) goto arr_val_end;
5487 goto fail_string;
5488 }
5489 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5490 if (skip_trivia(&cur, eof, flg)) goto arr_val_begin;
5491 if (cur == eof) goto fail_comment;
5492 }
5493 goto fail_character_val;
5494
5495arr_val_end:
5496 if (*cur == ',') {
5497 cur++;
5498 goto arr_val_begin;
5499 }
5500 if (*cur == ']') {
5501 cur++;
5502 goto arr_end;
5503 }
5504 if (char_is_space(*cur)) {
5505 while (char_is_space(*++cur));
5506 goto arr_val_end;
5507 }
5508 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5509 if (skip_trivia(&cur, eof, flg)) goto arr_val_end;
5510 if (cur == eof) goto fail_comment;
5511 }
5512 goto fail_character_arr_end;
5513
5514arr_end:
5515#if YYJSON_READER_DEPTH_LIMIT
5516 container_depth--;
5517#endif
5518 /* get parent container */
5519 ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
5520
5521 /* save the next sibling value offset */
5522 ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
5523 ctn->tag = ((ctn_len) << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR;
5524 if (unlikely(ctn == ctn_parent)) goto doc_end;
5525
5526 /* pop parent as current container */
5527 ctn = ctn_parent;
5528 ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
5529 if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
5530 goto obj_val_end;
5531 } else {
5532 goto arr_val_end;
5533 }
5534
5535obj_begin:
5536#if YYJSON_READER_DEPTH_LIMIT
5537 container_depth++;
5538 if (unlikely(container_depth >= YYJSON_READER_DEPTH_LIMIT)) {
5539 goto fail_depth;
5540 }
5541#endif
5542 /* push container */
5543 ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
5544 (ctn->tag & YYJSON_TAG_MASK);
5545 val_incr();
5546 val->tag = YYJSON_TYPE_OBJ;
5547 /* offset to the parent */
5548 val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
5549 ctn = val;
5550 ctn_len = 0;
5551
5552obj_key_begin:
5553 if (likely(*cur == '"')) {
5554 val_incr();
5555 ctn_len++;
5556 if (likely(read_str(&cur, eof, flg, val, &msg))) goto obj_key_end;
5557 goto fail_string;
5558 }
5559 if (likely(*cur == '}')) {
5560 cur++;
5561 if (likely(ctn_len == 0)) goto obj_end;
5562 if (has_allow(TRAILING_COMMAS)) goto obj_end;
5563 while (*cur != ',') cur--;
5564 goto fail_trailing_comma;
5565 }
5566 if (char_is_space(*cur)) {
5567 while (char_is_space(*++cur));
5568 goto obj_key_begin;
5569 }
5570 if (has_allow(SINGLE_QUOTED_STR) && *cur == '\'') {
5571 val_incr();
5572 ctn_len++;
5573 if (likely(read_str_sq(&cur, eof, flg, val, &msg))) goto obj_key_end;
5574 goto fail_string;
5575 }
5576 if (has_allow(UNQUOTED_KEY) && char_is_id_start(*cur)) {
5577 val_incr();
5578 ctn_len++;
5579 if (read_str_id(&cur, eof, flg, pre, val, &msg)) goto obj_key_end;
5580 goto fail_string;
5581 }
5582 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5583 if (skip_trivia(&cur, eof, flg)) goto obj_key_begin;
5584 if (cur == eof) goto fail_comment;
5585 }
5586 goto fail_character_obj_key;
5587
5588obj_key_end:
5589 if (*cur == ':') {
5590 cur++;
5591 goto obj_val_begin;
5592 }
5593 if (char_is_space(*cur)) {
5594 while (char_is_space(*++cur));
5595 goto obj_key_end;
5596 }
5597 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5598 if (skip_trivia(&cur, eof, flg)) goto obj_key_end;
5599 if (cur == eof) goto fail_comment;
5600 }
5601 goto fail_character_obj_sep;
5602
5603obj_val_begin:
5604 if (*cur == '"') {
5605 val++;
5606 ctn_len++;
5607 if (likely(read_str(&cur, eof, flg, val, &msg))) goto obj_val_end;
5608 goto fail_string;
5609 }
5610 if (char_is_num(*cur)) {
5611 val++;
5612 ctn_len++;
5613 if (likely(read_num(&cur, pre, flg, val, &msg))) goto obj_val_end;
5614 goto fail_number;
5615 }
5616 if (*cur == '{') {
5617 cur++;
5618 goto obj_begin;
5619 }
5620 if (*cur == '[') {
5621 cur++;
5622 goto arr_begin;
5623 }
5624 if (*cur == 't') {
5625 val++;
5626 ctn_len++;
5627 if (likely(read_true(&cur, val))) goto obj_val_end;
5628 goto fail_literal_true;
5629 }
5630 if (*cur == 'f') {
5631 val++;
5632 ctn_len++;
5633 if (likely(read_false(&cur, val))) goto obj_val_end;
5634 goto fail_literal_false;
5635 }
5636 if (*cur == 'n') {
5637 val++;
5638 ctn_len++;
5639 if (likely(read_null(&cur, val))) goto obj_val_end;
5640 if (has_allow(INF_AND_NAN)) {
5641 if (read_nan(&cur, pre, flg, val)) goto obj_val_end;
5642 }
5643 goto fail_literal_null;
5644 }
5645 if (char_is_space(*cur)) {
5646 while (char_is_space(*++cur));
5647 goto obj_val_begin;
5648 }
5649 if (has_allow(INF_AND_NAN) &&
5650 (*cur == 'i' || *cur == 'I' || *cur == 'N')) {
5651 val++;
5652 ctn_len++;
5653 if (read_inf_or_nan(&cur, pre, flg, val)) goto obj_val_end;
5654 goto fail_character_val;
5655 }
5656 if (has_allow(SINGLE_QUOTED_STR) && *cur == '\'') {
5657 val++;
5658 ctn_len++;
5659 if (likely(read_str_sq(&cur, eof, flg, val, &msg))) goto obj_val_end;
5660 goto fail_string;
5661 }
5662 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5663 if (skip_trivia(&cur, eof, flg)) goto obj_val_begin;
5664 if (cur == eof) goto fail_comment;
5665 }
5666 goto fail_character_val;
5667
5668obj_val_end:
5669 if (likely(*cur == ',')) {
5670 cur++;
5671 goto obj_key_begin;
5672 }
5673 if (likely(*cur == '}')) {
5674 cur++;
5675 goto obj_end;
5676 }
5677 if (char_is_space(*cur)) {
5678 while (char_is_space(*++cur));
5679 goto obj_val_end;
5680 }
5681 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5682 if (skip_trivia(&cur, eof, flg)) goto obj_val_end;
5683 if (cur == eof) goto fail_comment;
5684 }
5685 goto fail_character_obj_end;
5686
5687obj_end:
5688#if YYJSON_READER_DEPTH_LIMIT
5689 container_depth--;
5690#endif
5691 /* pop container */
5692 ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
5693 /* point to the next value */
5694 ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
5695 ctn->tag = (ctn_len << (YYJSON_TAG_BIT - 1)) | YYJSON_TYPE_OBJ;
5696 if (unlikely(ctn == ctn_parent)) goto doc_end;
5697 ctn = ctn_parent;
5698 ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
5699 if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
5700 goto obj_val_end;
5701 } else {
5702 goto arr_val_end;
5703 }
5704
5705doc_end:
5706 /* check invalid contents after json document */
5707 if (unlikely(cur < eof) && !has_flg(STOP_WHEN_DONE)) {
5708 while (char_is_space(*cur)) cur++;
5709 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5710 if (!skip_trivia(&cur, eof, flg) && cur == eof) {
5711 goto fail_comment;
5712 }
5713 }
5714 if (unlikely(cur < eof)) goto fail_garbage;
5715 }
5716
5717 **pre = '\0';
5718 doc = (yyjson_doc *)val_hdr;
5719 doc->root = val_hdr + hdr_len;
5720 doc->alc = alc;
5721 doc->dat_read = (usize)(cur - hdr);
5722 doc->val_read = (usize)((val - doc->root) + 1);
5723 doc->str_pool = has_flg(INSITU) ? NULL : (char *)hdr;
5724 return doc;
5725
5726fail_string: return_err(cur, INVALID_STRING, msg);
5727fail_number: return_err(cur, INVALID_NUMBER, msg);
5728fail_alloc: return_err(cur, MEMORY_ALLOCATION, MSG_MALLOC);
5729fail_trailing_comma: return_err(cur, JSON_STRUCTURE, MSG_COMMA);
5730fail_literal_true: return_err(cur, LITERAL, MSG_CHAR_T);
5731fail_literal_false: return_err(cur, LITERAL, MSG_CHAR_F);
5732fail_literal_null: return_err(cur, LITERAL, MSG_CHAR_N);
5733fail_character_val: return_err(cur, UNEXPECTED_CHARACTER, MSG_CHAR);
5734fail_character_arr_end: return_err(cur, UNEXPECTED_CHARACTER, MSG_ARR_END);
5735fail_character_obj_key: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_KEY);
5736fail_character_obj_sep: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_SEP);
5737fail_character_obj_end: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_END);
5738fail_comment: return_err(cur, INVALID_COMMENT, MSG_COMMENT);
5739fail_garbage: return_err(cur, UNEXPECTED_CONTENT, MSG_GARBAGE);
5740fail_depth: return_err(cur, DEPTH, MSG_DEPTH);
5741
5742#undef val_incr
5743#undef return_err
5744}
5745
5746/** Read JSON document (accept all style, but optimized for pretty). */
5747static_inline yyjson_doc *read_root_pretty(u8 *hdr, u8 *cur, u8 *eof,
5748 yyjson_alc alc,
5749 yyjson_read_flag flg,
5750 yyjson_read_err *err) {
5751#define return_err(_pos, _code, _msg) do { \
5752 if (is_truncated_end(hdr, _pos, eof, YYJSON_READ_ERROR_##_code, flg)) { \
5753 err->pos = (usize)(eof - hdr); \
5754 err->code = YYJSON_READ_ERROR_UNEXPECTED_END; \
5755 err->msg = MSG_NOT_END; \
5756 } else { \
5757 err->pos = (usize)(_pos - hdr); \
5758 err->code = YYJSON_READ_ERROR_##_code; \
5759 err->msg = _msg; \
5760 } \
5761 if (val_hdr) alc.free(alc.ctx, val_hdr); \
5762 return NULL; \
5763} while (false)
5764
5765#define val_incr() do { \
5766 val++; \
5767 if (unlikely(val >= val_end)) { \
5768 usize alc_old = alc_len; \
5769 usize val_ofs = (usize)(val - val_hdr); \
5770 usize ctn_ofs = (usize)(ctn - val_hdr); \
5771 alc_len += alc_len / 2; \
5772 if ((sizeof(usize) < 8) && (alc_len >= alc_max)) goto fail_alloc; \
5773 val_tmp = (yyjson_val *)alc.realloc(alc.ctx, (void *)val_hdr, \
5774 alc_old * sizeof(yyjson_val), \
5775 alc_len * sizeof(yyjson_val)); \
5776 if ((!val_tmp)) goto fail_alloc; \
5777 val = val_tmp + val_ofs; \
5778 ctn = val_tmp + ctn_ofs; \
5779 val_hdr = val_tmp; \
5780 val_end = val_tmp + (alc_len - 2); \
5781 } \
5782} while (false)
5783
5784 usize dat_len; /* data length in bytes, hint for allocator */
5785 usize hdr_len; /* value count used by yyjson_doc */
5786 usize alc_len; /* value count allocated */
5787 usize alc_max; /* maximum value count for allocator */
5788 usize ctn_len; /* the number of elements in current container */
5789 yyjson_val *val_hdr; /* the head of allocated values */
5790 yyjson_val *val_end; /* the end of allocated values */
5791 yyjson_val *val_tmp; /* temporary pointer for realloc */
5792 yyjson_val *val; /* current JSON value */
5793 yyjson_val *ctn; /* current container */
5794 yyjson_val *ctn_parent; /* parent of current container */
5795 yyjson_doc *doc; /* the JSON document, equals to val_hdr */
5796 const char *msg; /* error message */
5797
5798 u8 raw_end[1]; /* raw end for null-terminator */
5799 u8 *raw_ptr = raw_end;
5800 u8 **pre = &raw_ptr; /* previous raw end pointer */
5801#if YYJSON_READER_DEPTH_LIMIT
5802 u32 container_depth = 0; /* current array/object depth */
5803#endif
5804
5805 dat_len = has_flg(STOP_WHEN_DONE) ? 256 : (usize)(eof - cur);
5806 hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);
5807 hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;
5808 alc_max = USIZE_MAX / sizeof(yyjson_val);
5809 alc_len = hdr_len + (dat_len / YYJSON_READER_ESTIMATED_PRETTY_RATIO) + 4;
5810 alc_len = yyjson_min(alc_len, alc_max);
5811
5812 val_hdr = (yyjson_val *)alc.malloc(alc.ctx, alc_len * sizeof(yyjson_val));
5813 if (unlikely(!val_hdr)) goto fail_alloc;
5814 val_end = val_hdr + (alc_len - 2); /* padding for key-value pair reading */
5815 val = val_hdr + hdr_len;
5816 ctn = val;
5817 ctn_len = 0;
5818
5819 if (*cur++ == '{') {
5820 ctn->tag = YYJSON_TYPE_OBJ;
5821 ctn->uni.ofs = 0;
5822 if (*cur == '\n') cur++;
5823 goto obj_key_begin;
5824 } else {
5825 ctn->tag = YYJSON_TYPE_ARR;
5826 ctn->uni.ofs = 0;
5827 if (*cur == '\n') cur++;
5828 goto arr_val_begin;
5829 }
5830
5831arr_begin:
5832#if YYJSON_READER_DEPTH_LIMIT
5833 container_depth++;
5834 if (unlikely(container_depth >= YYJSON_READER_DEPTH_LIMIT)) {
5835 goto fail_depth;
5836 }
5837#endif
5838
5839 /* save current container */
5840 ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
5841 (ctn->tag & YYJSON_TAG_MASK);
5842
5843 /* create a new array value, save parent container offset */
5844 val_incr();
5845 val->tag = YYJSON_TYPE_ARR;
5846 val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
5847
5848 /* push the new array value as current container */
5849 ctn = val;
5850 ctn_len = 0;
5851 if (*cur == '\n') cur++;
5852
5853arr_val_begin:
5854#if YYJSON_IS_REAL_GCC
5855 while (true) repeat16({
5856 if (byte_match_2(cur, " ")) cur += 2;
5857 else break;
5858 })
5859#else
5860 while (true) repeat16({
5861 if (likely(byte_match_2(cur, " "))) cur += 2;
5862 else break;
5863 })
5864#endif
5865
5866 if (*cur == '{') {
5867 cur++;
5868 goto obj_begin;
5869 }
5870 if (*cur == '[') {
5871 cur++;
5872 goto arr_begin;
5873 }
5874 if (char_is_num(*cur)) {
5875 val_incr();
5876 ctn_len++;
5877 if (likely(read_num(&cur, pre, flg, val, &msg))) goto arr_val_end;
5878 goto fail_number;
5879 }
5880 if (*cur == '"') {
5881 val_incr();
5882 ctn_len++;
5883 if (likely(read_str(&cur, eof, flg, val, &msg))) goto arr_val_end;
5884 goto fail_string;
5885 }
5886 if (*cur == 't') {
5887 val_incr();
5888 ctn_len++;
5889 if (likely(read_true(&cur, val))) goto arr_val_end;
5890 goto fail_literal_true;
5891 }
5892 if (*cur == 'f') {
5893 val_incr();
5894 ctn_len++;
5895 if (likely(read_false(&cur, val))) goto arr_val_end;
5896 goto fail_literal_false;
5897 }
5898 if (*cur == 'n') {
5899 val_incr();
5900 ctn_len++;
5901 if (likely(read_null(&cur, val))) goto arr_val_end;
5902 if (has_allow(INF_AND_NAN)) {
5903 if (read_nan(&cur, pre, flg, val)) goto arr_val_end;
5904 }
5905 goto fail_literal_null;
5906 }
5907 if (*cur == ']') {
5908 cur++;
5909 if (likely(ctn_len == 0)) goto arr_end;
5910 if (has_allow(TRAILING_COMMAS)) goto arr_end;
5911 while (*cur != ',') cur--;
5912 goto fail_trailing_comma;
5913 }
5914 if (char_is_space(*cur)) {
5915 while (char_is_space(*++cur));
5916 goto arr_val_begin;
5917 }
5918 if (has_allow(INF_AND_NAN) &&
5919 (*cur == 'i' || *cur == 'I' || *cur == 'N')) {
5920 val_incr();
5921 ctn_len++;
5922 if (read_inf_or_nan(&cur, pre, flg, val)) goto arr_val_end;
5923 goto fail_character_val;
5924 }
5925 if (has_allow(SINGLE_QUOTED_STR) && *cur == '\'') {
5926 val_incr();
5927 ctn_len++;
5928 if (likely(read_str_sq(&cur, eof, flg, val, &msg))) goto arr_val_end;
5929 goto fail_string;
5930 }
5931 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5932 if (skip_trivia(&cur, eof, flg)) goto arr_val_begin;
5933 if (cur == eof) goto fail_comment;
5934 }
5935 goto fail_character_val;
5936
5937arr_val_end:
5938 if (byte_match_2(cur, ",\n")) {
5939 cur += 2;
5940 goto arr_val_begin;
5941 }
5942 if (*cur == ',') {
5943 cur++;
5944 goto arr_val_begin;
5945 }
5946 if (*cur == ']') {
5947 cur++;
5948 goto arr_end;
5949 }
5950 if (char_is_space(*cur)) {
5951 while (char_is_space(*++cur));
5952 goto arr_val_end;
5953 }
5954 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
5955 if (skip_trivia(&cur, eof, flg)) goto arr_val_end;
5956 if (cur == eof) goto fail_comment;
5957 }
5958 goto fail_character_arr_end;
5959
5960arr_end:
5961#if YYJSON_READER_DEPTH_LIMIT
5962 container_depth--;
5963#endif
5964 /* get parent container */
5965 ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
5966
5967 /* save the next sibling value offset */
5968 ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
5969 ctn->tag = ((ctn_len) << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR;
5970 if (unlikely(ctn == ctn_parent)) goto doc_end;
5971
5972 /* pop parent as current container */
5973 ctn = ctn_parent;
5974 ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
5975 if (*cur == '\n') cur++;
5976 if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
5977 goto obj_val_end;
5978 } else {
5979 goto arr_val_end;
5980 }
5981
5982obj_begin:
5983#if YYJSON_READER_DEPTH_LIMIT
5984 container_depth++;
5985 if (unlikely(container_depth >= YYJSON_READER_DEPTH_LIMIT)) {
5986 goto fail_depth;
5987 }
5988#endif
5989
5990 /* push container */
5991 ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
5992 (ctn->tag & YYJSON_TAG_MASK);
5993 val_incr();
5994 val->tag = YYJSON_TYPE_OBJ;
5995 /* offset to the parent */
5996 val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
5997 ctn = val;
5998 ctn_len = 0;
5999 if (*cur == '\n') cur++;
6000
6001obj_key_begin:
6002#if YYJSON_IS_REAL_GCC
6003 while (true) repeat16({
6004 if (byte_match_2(cur, " ")) cur += 2;
6005 else break;
6006 })
6007#else
6008 while (true) repeat16({
6009 if (likely(byte_match_2(cur, " "))) cur += 2;
6010 else break;
6011 })
6012#endif
6013 if (likely(*cur == '"')) {
6014 val_incr();
6015 ctn_len++;
6016 if (likely(read_str(&cur, eof, flg, val, &msg))) goto obj_key_end;
6017 goto fail_string;
6018 }
6019 if (likely(*cur == '}')) {
6020 cur++;
6021 if (likely(ctn_len == 0)) goto obj_end;
6022 if (has_allow(TRAILING_COMMAS)) goto obj_end;
6023 while (*cur != ',') cur--;
6024 goto fail_trailing_comma;
6025 }
6026 if (char_is_space(*cur)) {
6027 while (char_is_space(*++cur));
6028 goto obj_key_begin;
6029 }
6030 if (has_allow(SINGLE_QUOTED_STR) && *cur == '\'') {
6031 val_incr();
6032 ctn_len++;
6033 if (likely(read_str_sq(&cur, eof, flg, val, &msg))) goto obj_key_end;
6034 goto fail_string;
6035 }
6036 if (has_allow(UNQUOTED_KEY) && char_is_id_start(*cur)) {
6037 val_incr();
6038 ctn_len++;
6039 if (read_str_id(&cur, eof, flg, pre, val, &msg)) goto obj_key_end;
6040 goto fail_string;
6041 }
6042 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
6043 if (skip_trivia(&cur, eof, flg)) goto obj_key_begin;
6044 if (cur == eof) goto fail_comment;
6045 }
6046 goto fail_character_obj_key;
6047
6048obj_key_end:
6049 if (byte_match_2(cur, ": ")) {
6050 cur += 2;
6051 goto obj_val_begin;
6052 }
6053 if (*cur == ':') {
6054 cur++;
6055 goto obj_val_begin;
6056 }
6057 if (char_is_space(*cur)) {
6058 while (char_is_space(*++cur));
6059 goto obj_key_end;
6060 }
6061 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
6062 if (skip_trivia(&cur, eof, flg)) goto obj_key_end;
6063 if (cur == eof) goto fail_comment;
6064 }
6065 goto fail_character_obj_sep;
6066
6067obj_val_begin:
6068 if (*cur == '"') {
6069 val++;
6070 ctn_len++;
6071 if (likely(read_str(&cur, eof, flg, val, &msg))) goto obj_val_end;
6072 goto fail_string;
6073 }
6074 if (char_is_num(*cur)) {
6075 val++;
6076 ctn_len++;
6077 if (likely(read_num(&cur, pre, flg, val, &msg))) goto obj_val_end;
6078 goto fail_number;
6079 }
6080 if (*cur == '{') {
6081 cur++;
6082 goto obj_begin;
6083 }
6084 if (*cur == '[') {
6085 cur++;
6086 goto arr_begin;
6087 }
6088 if (*cur == 't') {
6089 val++;
6090 ctn_len++;
6091 if (likely(read_true(&cur, val))) goto obj_val_end;
6092 goto fail_literal_true;
6093 }
6094 if (*cur == 'f') {
6095 val++;
6096 ctn_len++;
6097 if (likely(read_false(&cur, val))) goto obj_val_end;
6098 goto fail_literal_false;
6099 }
6100 if (*cur == 'n') {
6101 val++;
6102 ctn_len++;
6103 if (likely(read_null(&cur, val))) goto obj_val_end;
6104 if (has_allow(INF_AND_NAN)) {
6105 if (read_nan(&cur, pre, flg, val)) goto obj_val_end;
6106 }
6107 goto fail_literal_null;
6108 }
6109 if (char_is_space(*cur)) {
6110 while (char_is_space(*++cur));
6111 goto obj_val_begin;
6112 }
6113 if (has_allow(INF_AND_NAN) &&
6114 (*cur == 'i' || *cur == 'I' || *cur == 'N')) {
6115 val++;
6116 ctn_len++;
6117 if (read_inf_or_nan(&cur, pre, flg, val)) goto obj_val_end;
6118 goto fail_character_val;
6119 }
6120 if (has_allow(SINGLE_QUOTED_STR) && *cur == '\'') {
6121 val++;
6122 ctn_len++;
6123 if (likely(read_str_sq(&cur, eof, flg, val, &msg))) goto obj_val_end;
6124 goto fail_string;
6125 }
6126 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
6127 if (skip_trivia(&cur, eof, flg)) goto obj_val_begin;
6128 if (cur == eof) goto fail_comment;
6129 }
6130 goto fail_character_val;
6131
6132obj_val_end:
6133 if (byte_match_2(cur, ",\n")) {
6134 cur += 2;
6135 goto obj_key_begin;
6136 }
6137 if (likely(*cur == ',')) {
6138 cur++;
6139 goto obj_key_begin;
6140 }
6141 if (likely(*cur == '}')) {
6142 cur++;
6143 goto obj_end;
6144 }
6145 if (char_is_space(*cur)) {
6146 while (char_is_space(*++cur));
6147 goto obj_val_end;
6148 }
6149 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
6150 if (skip_trivia(&cur, eof, flg)) goto obj_val_end;
6151 if (cur == eof) goto fail_comment;
6152 }
6153 goto fail_character_obj_end;
6154
6155obj_end:
6156#if YYJSON_READER_DEPTH_LIMIT
6157 container_depth--;
6158#endif
6159
6160 /* pop container */
6161 ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
6162 /* point to the next value */
6163 ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
6164 ctn->tag = (ctn_len << (YYJSON_TAG_BIT - 1)) | YYJSON_TYPE_OBJ;
6165 if (unlikely(ctn == ctn_parent)) goto doc_end;
6166 ctn = ctn_parent;
6167 ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
6168 if (*cur == '\n') cur++;
6169 if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
6170 goto obj_val_end;
6171 } else {
6172 goto arr_val_end;
6173 }
6174
6175doc_end:
6176 /* check invalid contents after json document */
6177 if (unlikely(cur < eof) && !has_flg(STOP_WHEN_DONE)) {
6178 while (char_is_space(*cur)) cur++;
6179 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
6180 if (!skip_trivia(&cur, eof, flg) && cur == eof) {
6181 goto fail_comment;
6182 }
6183 }
6184 if (unlikely(cur < eof)) goto fail_garbage;
6185 }
6186
6187 **pre = '\0';
6188 doc = (yyjson_doc *)val_hdr;
6189 doc->root = val_hdr + hdr_len;
6190 doc->alc = alc;
6191 doc->dat_read = (usize)(cur - hdr);
6192 doc->val_read = (usize)((val - doc->root) + 1);
6193 doc->str_pool = has_flg(INSITU) ? NULL : (char *)hdr;
6194 return doc;
6195
6196fail_string: return_err(cur, INVALID_STRING, msg);
6197fail_number: return_err(cur, INVALID_NUMBER, msg);
6198fail_alloc: return_err(cur, MEMORY_ALLOCATION, MSG_MALLOC);
6199fail_trailing_comma: return_err(cur, JSON_STRUCTURE, MSG_COMMA);
6200fail_literal_true: return_err(cur, LITERAL, MSG_CHAR_T);
6201fail_literal_false: return_err(cur, LITERAL, MSG_CHAR_F);
6202fail_literal_null: return_err(cur, LITERAL, MSG_CHAR_N);
6203fail_character_val: return_err(cur, UNEXPECTED_CHARACTER, MSG_CHAR);
6204fail_character_arr_end: return_err(cur, UNEXPECTED_CHARACTER, MSG_ARR_END);
6205fail_character_obj_key: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_KEY);
6206fail_character_obj_sep: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_SEP);
6207fail_character_obj_end: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_END);
6208fail_comment: return_err(cur, INVALID_COMMENT, MSG_COMMENT);
6209fail_garbage: return_err(cur, UNEXPECTED_CONTENT, MSG_GARBAGE);
6210fail_depth: return_err(cur, DEPTH, MSG_DEPTH);
6211
6212#undef val_incr
6213#undef return_err
6214}
6215
6216
6217
6218/*==============================================================================
6219 * MARK: - JSON Reader (Public)
6220 *============================================================================*/
6221
6222yyjson_doc *yyjson_read_opts(char *dat, usize len,
6223 yyjson_read_flag flg,
6224 const yyjson_alc *alc_ptr,
6225 yyjson_read_err *err) {
6226#define return_err(_pos, _code, _msg) do { \
6227 err->pos = (usize)(_pos); \
6228 err->msg = _msg; \
6229 err->code = YYJSON_READ_ERROR_##_code; \
6230 if (!has_flg(INSITU) && hdr) alc.free(alc.ctx, (void *)hdr); \
6231 return NULL; \
6232} while (false)
6233
6234 yyjson_read_err tmp_err;
6235 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
6236 yyjson_doc *doc;
6237 u8 *hdr = NULL, *eof, *cur;
6238
6239 /* validate input parameters */
6240 if (!err) err = &tmp_err;
6241 if (unlikely(!dat)) return_err(0, INVALID_PARAMETER, "input data is NULL");
6242 if (unlikely(!len)) return_err(0, INVALID_PARAMETER, "input length is 0");
6243
6244 /* add 4-byte zero padding for input data if necessary */
6245 if (has_flg(INSITU)) {
6246 hdr = (u8 *)dat;
6247 eof = (u8 *)dat + len;
6248 cur = (u8 *)dat;
6249 } else {
6250 if (unlikely(len >= USIZE_MAX - YYJSON_PADDING_SIZE)) {
6251 return_err(0, MEMORY_ALLOCATION, MSG_MALLOC);
6252 }
6253 hdr = (u8 *)alc.malloc(alc.ctx, len + YYJSON_PADDING_SIZE);
6254 if (unlikely(!hdr)) {
6255 return_err(0, MEMORY_ALLOCATION, MSG_MALLOC);
6256 }
6257 eof = hdr + len;
6258 cur = hdr;
6259 memcpy(hdr, dat, len);
6260 }
6261 memset(eof, 0, YYJSON_PADDING_SIZE);
6262
6263 if (has_allow(BOM)) {
6264 if (len >= 3 && is_utf8_bom(cur)) cur += 3;
6265 }
6266
6267 /* skip empty contents before json document */
6268 if (unlikely(!char_is_ctn(*cur))) {
6269 while (char_is_space(*cur)) cur++;
6270 if (unlikely(!char_is_ctn(*cur))) {
6271 if (has_allow(TRIVIA) && char_is_trivia(*cur)) {
6272 if (!skip_trivia(&cur, eof, flg) && cur == eof) {
6273 return_err(cur - hdr, INVALID_COMMENT, MSG_COMMENT);
6274 }
6275 }
6276 }
6277 if (unlikely(cur >= eof)) {
6278 return_err(0, EMPTY_CONTENT, "input data is empty");
6279 }
6280 }
6281
6282 /* read json document */
6283 if (likely(char_is_ctn(*cur))) {
6284 if (char_is_space(cur[1]) && char_is_space(cur[2])) {
6285 doc = read_root_pretty(hdr, cur, eof, alc, flg, err);
6286 } else {
6287 doc = read_root_minify(hdr, cur, eof, alc, flg, err);
6288 }
6289 } else {
6290 doc = read_root_single(hdr, cur, eof, alc, flg, err);
6291 }
6292
6293 /* check result */
6294 if (likely(doc)) {
6295 memset(err, 0, sizeof(yyjson_read_err));
6296 } else {
6297 /* RFC 8259: JSON text MUST be encoded using UTF-8 */
6298 if (err->pos == 0 && err->code != YYJSON_READ_ERROR_MEMORY_ALLOCATION) {
6299 if (is_utf8_bom(hdr)) err->msg = MSG_ERR_BOM;
6300 else if (len >= 4 && is_utf32_bom(hdr)) err->msg = MSG_ERR_UTF32;
6301 else if (len >= 2 && is_utf16_bom(hdr)) err->msg = MSG_ERR_UTF16;
6302 }
6303 if (!has_flg(INSITU)) alc.free(alc.ctx, hdr);
6304 }
6305 return doc;
6306
6307#undef return_err
6308}
6309
6310yyjson_doc *yyjson_read_file(const char *path,
6311 yyjson_read_flag flg,
6312 const yyjson_alc *alc_ptr,
6313 yyjson_read_err *err) {
6314#define return_err(_code, _msg) do { \
6315 err->pos = 0; \
6316 err->msg = _msg; \
6317 err->code = YYJSON_READ_ERROR_##_code; \
6318 return NULL; \
6319} while (false)
6320
6321 yyjson_read_err tmp_err;
6322 yyjson_doc *doc;
6323 FILE *file;
6324
6325 if (!err) err = &tmp_err;
6326 if (unlikely(!path)) return_err(INVALID_PARAMETER, "input path is NULL");
6327
6328 file = fopen_readonly(path);
6329 if (unlikely(!file)) return_err(FILE_OPEN, MSG_FREAD);
6330
6331 doc = yyjson_read_fp(file, flg, alc_ptr, err);
6332 fclose(file);
6333 return doc;
6334
6335#undef return_err
6336}
6337
6338yyjson_doc *yyjson_read_fp(FILE *file,
6339 yyjson_read_flag flg,
6340 const yyjson_alc *alc_ptr,
6341 yyjson_read_err *err) {
6342#define return_err(_code, _msg) do { \
6343 err->pos = 0; \
6344 err->msg = _msg; \
6345 err->code = YYJSON_READ_ERROR_##_code; \
6346 if (buf) alc.free(alc.ctx, buf); \
6347 return NULL; \
6348} while (false)
6349
6350 yyjson_read_err tmp_err;
6351 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
6352 yyjson_doc *doc;
6353
6354 long file_size = 0, file_pos;
6355 void *buf = NULL;
6356 usize buf_size = 0;
6357
6358 /* validate input parameters */
6359 if (!err) err = &tmp_err;
6360 if (unlikely(!file)) return_err(INVALID_PARAMETER, "input file is NULL");
6361
6362 /* get current position */
6363 file_pos = ftell(file);
6364 if (file_pos != -1) {
6365 /* get total file size, may fail */
6366 if (fseek(file, 0, SEEK_END) == 0) file_size = ftell(file);
6367 /* reset to original position, may fail */
6368 if (fseek(file, file_pos, SEEK_SET) != 0) file_size = 0;
6369 /* get file size from current postion to end */
6370 if (file_size > 0) file_size -= file_pos;
6371 }
6372
6373 /* read file */
6374 if (file_size > 0) {
6375 /* read the entire file in one call */
6376 buf_size = (usize)file_size + YYJSON_PADDING_SIZE;
6377 buf = alc.malloc(alc.ctx, buf_size);
6378 if (buf == NULL) {
6379 return_err(MEMORY_ALLOCATION, MSG_MALLOC);
6380 }
6381 if (fread_safe(buf, (usize)file_size, file) != (usize)file_size) {
6382 return_err(FILE_READ, MSG_FREAD);
6383 }
6384 } else {
6385 /* failed to get file size, read it as a stream */
6386 usize chunk_min = (usize)64;
6387 usize chunk_max = (usize)512 * 1024 * 1024;
6388 usize chunk_now = chunk_min;
6389 usize read_size;
6390 void *tmp;
6391
6392 buf_size = YYJSON_PADDING_SIZE;
6393 while (true) {
6394 if (buf_size + chunk_now < buf_size) { /* overflow */
6395 return_err(MEMORY_ALLOCATION, MSG_MALLOC);
6396 }
6397 buf_size += chunk_now;
6398 if (!buf) {
6399 buf = alc.malloc(alc.ctx, buf_size);
6400 if (!buf) return_err(MEMORY_ALLOCATION, MSG_MALLOC);
6401 } else {
6402 tmp = alc.realloc(alc.ctx, buf, buf_size - chunk_now, buf_size);
6403 if (!tmp) return_err(MEMORY_ALLOCATION, MSG_MALLOC);
6404 buf = tmp;
6405 }
6406 tmp = ((u8 *)buf) + buf_size - YYJSON_PADDING_SIZE - chunk_now;
6407 read_size = fread_safe(tmp, chunk_now, file);
6408 file_size += (long)read_size;
6409 if (read_size != chunk_now) break;
6410
6411 chunk_now *= 2;
6412 if (chunk_now > chunk_max) chunk_now = chunk_max;
6413 }
6414 }
6415
6416 /* read JSON */
6417 memset((u8 *)buf + file_size, 0, YYJSON_PADDING_SIZE);
6418 flg |= YYJSON_READ_INSITU;
6419 doc = yyjson_read_opts((char *)buf, (usize)file_size, flg, &alc, err);
6420 if (doc) {
6421 doc->str_pool = (char *)buf;
6422 return doc;
6423 } else {
6424 alc.free(alc.ctx, buf);
6425 return NULL;
6426 }
6427
6428#undef return_err
6429}
6430
6431const char *yyjson_read_number(const char *dat,
6432 yyjson_val *val,
6433 yyjson_read_flag flg,
6434 const yyjson_alc *alc,
6435 yyjson_read_err *err) {
6436#define return_err(_pos, _code, _msg) do { \
6437 err->pos = _pos > hdr ? (usize)(_pos - hdr) : 0; \
6438 err->msg = _msg; \
6439 err->code = YYJSON_READ_ERROR_##_code; \
6440 return NULL; \
6441} while (false)
6442
6443 u8 *hdr = constcast(u8 *)dat, *cur = hdr;
6444 u8 raw_end[1]; /* raw end for null-terminator */
6445 u8 *raw_ptr = raw_end;
6446 u8 **pre = &raw_ptr; /* previous raw end pointer */
6447 const char *msg;
6448 yyjson_read_err tmp_err;
6449
6450#if YYJSON_DISABLE_FAST_FP_CONV
6451 u8 buf[128];
6452 usize dat_len;
6453#endif
6454
6455 if (!err) err = &tmp_err;
6456 if (unlikely(!dat)) {
6457 return_err(cur, INVALID_PARAMETER, "input data is NULL");
6458 }
6459 if (unlikely(!val)) {
6460 return_err(cur, INVALID_PARAMETER, "output value is NULL");
6461 }
6462
6463#if YYJSON_DISABLE_FAST_FP_CONV
6464 if (!alc) alc = &YYJSON_DEFAULT_ALC;
6465 dat_len = strlen(dat);
6466 if (dat_len < sizeof(buf)) {
6467 memcpy(buf, dat, dat_len + 1);
6468 hdr = buf;
6469 cur = hdr;
6470 } else {
6471 hdr = (u8 *)alc->malloc(alc->ctx, dat_len + 1);
6472 cur = hdr;
6473 if (unlikely(!hdr)) {
6474 return_err(cur, MEMORY_ALLOCATION, MSG_MALLOC);
6475 }
6476 memcpy(hdr, dat, dat_len + 1);
6477 }
6478 hdr[dat_len] = 0;
6479#endif
6480
6481#if YYJSON_DISABLE_FAST_FP_CONV
6482 if (!read_num(&cur, pre, flg, val, &msg)) {
6483 if (dat_len >= sizeof(buf)) alc->free(alc->ctx, hdr);
6484 return_err(cur, INVALID_NUMBER, msg);
6485 }
6486 if (dat_len >= sizeof(buf)) alc->free(alc->ctx, hdr);
6487 if (yyjson_is_raw(val)) val->uni.str = dat;
6488 return dat + (cur - hdr);
6489#else
6490 if (!read_num(&cur, pre, flg, val, &msg)) {
6491 return_err(cur, INVALID_NUMBER, msg);
6492 }
6493 return (const char *)cur;
6494#endif
6495
6496#undef return_err
6497}
6498
6499
6500
6501/*==============================================================================
6502 * MARK: - Incremental JSON Reader (Public)
6503 *============================================================================*/
6504
6505#if !YYJSON_DISABLE_INCR_READER
6506
6507/* labels within yyjson_incr_read() to resume incremental parsing */
6508#define LABEL_doc_begin 0
6509#define LABEL_arr_val_begin 1
6510#define LABEL_arr_val_end 2
6511#define LABEL_obj_key_begin 3
6512#define LABEL_obj_key_end 4
6513#define LABEL_obj_val_begin 5
6514#define LABEL_obj_val_end 6
6515#define LABEL_doc_end 7
6516
6517/** State for incremental JSON reader, opaque in the API. */
6518struct yyjson_incr_state {
6519 u32 label; /* current parser goto label */
6520 yyjson_alc alc; /* allocator */
6521 yyjson_read_flag flg; /* read flags */
6522 u8 *hdr; /* JSON data header */
6523 u8 *cur; /* current position in JSON data */
6524 usize buf_len; /* total buffer length (without padding) */
6525 usize hdr_len; /* value count used by yyjson_doc */
6526 usize alc_len; /* value count allocated */
6527 usize ctn_len; /* the number of elements in current container */
6528 yyjson_val *val_hdr; /* the head of allocated values */
6529 yyjson_val *val_end; /* the end of allocated values */
6530 yyjson_val *val; /* current JSON value */
6531 yyjson_val *ctn; /* current container */
6532 u8 *str_con[2]; /* string parser incremental state */
6533};
6534
6535yyjson_incr_state *yyjson_incr_new(char *buf, size_t buf_len,
6536 yyjson_read_flag flg,
6537 const yyjson_alc *alc_ptr) {
6538 yyjson_incr_state *state = NULL;
6539 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
6540
6541 /* remove non-standard flags */
6542 flg &= ~YYJSON_READ_JSON5;
6543 flg &= ~YYJSON_READ_ALLOW_BOM;
6544 flg &= ~YYJSON_READ_ALLOW_INVALID_UNICODE;
6545
6546 if (unlikely(!buf)) return NULL;
6547 if (unlikely(buf_len >= USIZE_MAX - YYJSON_PADDING_SIZE)) return NULL;
6548 state = (yyjson_incr_state *)alc.malloc(alc.ctx, sizeof(*state));
6549 if (!state) return NULL;
6550 memset(state, 0, sizeof(yyjson_incr_state));
6551 state->alc = alc;
6552 state->flg = flg;
6553 state->buf_len = buf_len;
6554
6555 /* add 4-byte zero padding for input data if necessary */
6556 if (has_flg(INSITU)) {
6557 state->hdr = (u8 *)buf;
6558 } else {
6559 state->hdr = (u8 *)alc.malloc(alc.ctx, buf_len + YYJSON_PADDING_SIZE);
6560 if (unlikely(!state->hdr)) {
6561 alc.free(alc.ctx, state);
6562 return NULL;
6563 }
6564 memcpy(state->hdr, buf, buf_len);
6565 }
6566 memset(state->hdr + buf_len, 0, YYJSON_PADDING_SIZE);
6567 state->cur = state->hdr;
6568 state->label = LABEL_doc_begin;
6569 return state;
6570}
6571
6572void yyjson_incr_free(yyjson_incr_state *state) {
6573 if (state) {
6574 yyjson_alc alc = state->alc;
6575 memset(&state->alc, 0, sizeof(alc));
6576 if (state->val_hdr) {
6577 alc.free(alc.ctx, (void *)state->val_hdr);
6578 }
6579 if (state->hdr && !(state->flg & YYJSON_READ_INSITU)) {
6580 alc.free(alc.ctx, state->hdr);
6581 }
6582 alc.free(alc.ctx, state);
6583 }
6584}
6585
6586yyjson_doc *yyjson_incr_read(yyjson_incr_state *state, size_t len,
6587 yyjson_read_err *err) {
6588#define return_err_inv_param(_msg) do { \
6589 err->pos = 0; \
6590 err->msg = _msg; \
6591 err->code = YYJSON_READ_ERROR_INVALID_PARAMETER; \
6592 return NULL; \
6593} while (false)
6594
6595#define return_err(_pos, _code, _msg) do { \
6596 if (is_truncated_end(hdr, _pos, end, YYJSON_READ_ERROR_##_code, flg)) { \
6597 goto unexpected_end; \
6598 } else { \
6599 err->pos = (usize)(_pos - hdr); \
6600 err->code = YYJSON_READ_ERROR_##_code; \
6601 err->msg = _msg; \
6602 } \
6603 return NULL; \
6604} while (false)
6605
6606#define val_incr() do { \
6607 val++; \
6608 if (unlikely(val >= val_end)) { \
6609 usize alc_old = alc_len; \
6610 alc_len += alc_len / 2; \
6611 if ((sizeof(usize) < 8) && (alc_len >= alc_max)) goto fail_alloc; \
6612 val_tmp = (yyjson_val *)alc.realloc(alc.ctx, (void *)val_hdr, \
6613 alc_old * sizeof(yyjson_val), \
6614 alc_len * sizeof(yyjson_val)); \
6615 if ((!val_tmp)) goto fail_alloc; \
6616 val = val_tmp + (usize)(val - val_hdr); \
6617 ctn = val_tmp + (usize)(ctn - val_hdr); \
6618 state->val = val_tmp + (usize)(state->val - val_hdr); \
6619 state->val_hdr = val_hdr = val_tmp; \
6620 val_end = val_tmp + (alc_len - 2); \
6621 state->val_end = val_end; \
6622 } \
6623} while (false)
6624
6625 /* save position where it's possible to resume incremental parsing */
6626#define save_incr_state(_label) do { \
6627 state->label = LABEL_##_label; \
6628 state->cur = cur; \
6629 state->val = val; \
6630 state->ctn_len = ctn_len; \
6631 state->hdr_len = hdr_len; \
6632 if (unlikely(cur >= end)) goto unexpected_end; \
6633} while (false)
6634
6635#define check_maybe_truncated_number() do { \
6636 if (unlikely(cur >= end)) { \
6637 if (unlikely(cur > state->cur + INCR_NUM_MAX_LEN)) { \
6638 msg = "number too long"; \
6639 goto fail_number; \
6640 } \
6641 goto unexpected_end; \
6642 } \
6643} while (false)
6644
6645 u8 *hdr = NULL, *end = NULL, *cur = NULL;
6646 yyjson_read_flag flg;
6647 yyjson_alc alc;
6648 usize dat_len; /* data length in bytes, hint for allocator */
6649 usize hdr_len; /* value count used by yyjson_doc */
6650 usize alc_len; /* value count allocated */
6651 usize alc_max; /* maximum value count for allocator */
6652 usize ctn_len; /* the number of elements in current container */
6653 yyjson_val *val_hdr; /* the head of allocated values */
6654 yyjson_val *val_end; /* the end of allocated values */
6655 yyjson_val *val_tmp; /* temporary pointer for realloc */
6656 yyjson_val *val; /* current JSON value */
6657 yyjson_val *ctn; /* current container */
6658 yyjson_val *ctn_parent; /* parent of current container */
6659 yyjson_doc *doc; /* the JSON document, equals to val_hdr */
6660 const char *msg; /* error message */
6661
6662 yyjson_read_err tmp_err;
6663 u8 raw_end[1]; /* raw end for null-terminator */
6664 u8 *raw_ptr = raw_end;
6665 u8 **pre = &raw_ptr; /* previous raw end pointer */
6666 u8 **con = NULL; /* for incremental string parsing */
6667 u8 saved_end = '\0'; /* saved end char */
6668
6669#if YYJSON_READER_DEPTH_LIMIT
6670 u32 container_depth = 0; /* current array/object depth */
6671#endif
6672
6673 /* validate input parameters */
6674 if (!err) err = &tmp_err;
6675 if (unlikely(!state)) {
6676 return_err_inv_param("input state is NULL");
6677 }
6678 if (unlikely(!len)) {
6679 return_err_inv_param("input length is 0");
6680 }
6681 if (unlikely(len > state->buf_len)) {
6682 return_err_inv_param("length is greater than total input length");
6683 }
6684
6685 /* restore state saved from the previous call */
6686 hdr = state->hdr;
6687 end = state->hdr + len;
6688 cur = state->cur;
6689 flg = state->flg;
6690 alc = state->alc;
6691 ctn_len = state->ctn_len;
6692 hdr_len = state->hdr_len;
6693 alc_len = state->alc_len;
6694 val = state->val;
6695 val_hdr = state->val_hdr;
6696 val_end = state->val_end;
6697 ctn = state->ctn;
6698 con = state->str_con;
6699 alc_max = USIZE_MAX / sizeof(yyjson_val);
6700
6701 /* insert null terminator to make us stop at the specified end, even if
6702 the data contains more valid JSON */
6703 saved_end = *end;
6704 *end = '\0';
6705
6706 /* resume parsing from the last save point */
6707 switch (state->label) {
6708 case LABEL_doc_begin: goto doc_begin;
6709 case LABEL_arr_val_begin: goto arr_val_begin;
6710 case LABEL_arr_val_end: goto arr_val_end;
6711 case LABEL_obj_key_begin: goto obj_key_begin;
6712 case LABEL_obj_key_end: goto obj_key_end;
6713 case LABEL_obj_val_begin: goto obj_val_begin;
6714 case LABEL_obj_val_end: goto obj_val_end;
6715 case LABEL_doc_end: goto doc_end;
6716 default: return_err_inv_param("invalid incremental state");
6717 }
6718
6719doc_begin:
6720 /* skip empty contents before json document */
6721 if (unlikely(!char_is_ctn(*cur))) {
6722 while (char_is_space(*cur)) cur++;
6723 if (unlikely(cur >= end)) goto unexpected_end; /* input data is empty */
6724 }
6725
6726 /* allocate memory for document */
6727 if (!val_hdr) {
6728 hdr_len = sizeof(yyjson_doc) / sizeof(yyjson_val);
6729 hdr_len += (sizeof(yyjson_doc) % sizeof(yyjson_val)) > 0;
6730 if (likely(char_is_ctn(*cur))) {
6731 dat_len = has_flg(STOP_WHEN_DONE) ? 256 : state->buf_len;
6732 alc_len = hdr_len +
6733 (dat_len / YYJSON_READER_ESTIMATED_MINIFY_RATIO) + 4;
6734 alc_len = yyjson_min(alc_len, alc_max);
6735 } else {
6736 alc_len = hdr_len + 1; /* single value */
6737 }
6738 val_hdr = (yyjson_val *)alc.malloc(alc.ctx,
6739 alc_len * sizeof(yyjson_val));
6740 if (unlikely(!val_hdr)) goto fail_alloc;
6741 val_end = val_hdr + (alc_len - 2); /* padding for kv pair reading */
6742 val = val_hdr + hdr_len;
6743 ctn = val;
6744 ctn_len = 0;
6745 state->val_hdr = val_hdr;
6746 state->val_end = val_end;
6747 save_incr_state(doc_begin);
6748 }
6749
6750 /* read json document */
6751 if (*cur == '{') {
6752 cur++;
6753 ctn->tag = YYJSON_TYPE_OBJ;
6754 ctn->uni.ofs = 0;
6755 goto obj_key_begin;
6756 }
6757 if (*cur == '[') {
6758 cur++;
6759 ctn->tag = YYJSON_TYPE_ARR;
6760 ctn->uni.ofs = 0;
6761 goto arr_val_begin;
6762 }
6763 if (char_is_num(*cur)) {
6764 if (likely(read_num(&cur, pre, flg, val, &msg))) goto doc_end;
6765 goto fail_number;
6766 }
6767 if (*cur == '"') {
6768 if (likely(read_str_con(&cur, end, flg, val, &msg, con))) goto doc_end;
6769 goto fail_string;
6770 }
6771 if (*cur == 't') {
6772 if (likely(read_true(&cur, val))) goto doc_end;
6773 goto fail_literal_true;
6774 }
6775 if (*cur == 'f') {
6776 if (likely(read_false(&cur, val))) goto doc_end;
6777 goto fail_literal_false;
6778 }
6779 if (*cur == 'n') {
6780 if (likely(read_null(&cur, val))) goto doc_end;
6781 goto fail_literal_null;
6782 }
6783
6784 msg = "unexpected character, expected a valid root value";
6785 if (cur == hdr) {
6786 /* RFC 8259: JSON text MUST be encoded using UTF-8 */
6787 if (is_utf8_bom(hdr)) msg = MSG_ERR_BOM;
6788 else if (len >= 4 && is_utf32_bom(hdr)) msg = MSG_ERR_UTF32;
6789 else if (len >= 2 && is_utf16_bom(hdr)) msg = MSG_ERR_UTF16;
6790 }
6791 return_err(cur, UNEXPECTED_CHARACTER, msg);
6792
6793arr_begin:
6794#if YYJSON_READER_DEPTH_LIMIT
6795 container_depth++;
6796 if (unlikely(container_depth >= YYJSON_READER_DEPTH_LIMIT)) {
6797 goto fail_depth;
6798 }
6799#endif
6800
6801 /* save current container */
6802 ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
6803 (ctn->tag & YYJSON_TAG_MASK);
6804
6805 /* create a new array value, save parent container offset */
6806 val_incr();
6807 val->tag = YYJSON_TYPE_ARR;
6808 val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
6809
6810 /* push the new array value as current container */
6811 ctn = val;
6812 ctn_len = 0;
6813
6814arr_val_begin:
6815 save_incr_state(arr_val_begin);
6816arr_val_continue:
6817 if (*cur == '{') {
6818 cur++;
6819 goto obj_begin;
6820 }
6821 if (*cur == '[') {
6822 cur++;
6823 goto arr_begin;
6824 }
6825 if (char_is_num(*cur)) {
6826 val_incr();
6827 ctn_len++;
6828 if (likely(read_num(&cur, pre, flg, val, &msg))) goto arr_val_maybe_end;
6829 goto fail_number;
6830 }
6831 if (*cur == '"') {
6832 val_incr();
6833 ctn_len++;
6834 if (likely(read_str_con(&cur, end, flg, val, &msg, con)))
6835 goto arr_val_end;
6836 goto fail_string;
6837 }
6838 if (*cur == 't') {
6839 val_incr();
6840 ctn_len++;
6841 if (likely(read_true(&cur, val))) goto arr_val_end;
6842 goto fail_literal_true;
6843 }
6844 if (*cur == 'f') {
6845 val_incr();
6846 ctn_len++;
6847 if (likely(read_false(&cur, val))) goto arr_val_end;
6848 goto fail_literal_false;
6849 }
6850 if (*cur == 'n') {
6851 val_incr();
6852 ctn_len++;
6853 if (likely(read_null(&cur, val))) goto arr_val_end;
6854 goto fail_literal_null;
6855 }
6856 if (*cur == ']') {
6857 cur++;
6858 if (likely(ctn_len == 0)) goto arr_end;
6859 while (*cur != ',') cur--;
6860 goto fail_trailing_comma;
6861 }
6862 if (char_is_space(*cur)) {
6863 while (char_is_space(*++cur));
6864 goto arr_val_continue;
6865 }
6866 goto fail_character_val;
6867
6868arr_val_maybe_end:
6869 /* if incremental parsing stops in the middle of a number, it may continue
6870 with more digits, so arr val maybe didn't end yet */
6871 check_maybe_truncated_number();
6872
6873arr_val_end:
6874 save_incr_state(arr_val_end);
6875 if (*cur == ',') {
6876 cur++;
6877 goto arr_val_begin;
6878 }
6879 if (*cur == ']') {
6880 cur++;
6881 goto arr_end;
6882 }
6883 if (char_is_space(*cur)) {
6884 while (char_is_space(*++cur));
6885 goto arr_val_end;
6886 }
6887 goto fail_character_arr_end;
6888
6889arr_end:
6890#if YYJSON_READER_DEPTH_LIMIT
6891 container_depth--;
6892#endif
6893 /* get parent container */
6894 ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
6895
6896 /* save the next sibling value offset */
6897 ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
6898 ctn->tag = ((ctn_len) << YYJSON_TAG_BIT) | YYJSON_TYPE_ARR;
6899 if (unlikely(ctn == ctn_parent)) goto doc_end;
6900
6901 /* pop parent as current container */
6902 ctn = ctn_parent;
6903 ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
6904 if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
6905 goto obj_val_end;
6906 } else {
6907 goto arr_val_end;
6908 }
6909
6910obj_begin:
6911#if YYJSON_READER_DEPTH_LIMIT
6912 container_depth++;
6913 if (unlikely(container_depth >= YYJSON_READER_DEPTH_LIMIT)) {
6914 goto fail_depth;
6915 }
6916#endif
6917
6918 /* push container */
6919 ctn->tag = (((u64)ctn_len + 1) << YYJSON_TAG_BIT) |
6920 (ctn->tag & YYJSON_TAG_MASK);
6921 val_incr();
6922 val->tag = YYJSON_TYPE_OBJ;
6923 /* offset to the parent */
6924 val->uni.ofs = (usize)((u8 *)val - (u8 *)ctn);
6925 ctn = val;
6926 ctn_len = 0;
6927
6928obj_key_begin:
6929 save_incr_state(obj_key_begin);
6930obj_key_continue:
6931 if (likely(*cur == '"')) {
6932 val_incr();
6933 ctn_len++;
6934 if (likely(read_str_con(&cur, end, flg, val, &msg, con)))
6935 goto obj_key_end;
6936 goto fail_string;
6937 }
6938 if (likely(*cur == '}')) {
6939 cur++;
6940 if (likely(ctn_len == 0)) goto obj_end;
6941 while (*cur != ',') cur--;
6942 goto fail_trailing_comma;
6943 }
6944 if (char_is_space(*cur)) {
6945 while (char_is_space(*++cur));
6946 goto obj_key_continue;
6947 }
6948 goto fail_character_obj_key;
6949
6950obj_key_end:
6951 save_incr_state(obj_key_end);
6952 if (*cur == ':') {
6953 cur++;
6954 goto obj_val_begin;
6955 }
6956 if (char_is_space(*cur)) {
6957 while (char_is_space(*++cur));
6958 goto obj_key_end;
6959 }
6960 goto fail_character_obj_sep;
6961
6962obj_val_begin:
6963 save_incr_state(obj_val_begin);
6964obj_val_continue:
6965 if (*cur == '"') {
6966 val++;
6967 ctn_len++;
6968 if (likely(read_str_con(&cur, end, flg, val, &msg, con)))
6969 goto obj_val_end;
6970 goto fail_string;
6971 }
6972 if (char_is_num(*cur)) {
6973 val++;
6974 ctn_len++;
6975 if (likely(read_num(&cur, pre, flg, val, &msg))) goto obj_val_maybe_end;
6976 goto fail_number;
6977 }
6978 if (*cur == '{') {
6979 cur++;
6980 goto obj_begin;
6981 }
6982 if (*cur == '[') {
6983 cur++;
6984 goto arr_begin;
6985 }
6986 if (*cur == 't') {
6987 val++;
6988 ctn_len++;
6989 if (likely(read_true(&cur, val))) goto obj_val_end;
6990 goto fail_literal_true;
6991 }
6992 if (*cur == 'f') {
6993 val++;
6994 ctn_len++;
6995 if (likely(read_false(&cur, val))) goto obj_val_end;
6996 goto fail_literal_false;
6997 }
6998 if (*cur == 'n') {
6999 val++;
7000 ctn_len++;
7001 if (likely(read_null(&cur, val))) goto obj_val_end;
7002 goto fail_literal_null;
7003 }
7004 if (char_is_space(*cur)) {
7005 while (char_is_space(*++cur));
7006 goto obj_val_continue;
7007 }
7008 goto fail_character_val;
7009
7010obj_val_maybe_end:
7011 /* if incremental parsing stops in the middle of a number, it may continue
7012 with more digits, so obj val maybe didn't end yet */
7013 check_maybe_truncated_number();
7014
7015obj_val_end:
7016 save_incr_state(obj_val_end);
7017 if (likely(*cur == ',')) {
7018 cur++;
7019 goto obj_key_begin;
7020 }
7021 if (likely(*cur == '}')) {
7022 cur++;
7023 goto obj_end;
7024 }
7025 if (char_is_space(*cur)) {
7026 while (char_is_space(*++cur));
7027 goto obj_val_end;
7028 }
7029 goto fail_character_obj_end;
7030
7031obj_end:
7032#if YYJSON_READER_DEPTH_LIMIT
7033 container_depth--;
7034#endif
7035
7036 /* pop container */
7037 ctn_parent = (yyjson_val *)(void *)((u8 *)ctn - ctn->uni.ofs);
7038 /* point to the next value */
7039 ctn->uni.ofs = (usize)((u8 *)val - (u8 *)ctn) + sizeof(yyjson_val);
7040 ctn->tag = (ctn_len << (YYJSON_TAG_BIT - 1)) | YYJSON_TYPE_OBJ;
7041 if (unlikely(ctn == ctn_parent)) goto doc_end;
7042 ctn = ctn_parent;
7043 ctn_len = (usize)(ctn->tag >> YYJSON_TAG_BIT);
7044 if ((ctn->tag & YYJSON_TYPE_MASK) == YYJSON_TYPE_OBJ) {
7045 goto obj_val_end;
7046 } else {
7047 goto arr_val_end;
7048 }
7049
7050doc_end:
7051 /* check invalid contents after json document */
7052 if (unlikely(cur < end) && !has_flg(STOP_WHEN_DONE)) {
7053 save_incr_state(doc_end);
7054 while (char_is_space(*cur)) cur++;
7055 if (unlikely(cur < end)) goto fail_garbage;
7056 }
7057
7058 **pre = '\0';
7059 doc = (yyjson_doc *)val_hdr;
7060 doc->root = val_hdr + hdr_len;
7061 doc->alc = alc;
7062 doc->dat_read = (usize)(cur - hdr);
7063 doc->val_read = (usize)((val - doc->root) + 1);
7064 doc->str_pool = has_flg(INSITU) ? NULL : (char *)hdr;
7065 state->hdr = NULL;
7066 state->val_hdr = NULL;
7067 memset(err, 0, sizeof(yyjson_read_err));
7068 return doc;
7069
7070unexpected_end:
7071 err->pos = len;
7072 /* if no nore data, stop the incr read */
7073 if (unlikely(len >= state->buf_len)) {
7074 err->code = YYJSON_READ_ERROR_UNEXPECTED_END;
7075 err->msg = MSG_NOT_END;
7076 return NULL;
7077 }
7078 /* save parser state in extended error struct, in addition to what was
7079 * stored in the last save_incr_state */
7080 err->code = YYJSON_READ_ERROR_MORE;
7081 err->msg = "need more data";
7082 state->val_end = val_end;
7083 state->ctn = ctn;
7084 state->alc_len = alc_len;
7085 /* restore the end where we've inserted a null terminator */
7086 *end = saved_end;
7087 return NULL;
7088
7089fail_string: return_err(cur, INVALID_STRING, msg);
7090fail_number: return_err(cur, INVALID_NUMBER, msg);
7091fail_alloc: return_err(cur, MEMORY_ALLOCATION, MSG_MALLOC);
7092fail_trailing_comma: return_err(cur, JSON_STRUCTURE, MSG_COMMA);
7093fail_literal_true: return_err(cur, LITERAL, MSG_CHAR_T);
7094fail_literal_false: return_err(cur, LITERAL, MSG_CHAR_F);
7095fail_literal_null: return_err(cur, LITERAL, MSG_CHAR_N);
7096fail_character_val: return_err(cur, UNEXPECTED_CHARACTER, MSG_CHAR);
7097fail_character_arr_end: return_err(cur, UNEXPECTED_CHARACTER, MSG_ARR_END);
7098fail_character_obj_key: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_KEY);
7099fail_character_obj_sep: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_SEP);
7100fail_character_obj_end: return_err(cur, UNEXPECTED_CHARACTER, MSG_OBJ_END);
7101fail_garbage: return_err(cur, UNEXPECTED_CONTENT, MSG_GARBAGE);
7102fail_depth: return_err(cur, DEPTH, MSG_DEPTH);
7103
7104#undef val_incr
7105#undef return_err
7106#undef return_err_inv_param
7107#undef save_incr_state
7108#undef check_maybe_truncated_number
7109}
7110
7111#endif /* YYJSON_DISABLE_INCR_READER */
7112
7113#undef has_flg
7114#undef has_allow
7115#endif /* YYJSON_DISABLE_READER */
7116
7117
7118
7119#if !YYJSON_DISABLE_WRITER /* writer begin */
7120
7121/* Check write flag, avoids `always false` warning when disabled. */
7122#define has_flg(_flg) unlikely(has_wflag(flg, YYJSON_WRITE_##_flg, 0))
7123#define has_allow(_flg) unlikely(has_wflag(flg, YYJSON_WRITE_ALLOW_##_flg, 1))
7124static_inline bool has_wflag(yyjson_write_flag flg, yyjson_write_flag chk,
7125 bool non_standard) {
7126#if YYJSON_DISABLE_NON_STANDARD
7127 if (non_standard) return false;
7128#endif
7129 return (flg & chk) != 0;
7130}
7131
7132/*==============================================================================
7133 * MARK: - Integer Writer (Private)
7134 *
7135 * The maximum value of uint32_t is 4294967295 (10 digits),
7136 * these digits are named as 'aabbccddee' here.
7137 *
7138 * Although most compilers may convert the "division by constant value" into
7139 * "multiply and shift", manual conversion can still help some compilers
7140 * generate fewer and better instructions.
7141 *
7142 * Reference:
7143 * Division by Invariant Integers using Multiplication, 1994.
7144 * https://gmplib.org/~tege/divcnst-pldi94.pdf
7145 * Improved division by invariant integers, 2011.
7146 * https://gmplib.org/~tege/division-paper.pdf
7147 *============================================================================*/
7148
7149/** Digit table from 00 to 99. */
7150yyjson_align(2)
7151static const char digit_table[200] = {
7152 '0', '0', '0', '1', '0', '2', '0', '3', '0', '4',
7153 '0', '5', '0', '6', '0', '7', '0', '8', '0', '9',
7154 '1', '0', '1', '1', '1', '2', '1', '3', '1', '4',
7155 '1', '5', '1', '6', '1', '7', '1', '8', '1', '9',
7156 '2', '0', '2', '1', '2', '2', '2', '3', '2', '4',
7157 '2', '5', '2', '6', '2', '7', '2', '8', '2', '9',
7158 '3', '0', '3', '1', '3', '2', '3', '3', '3', '4',
7159 '3', '5', '3', '6', '3', '7', '3', '8', '3', '9',
7160 '4', '0', '4', '1', '4', '2', '4', '3', '4', '4',
7161 '4', '5', '4', '6', '4', '7', '4', '8', '4', '9',
7162 '5', '0', '5', '1', '5', '2', '5', '3', '5', '4',
7163 '5', '5', '5', '6', '5', '7', '5', '8', '5', '9',
7164 '6', '0', '6', '1', '6', '2', '6', '3', '6', '4',
7165 '6', '5', '6', '6', '6', '7', '6', '8', '6', '9',
7166 '7', '0', '7', '1', '7', '2', '7', '3', '7', '4',
7167 '7', '5', '7', '6', '7', '7', '7', '8', '7', '9',
7168 '8', '0', '8', '1', '8', '2', '8', '3', '8', '4',
7169 '8', '5', '8', '6', '8', '7', '8', '8', '8', '9',
7170 '9', '0', '9', '1', '9', '2', '9', '3', '9', '4',
7171 '9', '5', '9', '6', '9', '7', '9', '8', '9', '9'
7172};
7173
7174static_inline u8 *write_u32_len_8(u32 val, u8 *buf) {
7175 u32 aa, bb, cc, dd, aabb, ccdd; /* 8 digits: aabbccdd */
7176 aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */
7177 ccdd = val - aabb * 10000; /* (val % 10000) */
7178 aa = (aabb * 5243) >> 19; /* (aabb / 100) */
7179 cc = (ccdd * 5243) >> 19; /* (ccdd / 100) */
7180 bb = aabb - aa * 100; /* (aabb % 100) */
7181 dd = ccdd - cc * 100; /* (ccdd % 100) */
7182 byte_copy_2(buf + 0, digit_table + aa * 2);
7183 byte_copy_2(buf + 2, digit_table + bb * 2);
7184 byte_copy_2(buf + 4, digit_table + cc * 2);
7185 byte_copy_2(buf + 6, digit_table + dd * 2);
7186 return buf + 8;
7187}
7188
7189static_inline u8 *write_u32_len_4(u32 val, u8 *buf) {
7190 u32 aa, bb; /* 4 digits: aabb */
7191 aa = (val * 5243) >> 19; /* (val / 100) */
7192 bb = val - aa * 100; /* (val % 100) */
7193 byte_copy_2(buf + 0, digit_table + aa * 2);
7194 byte_copy_2(buf + 2, digit_table + bb * 2);
7195 return buf + 4;
7196}
7197
7198static_inline u8 *write_u32_len_1_to_8(u32 val, u8 *buf) {
7199 u32 aa, bb, cc, dd, aabb, bbcc, ccdd, lz;
7200
7201 if (val < 100) { /* 1-2 digits: aa */
7202 lz = val < 10; /* leading zero: 0 or 1 */
7203 byte_copy_2(buf + 0, digit_table + val * 2 + lz);
7204 buf -= lz;
7205 return buf + 2;
7206
7207 } else if (val < 10000) { /* 3-4 digits: aabb */
7208 aa = (val * 5243) >> 19; /* (val / 100) */
7209 bb = val - aa * 100; /* (val % 100) */
7210 lz = aa < 10; /* leading zero: 0 or 1 */
7211 byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
7212 buf -= lz;
7213 byte_copy_2(buf + 2, digit_table + bb * 2);
7214 return buf + 4;
7215
7216 } else if (val < 1000000) { /* 5-6 digits: aabbcc */
7217 aa = (u32)(((u64)val * 429497) >> 32); /* (val / 10000) */
7218 bbcc = val - aa * 10000; /* (val % 10000) */
7219 bb = (bbcc * 5243) >> 19; /* (bbcc / 100) */
7220 cc = bbcc - bb * 100; /* (bbcc % 100) */
7221 lz = aa < 10; /* leading zero: 0 or 1 */
7222 byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
7223 buf -= lz;
7224 byte_copy_2(buf + 2, digit_table + bb * 2);
7225 byte_copy_2(buf + 4, digit_table + cc * 2);
7226 return buf + 6;
7227
7228 } else { /* 7-8 digits: aabbccdd */
7229 aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */
7230 ccdd = val - aabb * 10000; /* (val % 10000) */
7231 aa = (aabb * 5243) >> 19; /* (aabb / 100) */
7232 cc = (ccdd * 5243) >> 19; /* (ccdd / 100) */
7233 bb = aabb - aa * 100; /* (aabb % 100) */
7234 dd = ccdd - cc * 100; /* (ccdd % 100) */
7235 lz = aa < 10; /* leading zero: 0 or 1 */
7236 byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
7237 buf -= lz;
7238 byte_copy_2(buf + 2, digit_table + bb * 2);
7239 byte_copy_2(buf + 4, digit_table + cc * 2);
7240 byte_copy_2(buf + 6, digit_table + dd * 2);
7241 return buf + 8;
7242 }
7243}
7244
7245static_inline u8 *write_u32_len_5_to_8(u32 val, u8 *buf) {
7246 u32 aa, bb, cc, dd, aabb, bbcc, ccdd, lz;
7247
7248 if (val < 1000000) { /* 5-6 digits: aabbcc */
7249 aa = (u32)(((u64)val * 429497) >> 32); /* (val / 10000) */
7250 bbcc = val - aa * 10000; /* (val % 10000) */
7251 bb = (bbcc * 5243) >> 19; /* (bbcc / 100) */
7252 cc = bbcc - bb * 100; /* (bbcc % 100) */
7253 lz = aa < 10; /* leading zero: 0 or 1 */
7254 byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
7255 buf -= lz;
7256 byte_copy_2(buf + 2, digit_table + bb * 2);
7257 byte_copy_2(buf + 4, digit_table + cc * 2);
7258 return buf + 6;
7259
7260 } else { /* 7-8 digits: aabbccdd */
7261 aabb = (u32)(((u64)val * 109951163) >> 40); /* (val / 10000) */
7262 ccdd = val - aabb * 10000; /* (val % 10000) */
7263 aa = (aabb * 5243) >> 19; /* (aabb / 100) */
7264 cc = (ccdd * 5243) >> 19; /* (ccdd / 100) */
7265 bb = aabb - aa * 100; /* (aabb % 100) */
7266 dd = ccdd - cc * 100; /* (ccdd % 100) */
7267 lz = aa < 10; /* leading zero: 0 or 1 */
7268 byte_copy_2(buf + 0, digit_table + aa * 2 + lz);
7269 buf -= lz;
7270 byte_copy_2(buf + 2, digit_table + bb * 2);
7271 byte_copy_2(buf + 4, digit_table + cc * 2);
7272 byte_copy_2(buf + 6, digit_table + dd * 2);
7273 return buf + 8;
7274 }
7275}
7276
7277static_inline u8 *write_u64(u64 val, u8 *buf) {
7278 u64 tmp, hgh;
7279 u32 mid, low;
7280
7281 if (val < 100000000) { /* 1-8 digits */
7282 buf = write_u32_len_1_to_8((u32)val, buf);
7283 return buf;
7284
7285 } else if (val < (u64)100000000 * 100000000) { /* 9-16 digits */
7286 hgh = val / 100000000; /* (val / 100000000) */
7287 low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
7288 buf = write_u32_len_1_to_8((u32)hgh, buf);
7289 buf = write_u32_len_8(low, buf);
7290 return buf;
7291
7292 } else { /* 17-20 digits */
7293 tmp = val / 100000000; /* (val / 100000000) */
7294 low = (u32)(val - tmp * 100000000); /* (val % 100000000) */
7295 hgh = (u32)(tmp / 10000); /* (tmp / 10000) */
7296 mid = (u32)(tmp - hgh * 10000); /* (tmp % 10000) */
7297 buf = write_u32_len_5_to_8((u32)hgh, buf);
7298 buf = write_u32_len_4(mid, buf);
7299 buf = write_u32_len_8(low, buf);
7300 return buf;
7301 }
7302}
7303
7304
7305
7306/*==============================================================================
7307 * MARK: - Number Writer (Private)
7308 *============================================================================*/
7309
7310#if !YYJSON_DISABLE_FAST_FP_CONV /* FP_WRITER */
7311
7312/** Trailing zero count table for number 0 to 99.
7313 (generate with misc/make_tables.c) */
7314static const u8 dec_trailing_zero_table[] = {
7315 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7316 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7317 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7318 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7319 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7320 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7321 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7322 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7323 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
7324 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
7325};
7326
7327static_inline u8 *write_u64_len_1_to_16(u64 val, u8 *buf) {
7328 u64 hgh;
7329 u32 low;
7330 if (val < 100000000) { /* 1-8 digits */
7331 buf = write_u32_len_1_to_8((u32)val, buf);
7332 return buf;
7333 } else { /* 9-16 digits */
7334 hgh = val / 100000000; /* (val / 100000000) */
7335 low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
7336 buf = write_u32_len_1_to_8((u32)hgh, buf);
7337 buf = write_u32_len_8(low, buf);
7338 return buf;
7339 }
7340}
7341
7342static_inline u8 *write_u64_len_1_to_17(u64 val, u8 *buf) {
7343 u64 hgh;
7344 u32 mid, low, one;
7345 if (val >= (u64)100000000 * 10000000) { /* len: 16 to 17 */
7346 hgh = val / 100000000; /* (val / 100000000) */
7347 low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
7348 one = (u32)(hgh / 100000000); /* (hgh / 100000000) */
7349 mid = (u32)(hgh - (u64)one * 100000000); /* (hgh % 100000000) */
7350 *buf = (u8)((u8)one + (u8)'0');
7351 buf += one > 0;
7352 buf = write_u32_len_8(mid, buf);
7353 buf = write_u32_len_8(low, buf);
7354 return buf;
7355 } else if (val >= (u64)100000000){ /* len: 9 to 15 */
7356 hgh = val / 100000000; /* (val / 100000000) */
7357 low = (u32)(val - hgh * 100000000); /* (val % 100000000) */
7358 buf = write_u32_len_1_to_8((u32)hgh, buf);
7359 buf = write_u32_len_8(low, buf);
7360 return buf;
7361 } else { /* len: 1 to 8 */
7362 buf = write_u32_len_1_to_8((u32)val, buf);
7363 return buf;
7364 }
7365}
7366
7367/**
7368 Write an unsigned integer with a length of 7 to 9 with trailing zero trimmed.
7369 These digits are named as "abbccddee" here.
7370 For example, input 123456000, output "123456".
7371 */
7372static_inline u8 *write_u32_len_7_to_9_trim(u32 val, u8 *buf) {
7373 bool lz;
7374 u32 tz, tz1, tz2;
7375
7376 u32 abbcc = val / 10000; /* (abbccddee / 10000) */
7377 u32 ddee = val - abbcc * 10000; /* (abbccddee % 10000) */
7378 u32 abb = (u32)(((u64)abbcc * 167773) >> 24); /* (abbcc / 100) */
7379 u32 a = (abb * 41) >> 12; /* (abb / 100) */
7380 u32 bb = abb - a * 100; /* (abb % 100) */
7381 u32 cc = abbcc - abb * 100; /* (abbcc % 100) */
7382
7383 /* write abbcc */
7384 buf[0] = (u8)(a + '0');
7385 buf += a > 0;
7386 lz = bb < 10 && a == 0;
7387 byte_copy_2(buf + 0, digit_table + bb * 2 + lz);
7388 buf -= lz;
7389 byte_copy_2(buf + 2, digit_table + cc * 2);
7390
7391 if (ddee) {
7392 u32 dd = (ddee * 5243) >> 19; /* (ddee / 100) */
7393 u32 ee = ddee - dd * 100; /* (ddee % 100) */
7394 byte_copy_2(buf + 4, digit_table + dd * 2);
7395 byte_copy_2(buf + 6, digit_table + ee * 2);
7396 tz1 = dec_trailing_zero_table[dd];
7397 tz2 = dec_trailing_zero_table[ee];
7398 tz = ee ? tz2 : (tz1 + 2);
7399 buf += 8 - tz;
7400 return buf;
7401 } else {
7402 tz1 = dec_trailing_zero_table[bb];
7403 tz2 = dec_trailing_zero_table[cc];
7404 tz = cc ? tz2 : (tz1 + tz2);
7405 buf += 4 - tz;
7406 return buf;
7407 }
7408}
7409
7410/**
7411 Write an unsigned integer with a length of 16 or 17 with trailing zero trimmed.
7412 These digits are named as "abbccddeeffgghhii" here.
7413 For example, input 1234567890123000, output "1234567890123".
7414 */
7415static_inline u8 *write_u64_len_16_to_17_trim(u64 val, u8 *buf) {
7416 u32 tz, tz1, tz2;
7417
7418 u32 abbccddee = (u32)(val / 100000000);
7419 u32 ffgghhii = (u32)(val - (u64)abbccddee * 100000000);
7420 u32 abbcc = abbccddee / 10000;
7421 u32 ddee = abbccddee - abbcc * 10000;
7422 u32 abb = (u32)(((u64)abbcc * 167773) >> 24); /* (abbcc / 100) */
7423 u32 a = (abb * 41) >> 12; /* (abb / 100) */
7424 u32 bb = abb - a * 100; /* (abb % 100) */
7425 u32 cc = abbcc - abb * 100; /* (abbcc % 100) */
7426 buf[0] = (u8)(a + '0');
7427 buf += a > 0;
7428 byte_copy_2(buf + 0, digit_table + bb * 2);
7429 byte_copy_2(buf + 2, digit_table + cc * 2);
7430
7431 if (ffgghhii) {
7432 u32 dd = (ddee * 5243) >> 19; /* (ddee / 100) */
7433 u32 ee = ddee - dd * 100; /* (ddee % 100) */
7434 u32 ffgg = (u32)(((u64)ffgghhii * 109951163) >> 40); /* (val / 10000) */
7435 u32 hhii = ffgghhii - ffgg * 10000; /* (val % 10000) */
7436 u32 ff = (ffgg * 5243) >> 19; /* (aabb / 100) */
7437 u32 gg = ffgg - ff * 100; /* (aabb % 100) */
7438 byte_copy_2(buf + 4, digit_table + dd * 2);
7439 byte_copy_2(buf + 6, digit_table + ee * 2);
7440 byte_copy_2(buf + 8, digit_table + ff * 2);
7441 byte_copy_2(buf + 10, digit_table + gg * 2);
7442 if (hhii) {
7443 u32 hh = (hhii * 5243) >> 19; /* (ccdd / 100) */
7444 u32 ii = hhii - hh * 100; /* (ccdd % 100) */
7445 byte_copy_2(buf + 12, digit_table + hh * 2);
7446 byte_copy_2(buf + 14, digit_table + ii * 2);
7447 tz1 = dec_trailing_zero_table[hh];
7448 tz2 = dec_trailing_zero_table[ii];
7449 tz = ii ? tz2 : (tz1 + 2);
7450 return buf + 16 - tz;
7451 } else {
7452 tz1 = dec_trailing_zero_table[ff];
7453 tz2 = dec_trailing_zero_table[gg];
7454 tz = gg ? tz2 : (tz1 + 2);
7455 return buf + 12 - tz;
7456 }
7457 } else {
7458 if (ddee) {
7459 u32 dd = (ddee * 5243) >> 19; /* (ddee / 100) */
7460 u32 ee = ddee - dd * 100; /* (ddee % 100) */
7461 byte_copy_2(buf + 4, digit_table + dd * 2);
7462 byte_copy_2(buf + 6, digit_table + ee * 2);
7463 tz1 = dec_trailing_zero_table[dd];
7464 tz2 = dec_trailing_zero_table[ee];
7465 tz = ee ? tz2 : (tz1 + 2);
7466 return buf + 8 - tz;
7467 } else {
7468 tz1 = dec_trailing_zero_table[bb];
7469 tz2 = dec_trailing_zero_table[cc];
7470 tz = cc ? tz2 : (tz1 + tz2);
7471 return buf + 4 - tz;
7472 }
7473 }
7474}
7475
7476/** Write exponent part in range `e-45` to `e38`. */
7477static_inline u8 *write_f32_exp(i32 exp, u8 *buf) {
7478 bool lz;
7479 byte_copy_2(buf, "e-");
7480 buf += 2 - (exp >= 0);
7481 exp = exp < 0 ? -exp : exp;
7482 lz = exp < 10;
7483 byte_copy_2(buf + 0, digit_table + (u32)exp * 2 + lz);
7484 return buf + 2 - lz;
7485}
7486
7487/** Write exponent part in range `e-324` to `e308`. */
7488static_inline u8 *write_f64_exp(i32 exp, u8 *buf) {
7489 byte_copy_2(buf, "e-");
7490 buf += 2 - (exp >= 0);
7491 exp = exp < 0 ? -exp : exp;
7492 if (exp < 100) {
7493 bool lz = exp < 10;
7494 byte_copy_2(buf + 0, digit_table + (u32)exp * 2 + lz);
7495 return buf + 2 - lz;
7496 } else {
7497 u32 hi = ((u32)exp * 656) >> 16; /* exp / 100 */
7498 u32 lo = (u32)exp - hi * 100; /* exp % 100 */
7499 buf[0] = (u8)((u8)hi + (u8)'0');
7500 byte_copy_2(buf + 1, digit_table + lo * 2);
7501 return buf + 3;
7502 }
7503}
7504
7505/** Magic number for fast `divide by power of 10`. */
7506typedef struct {
7507 u64 p10, mul;
7508 u32 shr1, shr2;
7509} div_pow10_magic;
7510
7511/** Generated with llvm, see https://github.com/llvm/llvm-project/
7512 blob/main/llvm/lib/Support/DivisionByConstantInfo.cpp */
7513static const div_pow10_magic div_pow10_table[] = {
7514 { U64(0x00000000, 0x00000001), U64(0x00000000, 0x00000000), 0, 0 },
7515 { U64(0x00000000, 0x0000000A), U64(0xCCCCCCCC, 0xCCCCCCCD), 0, 3 },
7516 { U64(0x00000000, 0x00000064), U64(0x28F5C28F, 0x5C28F5C3), 2, 2 },
7517 { U64(0x00000000, 0x000003E8), U64(0x20C49BA5, 0xE353F7CF), 3, 4 },
7518 { U64(0x00000000, 0x00002710), U64(0x346DC5D6, 0x3886594B), 0, 11 },
7519 { U64(0x00000000, 0x000186A0), U64(0x0A7C5AC4, 0x71B47843), 5, 7 },
7520 { U64(0x00000000, 0x000F4240), U64(0x431BDE82, 0xD7B634DB), 0, 18 },
7521 { U64(0x00000000, 0x00989680), U64(0xD6BF94D5, 0xE57A42BD), 0, 23 },
7522 { U64(0x00000000, 0x05F5E100), U64(0xABCC7711, 0x8461CEFD), 0, 26 },
7523 { U64(0x00000000, 0x3B9ACA00), U64(0x0044B82F, 0xA09B5A53), 9, 11 },
7524 { U64(0x00000002, 0x540BE400), U64(0xDBE6FECE, 0xBDEDD5BF), 0, 33 },
7525 { U64(0x00000017, 0x4876E800), U64(0xAFEBFF0B, 0xCB24AAFF), 0, 36 },
7526 { U64(0x000000E8, 0xD4A51000), U64(0x232F3302, 0x5BD42233), 0, 37 },
7527 { U64(0x00000918, 0x4E72A000), U64(0x384B84D0, 0x92ED0385), 0, 41 },
7528 { U64(0x00005AF3, 0x107A4000), U64(0x0B424DC3, 0x5095CD81), 0, 42 },
7529 { U64(0x00038D7E, 0xA4C68000), U64(0x00024075, 0xF3DCEAC3), 15, 20 },
7530 { U64(0x002386F2, 0x6FC10000), U64(0x39A5652F, 0xB1137857), 0, 51 },
7531 { U64(0x01634578, 0x5D8A0000), U64(0x00005C3B, 0xD5191B53), 17, 22 },
7532 { U64(0x0DE0B6B3, 0xA7640000), U64(0x000049C9, 0x7747490F), 18, 24 },
7533 { U64(0x8AC72304, 0x89E80000), U64(0x760F253E, 0xDB4AB0d3), 0, 62 },
7534};
7535
7536/** Divide a number by power of 10. */
7537static_inline void div_pow10(u64 num, u32 exp, u64 *div, u64 *mod, u64 *p10) {
7538 u64 hi, lo;
7539 div_pow10_magic m = div_pow10_table[exp];
7540 u128_mul(num >> m.shr1, m.mul, &hi, &lo);
7541 *div = hi >> m.shr2;
7542 *mod = num - (*div * m.p10);
7543 *p10 = m.p10;
7544}
7545
7546/** Multiplies 64-bit integer and returns highest 64-bit rounded value. */
7547static_inline u32 u64_round_to_odd(u64 u, u32 cp) {
7548 u64 hi, lo;
7549 u32 y_hi, y_lo;
7550 u128_mul(cp, u, &hi, &lo);
7551 y_hi = (u32)hi;
7552 y_lo = (u32)(lo >> 32);
7553 return y_hi | (y_lo > 1);
7554}
7555
7556/** Multiplies 128-bit integer and returns highest 64-bit rounded value. */
7557static_inline u64 u128_round_to_odd(u64 hi, u64 lo, u64 cp) {
7558 u64 x_hi, x_lo, y_hi, y_lo;
7559 u128_mul(cp, lo, &x_hi, &x_lo);
7560 u128_mul_add(cp, hi, x_hi, &y_hi, &y_lo);
7561 return y_hi | (y_lo > 1);
7562}
7563
7564/** Convert f32 from binary to decimal (shortest but may have trailing zeros).
7565 The input should not be 0, inf or nan. */
7566static_inline void f32_bin_to_dec(u32 sig_raw, u32 exp_raw,
7567 u32 sig_bin, i32 exp_bin,
7568 u32 *sig_dec, i32 *exp_dec) {
7569
7570 bool is_even, irregular, round_up, trim;
7571 bool u0_inside, u1_inside, w0_inside, w1_inside;
7572 u64 p10_hi, p10_lo, hi, lo;
7573 u32 s, sp, cb, cbl, cbr, vb, vbl, vbr, upper, lower, mid;
7574 i32 k, h;
7575
7576 /* Fast path, see f64_bin_to_dec(). */
7577 while (likely(sig_raw)) {
7578 u32 mod, dec, add_1, add_10, s_hi, s_lo;
7579 u32 c, half_ulp, t0, t1;
7580
7581 /* k = floor(exp_bin * log10(2)); */
7582 /* h = exp_bin + floor(log2(10) * -k); (h = 0/1/2/3) */
7583 k = (i32)(exp_bin * 315653) >> 20;
7584 h = exp_bin + ((-k * 217707) >> 16);
7585 pow10_table_get_sig(-k, &p10_hi, &p10_lo);
7586
7587 /* sig_bin << (1/2/3/4) */
7588 cb = sig_bin << (h + 1);
7589 u128_mul(cb, p10_hi, &hi, &lo);
7590 s_hi = (u32)(hi);
7591 s_lo = (u32)(lo >> 32);
7592 mod = s_hi % 10;
7593 dec = s_hi - mod;
7594
7595 /* right shift 4 to fit in u32 */
7596 c = (mod << (32 - 4)) | (s_lo >> 4);
7597 half_ulp = (u32)(p10_hi >> (32 + 4 - h));
7598
7599 /* check w1, u0, w0 range */
7600 w1_inside = (s_lo >= ((u32)1 << 31));
7601 if (unlikely(s_lo == ((u32)1 << 31))) break;
7602 u0_inside = (half_ulp >= c);
7603 if (unlikely(half_ulp == c)) break;
7604 t0 = (u32)10 << (32 - 4);
7605 t1 = c + half_ulp;
7606 w0_inside = (t1 >= t0);
7607 if (unlikely(t0 - t1 <= (u32)1)) break;
7608
7609 trim = (u0_inside | w0_inside);
7610 add_10 = (w0_inside ? 10 : 0);
7611 add_1 = mod + w1_inside;
7612 *sig_dec = dec + (trim ? add_10 : add_1);
7613 *exp_dec = k;
7614 return;
7615 }
7616
7617 /* Schubfach algorithm, see f64_bin_to_dec(). */
7618 irregular = (sig_raw == 0 && exp_raw > 1);
7619 is_even = !(sig_bin & 1);
7620 cbl = 4 * sig_bin - 2 + irregular;
7621 cb = 4 * sig_bin;
7622 cbr = 4 * sig_bin + 2;
7623
7624 /* k = floor(exp_bin * log10(2) + (irregular ? log10(3.0 / 4.0) : 0)); */
7625 /* h = exp_bin + floor(log2(10) * -k) + 1; (h = 1/2/3/4) */
7626 k = (i32)(exp_bin * 315653 - (irregular ? 131237 : 0)) >> 20;
7627 h = exp_bin + ((-k * 217707) >> 16) + 1;
7628 pow10_table_get_sig(-k, &p10_hi, &p10_lo);
7629 p10_hi += 1;
7630
7631 vbl = u64_round_to_odd(p10_hi, cbl << h);
7632 vb = u64_round_to_odd(p10_hi, cb << h);
7633 vbr = u64_round_to_odd(p10_hi, cbr << h);
7634 lower = vbl + !is_even;
7635 upper = vbr - !is_even;
7636
7637 s = vb / 4;
7638 if (s >= 10) {
7639 sp = s / 10;
7640 u0_inside = (lower <= 40 * sp);
7641 w0_inside = (upper >= 40 * sp + 40);
7642 if (u0_inside != w0_inside) {
7643 *sig_dec = sp * 10 + (w0_inside ? 10 : 0);
7644 *exp_dec = k;
7645 return;
7646 }
7647 }
7648 u1_inside = (lower <= 4 * s);
7649 w1_inside = (upper >= 4 * s + 4);
7650 mid = 4 * s + 2;
7651 round_up = (vb > mid) || (vb == mid && (s & 1) != 0);
7652 *sig_dec = s + ((u1_inside != w1_inside) ? w1_inside : round_up);
7653 *exp_dec = k;
7654}
7655
7656/** Convert f64 from binary to decimal (shortest but may have trailing zeros).
7657 The input should not be 0, inf or nan. */
7658static_inline void f64_bin_to_dec(u64 sig_raw, u32 exp_raw,
7659 u64 sig_bin, i32 exp_bin,
7660 u64 *sig_dec, i32 *exp_dec) {
7661
7662 bool is_even, irregular, round_up, trim;
7663 bool u0_inside, u1_inside, w0_inside, w1_inside;
7664 u64 s, sp, cb, cbl, cbr, vb, vbl, vbr, p10_hi, p10_lo, upper, lower, mid;
7665 i32 k, h;
7666
7667 /*
7668 Fast path:
7669 For regular spacing significand 'c', there are 4 candidates:
7670
7671 u0 u1 c w1 w0
7672 ----|----|----|----|----|-*--|----|----|----|----|----|----|----|----
7673 9 0 1 2 3 4 5 6 7 8 9 0 1
7674 |___________________|___________________|
7675 1ulp
7676
7677 The `1ulp` is in the range [1.0, 10.0).
7678 If (c - 0.5ulp < u0), trim the last digit and round down.
7679 If (c + 0.5ulp > w0), trim the last digit and round up.
7680 If (c - 0.5ulp < u1), round down.
7681 If (c + 0.5ulp > w1), round up.
7682 */
7683 while (likely(sig_raw)) {
7684 u64 mod, dec, add_1, add_10, s_hi, s_lo;
7685 u64 c, half_ulp, t0, t1;
7686
7687 /* k = floor(exp_bin * log10(2)); */
7688 /* h = exp_bin + floor(log2(10) * -k); (h = 0/1/2/3) */
7689 k = (i32)(exp_bin * 315653) >> 20;
7690 h = exp_bin + ((-k * 217707) >> 16);
7691 pow10_table_get_sig(-k, &p10_hi, &p10_lo);
7692
7693 /* sig_bin << (1/2/3/4) */
7694 cb = sig_bin << (h + 1);
7695 u128_mul(cb, p10_lo, &s_hi, &s_lo);
7696 u128_mul_add(cb, p10_hi, s_hi, &s_hi, &s_lo);
7697 mod = s_hi % 10;
7698 dec = s_hi - mod;
7699
7700 /* right shift 4 to fit in u64 */
7701 c = (mod << (64 - 4)) | (s_lo >> 4);
7702 half_ulp = p10_hi >> (4 - h);
7703
7704 /* check w1, u0, w0 range */
7705 w1_inside = (s_lo >= ((u64)1 << 63));
7706 if (unlikely(s_lo == ((u64)1 << 63))) break;
7707 u0_inside = (half_ulp >= c);
7708 if (unlikely(half_ulp == c)) break;
7709 t0 = ((u64)10 << (64 - 4));
7710 t1 = c + half_ulp;
7711 w0_inside = (t1 >= t0);
7712 if (unlikely(t0 - t1 <= (u64)1)) break;
7713
7714 trim = (u0_inside | w0_inside);
7715 add_10 = (w0_inside ? 10 : 0);
7716 add_1 = mod + w1_inside;
7717 *sig_dec = dec + (trim ? add_10 : add_1);
7718 *exp_dec = k;
7719 return;
7720 }
7721
7722 /*
7723 Schubfach algorithm:
7724 Raffaello Giulietti, The Schubfach way to render doubles, 2022.
7725 https://drive.google.com/file/d/1gp5xv4CAa78SVgCeWfGqqI4FfYYYuNFb (Paper)
7726 https://github.com/openjdk/jdk/pull/3402 (Java implementation)
7727 https://github.com/abolz/Drachennest (C++ implementation)
7728 */
7729 irregular = (sig_raw == 0 && exp_raw > 1);
7730 is_even = !(sig_bin & 1);
7731 cbl = 4 * sig_bin - 2 + irregular;
7732 cb = 4 * sig_bin;
7733 cbr = 4 * sig_bin + 2;
7734
7735 /* k = floor(exp_bin * log10(2) + (irregular ? log10(3.0 / 4.0) : 0)); */
7736 /* h = exp_bin + floor(log2(10) * -k) + 1; (h = 1/2/3/4) */
7737 k = (i32)(exp_bin * 315653 - (irregular ? 131237 : 0)) >> 20;
7738 h = exp_bin + ((-k * 217707) >> 16) + 1;
7739 pow10_table_get_sig(-k, &p10_hi, &p10_lo);
7740 p10_lo += 1;
7741
7742 vbl = u128_round_to_odd(p10_hi, p10_lo, cbl << h);
7743 vb = u128_round_to_odd(p10_hi, p10_lo, cb << h);
7744 vbr = u128_round_to_odd(p10_hi, p10_lo, cbr << h);
7745 lower = vbl + !is_even;
7746 upper = vbr - !is_even;
7747
7748 s = vb / 4;
7749 if (s >= 10) {
7750 sp = s / 10;
7751 u0_inside = (lower <= 40 * sp);
7752 w0_inside = (upper >= 40 * sp + 40);
7753 if (u0_inside != w0_inside) {
7754 *sig_dec = sp * 10 + (w0_inside ? 10 : 0);
7755 *exp_dec = k;
7756 return;
7757 }
7758 }
7759 u1_inside = (lower <= 4 * s);
7760 w1_inside = (upper >= 4 * s + 4);
7761 mid = 4 * s + 2;
7762 round_up = (vb > mid) || (vb == mid && (s & 1) != 0);
7763 *sig_dec = s + ((u1_inside != w1_inside) ? w1_inside : round_up);
7764 *exp_dec = k;
7765}
7766
7767/** Convert f64 from binary to decimal (fast but not the shortest).
7768 The input should not be 0, inf, nan. */
7769static_inline void f64_bin_to_dec_fast(u64 sig_raw, u32 exp_raw,
7770 u64 sig_bin, i32 exp_bin,
7771 u64 *sig_dec, i32 *exp_dec,
7772 bool *round_up) {
7773 u64 cb, p10_hi, p10_lo, s_hi, s_lo;
7774 i32 k, h;
7775 bool irregular, u;
7776
7777 irregular = (sig_raw == 0 && exp_raw > 1);
7778
7779 /* k = floor(exp_bin * log10(2) + (irregular ? log10(3.0 / 4.0) : 0)); */
7780 /* h = exp_bin + floor(log2(10) * -k) + 1; (h = 1/2/3/4) */
7781 k = (i32)(exp_bin * 315653 - (irregular ? 131237 : 0)) >> 20;
7782 h = exp_bin + ((-k * 217707) >> 16);
7783 pow10_table_get_sig(-k, &p10_hi, &p10_lo);
7784
7785 /* sig_bin << (1/2/3/4) */
7786 cb = sig_bin << (h + 1);
7787 u128_mul(cb, p10_lo, &s_hi, &s_lo);
7788 u128_mul_add(cb, p10_hi, s_hi, &s_hi, &s_lo);
7789
7790 /* round up */
7791 u = s_lo >= (irregular ? U64(0x55555555, 0x55555555) : ((u64)1 << 63));
7792
7793 *sig_dec = s_hi + u;
7794 *exp_dec = k;
7795 *round_up = u;
7796 return;
7797}
7798
7799/** Write inf/nan if allowed. */
7800static_inline u8 *write_inf_or_nan(u8 *buf, yyjson_write_flag flg,
7801 u64 sig_raw, bool sign) {
7802 if (has_flg(INF_AND_NAN_AS_NULL)) {
7803 byte_copy_4(buf, "null");
7804 return buf + 4;
7805 }
7806 if (has_allow(INF_AND_NAN)) {
7807 if (sig_raw == 0) {
7808 buf[0] = '-';
7809 buf += sign;
7810 byte_copy_8(buf, "Infinity");
7811 return buf + 8;
7812 } else {
7813 byte_copy_4(buf, "NaN");
7814 return buf + 3;
7815 }
7816 }
7817 return NULL;
7818}
7819
7820/**
7821 Write a float number (requires 40 bytes buffer).
7822 We follow the ECMAScript specification for printing floating-point numbers,
7823 similar to `Number.prototype.toString()`, but with the following changes:
7824 1. Keep the negative sign of `-0.0` to preserve input information.
7825 2. Keep decimal point to indicate the number is floating point.
7826 3. Remove positive sign in the exponent part.
7827 */
7828static_noinline u8 *write_f32_raw(u8 *buf, u64 raw_f64,
7829 yyjson_write_flag flg) {
7830 u32 sig_bin, sig_dec, sig_raw;
7831 i32 exp_bin, exp_dec, sig_len, dot_ofs;
7832 u32 exp_raw, raw;
7833 u8 *end;
7834 bool sign;
7835
7836 /* cast double to float */
7837 raw = f32_to_bits(f64_to_f32(f64_from_bits(raw_f64)));
7838
7839 /* decode raw bytes from IEEE-754 double format. */
7840 sign = (bool)(raw >> (F32_BITS - 1));
7841 sig_raw = raw & F32_SIG_MASK;
7842 exp_raw = (raw & F32_EXP_MASK) >> F32_SIG_BITS;
7843
7844 /* return inf or nan */
7845 if (unlikely(exp_raw == ((u32)1 << F32_EXP_BITS) - 1)) {
7846 return write_inf_or_nan(buf, flg, sig_raw, sign);
7847 }
7848
7849 /* add sign for all finite number */
7850 buf[0] = '-';
7851 buf += sign;
7852
7853 /* return zero */
7854 if ((raw << 1) == 0) {
7855 byte_copy_4(buf, "0.0");
7856 return buf + 3;
7857 }
7858
7859 if (likely(exp_raw != 0)) {
7860 /* normal number */
7861 sig_bin = sig_raw | ((u32)1 << F32_SIG_BITS);
7862 exp_bin = (i32)exp_raw - F32_EXP_BIAS - F32_SIG_BITS;
7863
7864 /* fast path for small integer number without fraction */
7865 if ((-F32_SIG_BITS <= exp_bin && exp_bin <= 0) &&
7866 (u64_tz_bits(sig_bin) >= (u32)-exp_bin)) {
7867 sig_dec = sig_bin >> -exp_bin; /* range: [1, 0xFFFFFF] */
7868 buf = write_u32_len_1_to_8(sig_dec, buf);
7869 byte_copy_2(buf, ".0");
7870 return buf + 2;
7871 }
7872
7873 /* binary to decimal */
7874 f32_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);
7875
7876 /* the sig length is 7 or 9 */
7877 sig_len = 7 + (sig_dec >= (u32)10000000) + (sig_dec >= (u32)100000000);
7878
7879 /* the decimal point offset relative to the first digit */
7880 dot_ofs = sig_len + exp_dec;
7881
7882 if (-6 < dot_ofs && dot_ofs <= 21) {
7883 i32 num_sep_pos, dot_set_pos, pre_ofs;
7884 u8 *num_hdr, *num_end, *num_sep, *dot_end;
7885 bool no_pre_zero;
7886
7887 /* fill zeros */
7888 memset(buf, '0', 32);
7889
7890 /* not prefixed with zero, e.g. 1.234, 1234.0 */
7891 no_pre_zero = (dot_ofs > 0);
7892
7893 /* write the number as digits */
7894 pre_ofs = no_pre_zero ? 0 : (2 - dot_ofs);
7895 num_hdr = buf + pre_ofs;
7896 num_end = write_u32_len_7_to_9_trim(sig_dec, num_hdr);
7897
7898 /* seperate these digits to leave a space for dot */
7899 num_sep_pos = no_pre_zero ? dot_ofs : 0;
7900 num_sep = num_hdr + num_sep_pos;
7901 byte_move_8(num_sep + no_pre_zero, num_sep);
7902 num_end += no_pre_zero;
7903
7904 /* write the dot */
7905 dot_set_pos = yyjson_max(dot_ofs, 1);
7906 buf[dot_set_pos] = '.';
7907
7908 /* return the ending */
7909 dot_end = buf + dot_ofs + 2;
7910 return yyjson_max(dot_end, num_end);
7911
7912 } else {
7913 /* write with scientific notation, e.g. 1.234e56 */
7914 end = write_u32_len_7_to_9_trim(sig_dec, buf + 1);
7915 end -= (end == buf + 2); /* remove '.0', e.g. 2.0e34 -> 2e34 */
7916 exp_dec += sig_len - 1;
7917 buf[0] = buf[1];
7918 buf[1] = '.';
7919 return write_f32_exp(exp_dec, end);
7920 }
7921
7922 } else {
7923 /* subnormal number */
7924 sig_bin = sig_raw;
7925 exp_bin = 1 - F32_EXP_BIAS - F32_SIG_BITS;
7926
7927 /* binary to decimal */
7928 f32_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);
7929
7930 /* write significand part */
7931 end = write_u32_len_1_to_8(sig_dec, buf + 1);
7932 buf[0] = buf[1];
7933 buf[1] = '.';
7934 exp_dec += (i32)(end - buf) - 2;
7935
7936 /* trim trailing zeros */
7937 end -= *(end - 1) == '0'; /* branchless for last zero */
7938 end -= *(end - 1) == '0'; /* branchless for second last zero */
7939 while (*(end - 1) == '0') end--; /* for unlikely more zeros */
7940 end -= *(end - 1) == '.'; /* remove dot, e.g. 2.e-321 -> 2e-321 */
7941
7942 /* write exponent part */
7943 return write_f32_exp(exp_dec, end);
7944 }
7945}
7946
7947/**
7948 Write a double number (requires 40 bytes buffer).
7949 We follow the ECMAScript specification for printing floating-point numbers,
7950 similar to `Number.prototype.toString()`, but with the following changes:
7951 1. Keep the negative sign of `-0.0` to preserve input information.
7952 2. Keep decimal point to indicate the number is floating point.
7953 3. Remove positive sign in the exponent part.
7954 */
7955static_noinline u8 *write_f64_raw(u8 *buf, u64 raw, yyjson_write_flag flg) {
7956 u64 sig_bin, sig_dec, sig_raw;
7957 i32 exp_bin, exp_dec, sig_len, dot_ofs;
7958 u32 exp_raw;
7959 u8 *end;
7960 bool sign;
7961
7962 /* decode raw bytes from IEEE-754 double format. */
7963 sign = (bool)(raw >> (F64_BITS - 1));
7964 sig_raw = raw & F64_SIG_MASK;
7965 exp_raw = (u32)((raw & F64_EXP_MASK) >> F64_SIG_BITS);
7966
7967 /* return inf or nan */
7968 if (unlikely(exp_raw == ((u32)1 << F64_EXP_BITS) - 1)) {
7969 return write_inf_or_nan(buf, flg, sig_raw, sign);
7970 }
7971
7972 /* add sign for all finite number */
7973 buf[0] = '-';
7974 buf += sign;
7975
7976 /* return zero */
7977 if ((raw << 1) == 0) {
7978 byte_copy_4(buf, "0.0");
7979 return buf + 3;
7980 }
7981
7982 if (likely(exp_raw != 0)) {
7983 /* normal number */
7984 sig_bin = sig_raw | ((u64)1 << F64_SIG_BITS);
7985 exp_bin = (i32)exp_raw - F64_EXP_BIAS - F64_SIG_BITS;
7986
7987 /* fast path for small integer number without fraction */
7988 if ((-F64_SIG_BITS <= exp_bin && exp_bin <= 0) &&
7989 (u64_tz_bits(sig_bin) >= (u32)-exp_bin)) {
7990 sig_dec = sig_bin >> -exp_bin; /* range: [1, 0x1FFFFFFFFFFFFF] */
7991 buf = write_u64_len_1_to_16(sig_dec, buf);
7992 byte_copy_2(buf, ".0");
7993 return buf + 2;
7994 }
7995
7996 /* binary to decimal */
7997 f64_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);
7998
7999 /* the sig length is 16 or 17 */
8000 sig_len = 16 + (sig_dec >= (u64)100000000 * 100000000);
8001
8002 /* the decimal point offset relative to the first digit */
8003 dot_ofs = sig_len + exp_dec;
8004
8005 if (-6 < dot_ofs && dot_ofs <= 21) {
8006 i32 num_sep_pos, dot_set_pos, pre_ofs;
8007 u8 *num_hdr, *num_end, *num_sep, *dot_end;
8008 bool no_pre_zero;
8009
8010 /* fill zeros */
8011 memset(buf, '0', 32);
8012
8013 /* not prefixed with zero, e.g. 1.234, 1234.0 */
8014 no_pre_zero = (dot_ofs > 0);
8015
8016 /* write the number as digits */
8017 pre_ofs = no_pre_zero ? 0 : (2 - dot_ofs);
8018 num_hdr = buf + pre_ofs;
8019 num_end = write_u64_len_16_to_17_trim(sig_dec, num_hdr);
8020
8021 /* seperate these digits to leave a space for dot */
8022 num_sep_pos = no_pre_zero ? dot_ofs : 0;
8023 num_sep = num_hdr + num_sep_pos;
8024 byte_move_16(num_sep + no_pre_zero, num_sep);
8025 num_end += no_pre_zero;
8026
8027 /* write the dot */
8028 dot_set_pos = yyjson_max(dot_ofs, 1);
8029 buf[dot_set_pos] = '.';
8030
8031 /* return the ending */
8032 dot_end = buf + dot_ofs + 2;
8033 return yyjson_max(dot_end, num_end);
8034
8035 } else {
8036 /* write with scientific notation, e.g. 1.234e56 */
8037 end = write_u64_len_16_to_17_trim(sig_dec, buf + 1);
8038 end -= (end == buf + 2); /* remove '.0', e.g. 2.0e34 -> 2e34 */
8039 exp_dec += sig_len - 1;
8040 buf[0] = buf[1];
8041 buf[1] = '.';
8042 return write_f64_exp(exp_dec, end);
8043 }
8044
8045 } else {
8046 /* subnormal number */
8047 sig_bin = sig_raw;
8048 exp_bin = 1 - F64_EXP_BIAS - F64_SIG_BITS;
8049
8050 /* binary to decimal */
8051 f64_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin, &sig_dec, &exp_dec);
8052
8053 /* write significand part */
8054 end = write_u64_len_1_to_17(sig_dec, buf + 1);
8055 buf[0] = buf[1];
8056 buf[1] = '.';
8057 exp_dec += (i32)(end - buf) - 2;
8058
8059 /* trim trailing zeros */
8060 end -= *(end - 1) == '0'; /* branchless for last zero */
8061 end -= *(end - 1) == '0'; /* branchless for second last zero */
8062 while (*(end - 1) == '0') end--; /* for unlikely more zeros */
8063 end -= *(end - 1) == '.'; /* remove dot, e.g. 2.e-321 -> 2e-321 */
8064
8065 /* write exponent part */
8066 return write_f64_exp(exp_dec, end);
8067 }
8068}
8069
8070/**
8071 Write a double number using fixed-point notation (requires 40 bytes buffer).
8072
8073 We follow the ECMAScript specification for printing floating-point numbers,
8074 similar to `Number.prototype.toFixed(prec)`, but with the following changes:
8075 1. Keep the negative sign of `-0.0` to preserve input information.
8076 2. Keep decimal point to indicate the number is floating point.
8077 3. Remove positive sign in the exponent part.
8078 4. Remove trailing zeros and reduce unnecessary precision.
8079 */
8080static_noinline u8 *write_f64_raw_fixed(u8 *buf, u64 raw, yyjson_write_flag flg,
8081 u32 prec) {
8082 u64 sig_bin, sig_dec, sig_raw;
8083 i32 exp_bin, exp_dec, sig_len, dot_ofs;
8084 u32 exp_raw;
8085 u8 *end;
8086 bool sign;
8087
8088 /* decode raw bytes from IEEE-754 double format. */
8089 sign = (bool)(raw >> (F64_BITS - 1));
8090 sig_raw = raw & F64_SIG_MASK;
8091 exp_raw = (u32)((raw & F64_EXP_MASK) >> F64_SIG_BITS);
8092
8093 /* return inf or nan */
8094 if (unlikely(exp_raw == ((u32)1 << F64_EXP_BITS) - 1)) {
8095 return write_inf_or_nan(buf, flg, sig_raw, sign);
8096 }
8097
8098 /* add sign for all finite number */
8099 buf[0] = '-';
8100 buf += sign;
8101
8102 /* return zero */
8103 if ((raw << 1) == 0) {
8104 byte_copy_4(buf, "0.0");
8105 return buf + 3;
8106 }
8107
8108 if (likely(exp_raw != 0)) {
8109 /* normal number */
8110 sig_bin = sig_raw | ((u64)1 << F64_SIG_BITS);
8111 exp_bin = (i32)exp_raw - F64_EXP_BIAS - F64_SIG_BITS;
8112
8113 /* fast path for small integer number without fraction */
8114 if ((-F64_SIG_BITS <= exp_bin && exp_bin <= 0) &&
8115 (u64_tz_bits(sig_bin) >= (u32)-exp_bin)) {
8116 sig_dec = sig_bin >> -exp_bin; /* range: [1, 0x1FFFFFFFFFFFFF] */
8117 buf = write_u64_len_1_to_16(sig_dec, buf);
8118 byte_copy_2(buf, ".0");
8119 return buf + 2;
8120 }
8121
8122 /* only `fabs(num) < 1e21` are processed here. */
8123 if ((raw << 1) < (U64(0x444B1AE4, 0xD6E2EF50) << 1)) {
8124 i32 num_sep_pos, dot_set_pos, pre_ofs;
8125 u8 *num_hdr, *num_end, *num_sep;
8126 bool round_up, no_pre_zero;
8127
8128 /* binary to decimal */
8129 f64_bin_to_dec_fast(sig_raw, exp_raw, sig_bin, exp_bin,
8130 &sig_dec, &exp_dec, &round_up);
8131
8132 /* the sig length is 16 or 17 */
8133 sig_len = 16 + (sig_dec >= (u64)100000000 * 100000000);
8134
8135 /* limit the length of digits after the decimal point */
8136 if (exp_dec < -1) {
8137 i32 sig_len_cut = -exp_dec - (i32)prec;
8138 if (sig_len_cut > sig_len) {
8139 byte_copy_4(buf, "0.0");
8140 return buf + 3;
8141 }
8142 if (sig_len_cut > 0) {
8143 u64 div, mod, p10;
8144
8145 /* remove round up */
8146 sig_dec -= round_up;
8147 sig_len = 16 + (sig_dec >= (u64)100000000 * 100000000);
8148
8149 /* cut off some digits */
8150 div_pow10(sig_dec, (u32)sig_len_cut, &div, &mod, &p10);
8151
8152 /* add round up */
8153 sig_dec = div + (mod >= p10 / 2);
8154
8155 /* update exp and sig length */
8156 exp_dec += sig_len_cut;
8157 sig_len -= sig_len_cut;
8158 sig_len += (sig_len >= 0) &&
8159 (sig_dec >= div_pow10_table[sig_len].p10);
8160 }
8161 if (sig_len <= 0) {
8162 byte_copy_4(buf, "0.0");
8163 return buf + 3;
8164 }
8165 }
8166
8167 /* fill zeros */
8168 memset(buf, '0', 32);
8169
8170 /* the decimal point offset relative to the first digit */
8171 dot_ofs = sig_len + exp_dec;
8172
8173 /* not prefixed with zero, e.g. 1.234, 1234.0 */
8174 no_pre_zero = (dot_ofs > 0);
8175
8176 /* write the number as digits */
8177 pre_ofs = no_pre_zero ? 0 : (1 - dot_ofs);
8178 num_hdr = buf + pre_ofs;
8179 num_end = write_u64_len_1_to_17(sig_dec, num_hdr);
8180
8181 /* seperate these digits to leave a space for dot */
8182 num_sep_pos = no_pre_zero ? dot_ofs : -dot_ofs;
8183 num_sep = buf + num_sep_pos;
8184 byte_move_16(num_sep + 1, num_sep);
8185 num_end += (exp_dec < 0);
8186
8187 /* write the dot */
8188 dot_set_pos = yyjson_max(dot_ofs, 1);
8189 buf[dot_set_pos] = '.';
8190
8191 /* remove trailing zeros */
8192 buf += dot_set_pos + 2;
8193 buf = yyjson_max(buf, num_end);
8194 buf -= *(buf - 1) == '0'; /* branchless for last zero */
8195 buf -= *(buf - 1) == '0'; /* branchless for second last zero */
8196 while (*(buf - 1) == '0') buf--; /* for unlikely more zeros */
8197 buf += *(buf - 1) == '.'; /* keep a zero after dot */
8198 return buf;
8199
8200 } else {
8201 /* binary to decimal */
8202 f64_bin_to_dec(sig_raw, exp_raw, sig_bin, exp_bin,
8203 &sig_dec, &exp_dec);
8204
8205 /* the sig length is 16 or 17 */
8206 sig_len = 16 + (sig_dec >= (u64)100000000 * 100000000);
8207
8208 /* write with scientific notation, e.g. 1.234e56 */
8209 end = write_u64_len_16_to_17_trim(sig_dec, buf + 1);
8210 end -= (end == buf + 2); /* remove '.0', e.g. 2.0e34 -> 2e34 */
8211 exp_dec += sig_len - 1;
8212 buf[0] = buf[1];
8213 buf[1] = '.';
8214 return write_f64_exp(exp_dec, end);
8215 }
8216 } else {
8217 /* subnormal number */
8218 byte_copy_4(buf, "0.0");
8219 return buf + 3;
8220 }
8221}
8222
8223#else /* FP_WRITER */
8224
8225#if YYJSON_MSC_VER >= 1400
8226#define snprintf_num(buf, len, fmt, dig, val) \
8227 sprintf_s((char *)buf, len, fmt, dig, val)
8228#elif defined(snprintf) || (YYJSON_STDC_VER >= 199901L)
8229#define snprintf_num(buf, len, fmt, dig, val) \
8230 snprintf((char *)buf, len, fmt, dig, val)
8231#else
8232#define snprintf_num(buf, len, fmt, dig, val) \
8233 sprintf((char *)buf, fmt, dig, val)
8234#endif
8235
8236static_noinline u8 *write_fp_reformat(u8 *buf, int len,
8237 yyjson_write_flag flg, bool fixed) {
8238 u8 *cur = buf;
8239 if (unlikely(len < 1)) return NULL;
8240 cur += (*cur == '-');
8241 if (unlikely(!char_is_digit(*cur))) {
8242 /* nan, inf, or bad output */
8243 if (has_flg(INF_AND_NAN_AS_NULL)) {
8244 byte_copy_4(buf, "null");
8245 return buf + 4;
8246 } else if (has_allow(INF_AND_NAN)) {
8247 if (*cur == 'i') {
8248 byte_copy_8(cur, "Infinity");
8249 return cur + 8;
8250 } else if (*cur == 'n') {
8251 byte_copy_4(buf, "NaN");
8252 return buf + 3;
8253 }
8254 }
8255 return NULL;
8256 } else {
8257 /* finite number */
8258 u8 *end = buf + len, *dot = NULL, *exp = NULL;
8259
8260 /*
8261 The snprintf() function is locale-dependent. For currently known
8262 locales, (en, zh, ja, ko, am, he, hi) use '.' as the decimal point,
8263 while other locales use ',' as the decimal point. we need to replace
8264 ',' with '.' to avoid the locale setting.
8265 */
8266 for (; cur < end; cur++) {
8267 switch (*cur) {
8268 case ',': *cur = '.'; /* fallthrough */
8269 case '.': dot = cur; break;
8270 case 'e': exp = cur; break;
8271 default: break;
8272 }
8273 }
8274 if (fixed) {
8275 /* remove trailing zeros */
8276 while (*(end - 1) == '0') end--;
8277 end += *(end - 1) == '.';
8278 } else {
8279 if (!dot && !exp) {
8280 /* add decimal point, e.g. 123 -> 123.0 */
8281 byte_copy_2(end, ".0");
8282 end += 2;
8283 } else if (exp) {
8284 cur = exp + 1;
8285 /* remove positive sign in the exponent part */
8286 if (*cur == '+') {
8287 memmove(cur, cur + 1, (usize)(end - cur - 1));
8288 end--;
8289 }
8290 cur += (*cur == '-');
8291 /* remove leading zeros in the exponent part */
8292 if (*cur == '0') {
8293 u8 *hdr = cur++;
8294 while (*cur == '0') cur++;
8295 memmove(hdr, cur, (usize)(end - cur));
8296 end -= (usize)(cur - hdr);
8297 }
8298 }
8299 }
8300 return end;
8301 }
8302}
8303
8304/** Write a double number (requires 40 bytes buffer). */
8305static_noinline u8 *write_f64_raw(u8 *buf, u64 raw, yyjson_write_flag flg) {
8306#if defined(DBL_DECIMAL_DIG) && DBL_DECIMAL_DIG < F64_DEC_DIG
8307 int dig = DBL_DECIMAL_DIG;
8308#else
8309 int dig = F64_DEC_DIG;
8310#endif
8311 f64 val = f64_from_bits(raw);
8312 int len = snprintf_num(buf, FP_BUF_LEN, "%.*g", dig, val);
8313 return write_fp_reformat(buf, len, flg, false);
8314}
8315
8316/** Write a double number (requires 40 bytes buffer). */
8317static_noinline u8 *write_f32_raw(u8 *buf, u64 raw, yyjson_write_flag flg) {
8318#if defined(FLT_DECIMAL_DIG) && FLT_DECIMAL_DIG < F32_DEC_DIG
8319 int dig = FLT_DECIMAL_DIG;
8320#else
8321 int dig = F32_DEC_DIG;
8322#endif
8323 f64 val = (f64)f64_to_f32(f64_from_bits(raw));
8324 int len = snprintf_num(buf, FP_BUF_LEN, "%.*g", dig, val);
8325 return write_fp_reformat(buf, len, flg, false);
8326}
8327
8328/** Write a double number (requires 40 bytes buffer). */
8329static_noinline u8 *write_f64_raw_fixed(u8 *buf, u64 raw,
8330 yyjson_write_flag flg, u32 prec) {
8331 f64 val = (f64)f64_from_bits(raw);
8332 if (-1e21 < val && val < 1e21) {
8333 int len = snprintf_num(buf, FP_BUF_LEN, "%.*f", (int)prec, val);
8334 return write_fp_reformat(buf, len, flg, true);
8335 } else {
8336 return write_f64_raw(buf, raw, flg);
8337 }
8338}
8339
8340#endif /* FP_WRITER */
8341
8342/** Write a JSON number (requires 40 bytes buffer). */
8343static_inline u8 *write_num(u8 *cur, yyjson_val *val, yyjson_write_flag flg) {
8344 if (!(val->tag & YYJSON_SUBTYPE_REAL)) {
8345 u64 pos = val->uni.u64;
8346 u64 neg = ~pos + 1;
8347 usize sign = ((val->tag & YYJSON_SUBTYPE_SINT) > 0) & ((i64)pos < 0);
8348 *cur = '-';
8349 return write_u64(sign ? neg : pos, cur + sign);
8350 } else {
8351 u64 raw = val->uni.u64;
8352 u32 val_fmt = (u32)(val->tag >> 32);
8353 u32 all_fmt = flg;
8354 u32 fmt = val_fmt | all_fmt;
8355 if (likely(!(fmt >> (32 - YYJSON_WRITE_FP_FLAG_BITS)))) {
8356 /* double to shortest */
8357 return write_f64_raw(cur, raw, flg);
8358 } else if (fmt >> (32 - YYJSON_WRITE_FP_PREC_BITS)) {
8359 /* double to fixed */
8360 u32 val_prec = val_fmt >> (32 - YYJSON_WRITE_FP_PREC_BITS);
8361 u32 all_prec = all_fmt >> (32 - YYJSON_WRITE_FP_PREC_BITS);
8362 u32 prec = val_prec ? val_prec : all_prec;
8363 return write_f64_raw_fixed(cur, raw, flg, prec);
8364 } else {
8365 if (fmt & YYJSON_WRITE_FP_TO_FLOAT) {
8366 /* float to shortest */
8367 return write_f32_raw(cur, raw, flg);
8368 } else {
8369 /* double to shortest */
8370 return write_f64_raw(cur, raw, flg);
8371 }
8372 }
8373 }
8374}
8375
8376char *yyjson_write_number(const yyjson_val *val, char *buf) {
8377 if (unlikely(!val || !buf)) return NULL;
8378 switch (val->tag & YYJSON_TAG_MASK) {
8379 case YYJSON_TYPE_NUM | YYJSON_SUBTYPE_UINT: {
8380 buf = (char *)write_u64(val->uni.u64, (u8 *)buf);
8381 *buf = '\0';
8382 return buf;
8383 }
8384 case YYJSON_TYPE_NUM | YYJSON_SUBTYPE_SINT: {
8385 u64 pos = val->uni.u64;
8386 u64 neg = ~pos + 1;
8387 usize sign = ((i64)pos < 0);
8388 *buf = '-';
8389 buf = (char *)write_u64(sign ? neg : pos, (u8 *)buf + sign);
8390 *buf = '\0';
8391 return buf;
8392 }
8393 case YYJSON_TYPE_NUM | YYJSON_SUBTYPE_REAL: {
8394 u64 raw = val->uni.u64;
8395 u32 fmt = (u32)(val->tag >> 32);
8396 u32 flg = YYJSON_WRITE_ALLOW_INF_AND_NAN;
8397 if (likely(!(fmt >> (32 - YYJSON_WRITE_FP_FLAG_BITS)))) {
8398 buf = (char *)write_f64_raw((u8 *)buf, raw, flg);
8399 } else if (fmt >> (32 - YYJSON_WRITE_FP_PREC_BITS)) {
8400 u32 prec = fmt >> (32 - YYJSON_WRITE_FP_PREC_BITS);
8401 buf = (char *)write_f64_raw_fixed((u8 *)buf, raw, flg, prec);
8402 } else {
8403 if (fmt & YYJSON_WRITE_FP_TO_FLOAT) {
8404 buf = (char *)write_f32_raw((u8 *)buf, raw, flg);
8405 } else {
8406 buf = (char *)write_f64_raw((u8 *)buf, raw, flg);
8407 }
8408 }
8409 if (buf) *buf = '\0';
8410 return buf;
8411 }
8412 default: return NULL;
8413 }
8414}
8415
8416
8417
8418/*==============================================================================
8419 * MARK: - String Writer (Private)
8420 *============================================================================*/
8421
8422/** Character encode type, if (type > CHAR_ENC_ERR_1) bytes = type / 2; */
8423typedef u8 char_enc_type;
8424#define CHAR_ENC_CPY_1 0 /* 1-byte UTF-8, copy. */
8425#define CHAR_ENC_ERR_1 1 /* 1-byte UTF-8, error. */
8426#define CHAR_ENC_ESC_A 2 /* 1-byte ASCII, escaped as '\x'. */
8427#define CHAR_ENC_ESC_1 3 /* 1-byte UTF-8, escaped as '\uXXXX'. */
8428#define CHAR_ENC_CPY_2 4 /* 2-byte UTF-8, copy. */
8429#define CHAR_ENC_ESC_2 5 /* 2-byte UTF-8, escaped as '\uXXXX'. */
8430#define CHAR_ENC_CPY_3 6 /* 3-byte UTF-8, copy. */
8431#define CHAR_ENC_ESC_3 7 /* 3-byte UTF-8, escaped as '\uXXXX'. */
8432#define CHAR_ENC_CPY_4 8 /* 4-byte UTF-8, copy. */
8433#define CHAR_ENC_ESC_4 9 /* 4-byte UTF-8, escaped as '\uXXXX\uXXXX'. */
8434
8435/** Character encode type table: don't escape unicode, don't escape '/'.
8436 (generate with misc/make_tables.c) */
8437static const char_enc_type enc_table_cpy[256] = {
8438 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
8439 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
8440 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8441 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8442 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8443 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,
8444 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8445 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8446 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8447 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8448 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8449 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8450 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
8451 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
8452 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
8453 8, 8, 8, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 1, 1
8454};
8455
8456/** Character encode type table: don't escape unicode, escape '/'.
8457 (generate with misc/make_tables.c) */
8458static const char_enc_type enc_table_cpy_slash[256] = {
8459 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
8460 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
8461 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
8462 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8463 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8464 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,
8465 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8466 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8467 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8468 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8469 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8470 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8471 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
8472 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
8473 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
8474 8, 8, 8, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 1, 1
8475};
8476
8477/** Character encode type table: escape unicode, don't escape '/'.
8478 (generate with misc/make_tables.c) */
8479static const char_enc_type enc_table_esc[256] = {
8480 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
8481 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
8482 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8483 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8484 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8485 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,
8486 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8487 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8488 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8489 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8490 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8491 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8492 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
8493 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
8494 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8495 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1
8496};
8497
8498/** Character encode type table: escape unicode, escape '/'.
8499 (generate with misc/make_tables.c) */
8500static const char_enc_type enc_table_esc_slash[256] = {
8501 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 3,
8502 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
8503 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
8504 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8505 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8506 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0,
8507 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8508 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
8509 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8510 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8511 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8512 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
8513 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
8514 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
8515 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8516 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1
8517};
8518
8519/** Escaped hex character table: ["00" "01" "02" ... "FD" "FE" "FF"].
8520 (generate with misc/make_tables.c) */
8521yyjson_align(2)
8522static const u8 esc_hex_char_table[512] = {
8523 '0', '0', '0', '1', '0', '2', '0', '3',
8524 '0', '4', '0', '5', '0', '6', '0', '7',
8525 '0', '8', '0', '9', '0', 'A', '0', 'B',
8526 '0', 'C', '0', 'D', '0', 'E', '0', 'F',
8527 '1', '0', '1', '1', '1', '2', '1', '3',
8528 '1', '4', '1', '5', '1', '6', '1', '7',
8529 '1', '8', '1', '9', '1', 'A', '1', 'B',
8530 '1', 'C', '1', 'D', '1', 'E', '1', 'F',
8531 '2', '0', '2', '1', '2', '2', '2', '3',
8532 '2', '4', '2', '5', '2', '6', '2', '7',
8533 '2', '8', '2', '9', '2', 'A', '2', 'B',
8534 '2', 'C', '2', 'D', '2', 'E', '2', 'F',
8535 '3', '0', '3', '1', '3', '2', '3', '3',
8536 '3', '4', '3', '5', '3', '6', '3', '7',
8537 '3', '8', '3', '9', '3', 'A', '3', 'B',
8538 '3', 'C', '3', 'D', '3', 'E', '3', 'F',
8539 '4', '0', '4', '1', '4', '2', '4', '3',
8540 '4', '4', '4', '5', '4', '6', '4', '7',
8541 '4', '8', '4', '9', '4', 'A', '4', 'B',
8542 '4', 'C', '4', 'D', '4', 'E', '4', 'F',
8543 '5', '0', '5', '1', '5', '2', '5', '3',
8544 '5', '4', '5', '5', '5', '6', '5', '7',
8545 '5', '8', '5', '9', '5', 'A', '5', 'B',
8546 '5', 'C', '5', 'D', '5', 'E', '5', 'F',
8547 '6', '0', '6', '1', '6', '2', '6', '3',
8548 '6', '4', '6', '5', '6', '6', '6', '7',
8549 '6', '8', '6', '9', '6', 'A', '6', 'B',
8550 '6', 'C', '6', 'D', '6', 'E', '6', 'F',
8551 '7', '0', '7', '1', '7', '2', '7', '3',
8552 '7', '4', '7', '5', '7', '6', '7', '7',
8553 '7', '8', '7', '9', '7', 'A', '7', 'B',
8554 '7', 'C', '7', 'D', '7', 'E', '7', 'F',
8555 '8', '0', '8', '1', '8', '2', '8', '3',
8556 '8', '4', '8', '5', '8', '6', '8', '7',
8557 '8', '8', '8', '9', '8', 'A', '8', 'B',
8558 '8', 'C', '8', 'D', '8', 'E', '8', 'F',
8559 '9', '0', '9', '1', '9', '2', '9', '3',
8560 '9', '4', '9', '5', '9', '6', '9', '7',
8561 '9', '8', '9', '9', '9', 'A', '9', 'B',
8562 '9', 'C', '9', 'D', '9', 'E', '9', 'F',
8563 'A', '0', 'A', '1', 'A', '2', 'A', '3',
8564 'A', '4', 'A', '5', 'A', '6', 'A', '7',
8565 'A', '8', 'A', '9', 'A', 'A', 'A', 'B',
8566 'A', 'C', 'A', 'D', 'A', 'E', 'A', 'F',
8567 'B', '0', 'B', '1', 'B', '2', 'B', '3',
8568 'B', '4', 'B', '5', 'B', '6', 'B', '7',
8569 'B', '8', 'B', '9', 'B', 'A', 'B', 'B',
8570 'B', 'C', 'B', 'D', 'B', 'E', 'B', 'F',
8571 'C', '0', 'C', '1', 'C', '2', 'C', '3',
8572 'C', '4', 'C', '5', 'C', '6', 'C', '7',
8573 'C', '8', 'C', '9', 'C', 'A', 'C', 'B',
8574 'C', 'C', 'C', 'D', 'C', 'E', 'C', 'F',
8575 'D', '0', 'D', '1', 'D', '2', 'D', '3',
8576 'D', '4', 'D', '5', 'D', '6', 'D', '7',
8577 'D', '8', 'D', '9', 'D', 'A', 'D', 'B',
8578 'D', 'C', 'D', 'D', 'D', 'E', 'D', 'F',
8579 'E', '0', 'E', '1', 'E', '2', 'E', '3',
8580 'E', '4', 'E', '5', 'E', '6', 'E', '7',
8581 'E', '8', 'E', '9', 'E', 'A', 'E', 'B',
8582 'E', 'C', 'E', 'D', 'E', 'E', 'E', 'F',
8583 'F', '0', 'F', '1', 'F', '2', 'F', '3',
8584 'F', '4', 'F', '5', 'F', '6', 'F', '7',
8585 'F', '8', 'F', '9', 'F', 'A', 'F', 'B',
8586 'F', 'C', 'F', 'D', 'F', 'E', 'F', 'F'
8587};
8588
8589/** Escaped single character table. (generate with misc/make_tables.c) */
8590yyjson_align(2)
8591static const u8 esc_single_char_table[512] = {
8592 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8593 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8594 '\\', 'b', '\\', 't', '\\', 'n', ' ', ' ',
8595 '\\', 'f', '\\', 'r', ' ', ' ', ' ', ' ',
8596 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8597 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8598 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8599 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8600 ' ', ' ', ' ', ' ', '\\', '"', ' ', ' ',
8601 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8602 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8603 ' ', ' ', ' ', ' ', ' ', ' ', '\\', '/',
8604 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8605 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8606 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8607 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8608 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8609 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8610 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8611 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8612 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8613 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8614 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8615 '\\', '\\', ' ', ' ', ' ', ' ', ' ', ' ',
8616 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8617 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8618 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8619 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8620 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8621 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8622 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8623 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8624 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8625 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8626 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8627 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8628 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8629 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8630 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8631 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8632 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8633 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8634 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8635 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8636 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8637 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8638 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8639 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8640 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8641 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8642 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8643 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8644 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8645 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8646 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8647 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8648 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8649 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8650 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8651 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8652 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8653 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8654 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
8655 ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
8656};
8657
8658/** Returns the encode table with options. */
8659static_inline const char_enc_type *get_enc_table_with_flag(
8660 yyjson_write_flag flg) {
8661 if (has_flg(ESCAPE_UNICODE)) {
8662 if (has_flg(ESCAPE_SLASHES)) {
8663 return enc_table_esc_slash;
8664 } else {
8665 return enc_table_esc;
8666 }
8667 } else {
8668 if (has_flg(ESCAPE_SLASHES)) {
8669 return enc_table_cpy_slash;
8670 } else {
8671 return enc_table_cpy;
8672 }
8673 }
8674}
8675
8676/** Write raw string. */
8677static_inline u8 *write_raw(u8 *cur, const u8 *raw, usize raw_len) {
8678 memcpy(cur, raw, raw_len);
8679 return cur + raw_len;
8680}
8681
8682/**
8683 Write string no-escape.
8684 @param cur Buffer cursor.
8685 @param str A UTF-8 string, null-terminator is not required.
8686 @param str_len Length of string in bytes.
8687 @return The buffer cursor after string.
8688 */
8689static_inline u8 *write_str_noesc(u8 *cur, const u8 *str, usize str_len) {
8690 *cur++ = '"';
8691 while (str_len >= 16) {
8692 byte_copy_16(cur, str);
8693 cur += 16;
8694 str += 16;
8695 str_len -= 16;
8696 }
8697 while (str_len >= 4) {
8698 byte_copy_4(cur, str);
8699 cur += 4;
8700 str += 4;
8701 str_len -= 4;
8702 }
8703 while (str_len) {
8704 *cur++ = *str++;
8705 str_len -= 1;
8706 }
8707 *cur++ = '"';
8708 return cur;
8709}
8710
8711/**
8712 Write UTF-8 string (requires len * 6 + 2 bytes buffer).
8713 @param cur Buffer cursor.
8714 @param esc Escape unicode.
8715 @param inv Allow invalid unicode.
8716 @param str A UTF-8 string, null-terminator is not required.
8717 @param str_len Length of string in bytes.
8718 @param enc_table Encode type table for character.
8719 @return The buffer cursor after string, or NULL on invalid unicode.
8720 */
8721static_inline u8 *write_str(u8 *cur, bool esc, bool inv,
8722 const u8 *str, usize str_len,
8723 const char_enc_type *enc_table) {
8724 /* The replacement character U+FFFD, used to indicate invalid character. */
8725 const v32 rep = {{ 'F', 'F', 'F', 'D' }};
8726 const v32 pre = {{ '\\', 'u', '0', '0' }};
8727
8728 const u8 *src = str;
8729 const u8 *end = str + str_len;
8730 *cur++ = '"';
8731
8732copy_ascii:
8733 /*
8734 Copy continuous ASCII, loop unrolling, same as the following code:
8735
8736 while (end > src) (
8737 if (unlikely(enc_table[*src])) break;
8738 *cur++ = *src++;
8739 );
8740 */
8741#define expr_jump(i) \
8742 if (unlikely(enc_table[src[i]])) goto stop_char_##i;
8743
8744#define expr_stop(i) \
8745 stop_char_##i: \
8746 memcpy(cur, src, i); \
8747 cur += i; src += i; goto copy_utf8;
8748
8749 while (end - src >= 16) {
8750 repeat16_incr(expr_jump)
8751 byte_copy_16(cur, src);
8752 cur += 16; src += 16;
8753 }
8754
8755 while (end - src >= 4) {
8756 repeat4_incr(expr_jump)
8757 byte_copy_4(cur, src);
8758 cur += 4; src += 4;
8759 }
8760
8761 while (end > src) {
8762 expr_jump(0)
8763 *cur++ = *src++;
8764 }
8765
8766 *cur++ = '"';
8767 return cur;
8768
8769 repeat16_incr(expr_stop)
8770
8771#undef expr_jump
8772#undef expr_stop
8773
8774copy_utf8:
8775 if (unlikely(src + 4 > end)) {
8776 if (end == src) goto copy_end;
8777 if (end - src < enc_table[*src] / 2) goto err_one;
8778 }
8779 switch (enc_table[*src]) {
8780 case CHAR_ENC_CPY_1: {
8781 *cur++ = *src++;
8782 goto copy_ascii;
8783 }
8784 case CHAR_ENC_CPY_2: {
8785#if YYJSON_DISABLE_UTF8_VALIDATION
8786 byte_copy_2(cur, src);
8787#else
8788 u32 uni = 0;
8789 byte_copy_2(&uni, src);
8790 if (unlikely(!is_utf8_seq2(uni))) goto err_cpy;
8791 byte_copy_2(cur, &uni);
8792#endif
8793 cur += 2;
8794 src += 2;
8795 goto copy_utf8;
8796 }
8797 case CHAR_ENC_CPY_3: {
8798#if YYJSON_DISABLE_UTF8_VALIDATION
8799 if (likely(src + 4 <= end)) {
8800 byte_copy_4(cur, src);
8801 } else {
8802 byte_copy_2(cur, src);
8803 cur[2] = src[2];
8804 }
8805#else
8806 u32 uni, tmp;
8807 if (likely(src + 4 <= end)) {
8808 uni = byte_load_4(src);
8809 if (unlikely(!is_utf8_seq3(uni))) goto err_cpy;
8810 byte_copy_4(cur, src);
8811 } else {
8812 uni = byte_load_3(src);
8813 if (unlikely(!is_utf8_seq3(uni))) goto err_cpy;
8814 byte_copy_4(cur, &uni);
8815 }
8816#endif
8817 cur += 3;
8818 src += 3;
8819 goto copy_utf8;
8820 }
8821 case CHAR_ENC_CPY_4: {
8822#if YYJSON_DISABLE_UTF8_VALIDATION
8823 byte_copy_4(cur, src);
8824#else
8825 u32 uni, tmp;
8826 uni = byte_load_4(src);
8827 if (unlikely(!is_utf8_seq4(uni))) goto err_cpy;
8828 byte_copy_4(cur, src);
8829#endif
8830 cur += 4;
8831 src += 4;
8832 goto copy_utf8;
8833 }
8834 case CHAR_ENC_ESC_A: {
8835 byte_copy_2(cur, &esc_single_char_table[*src * 2]);
8836 cur += 2;
8837 src += 1;
8838 goto copy_utf8;
8839 }
8840 case CHAR_ENC_ESC_1: {
8841 byte_copy_4(cur + 0, &pre);
8842 byte_copy_2(cur + 4, &esc_hex_char_table[*src * 2]);
8843 cur += 6;
8844 src += 1;
8845 goto copy_utf8;
8846 }
8847 case CHAR_ENC_ESC_2: {
8848 u16 u;
8849#if !YYJSON_DISABLE_UTF8_VALIDATION
8850 u32 v4 = 0;
8851 u16 v2 = byte_load_2(src);
8852 byte_copy_2(&v4, &v2);
8853 if (unlikely(!is_utf8_seq2(v4))) goto err_esc;
8854#endif
8855 u = (u16)(((u16)(src[0] & 0x1F) << 6) |
8856 ((u16)(src[1] & 0x3F) << 0));
8857 byte_copy_2(cur + 0, &pre);
8858 byte_copy_2(cur + 2, &esc_hex_char_table[(u >> 8) * 2]);
8859 byte_copy_2(cur + 4, &esc_hex_char_table[(u & 0xFF) * 2]);
8860 cur += 6;
8861 src += 2;
8862 goto copy_utf8;
8863 }
8864 case CHAR_ENC_ESC_3: {
8865 u16 u;
8866 u32 v, tmp;
8867#if !YYJSON_DISABLE_UTF8_VALIDATION
8868 v = byte_load_3(src);
8869 if (unlikely(!is_utf8_seq3(v))) goto err_esc;
8870#endif
8871 u = (u16)(((u16)(src[0] & 0x0F) << 12) |
8872 ((u16)(src[1] & 0x3F) << 6) |
8873 ((u16)(src[2] & 0x3F) << 0));
8874 byte_copy_2(cur + 0, &pre);
8875 byte_copy_2(cur + 2, &esc_hex_char_table[(u >> 8) * 2]);
8876 byte_copy_2(cur + 4, &esc_hex_char_table[(u & 0xFF) * 2]);
8877 cur += 6;
8878 src += 3;
8879 goto copy_utf8;
8880 }
8881 case CHAR_ENC_ESC_4: {
8882 u32 hi, lo, u, v, tmp;
8883#if !YYJSON_DISABLE_UTF8_VALIDATION
8884 v = byte_load_4(src);
8885 if (unlikely(!is_utf8_seq4(v))) goto err_esc;
8886#endif
8887 u = ((u32)(src[0] & 0x07) << 18) |
8888 ((u32)(src[1] & 0x3F) << 12) |
8889 ((u32)(src[2] & 0x3F) << 6) |
8890 ((u32)(src[3] & 0x3F) << 0);
8891 u -= 0x10000;
8892 hi = (u >> 10) + 0xD800;
8893 lo = (u & 0x3FF) + 0xDC00;
8894 byte_copy_2(cur + 0, &pre);
8895 byte_copy_2(cur + 2, &esc_hex_char_table[(hi >> 8) * 2]);
8896 byte_copy_2(cur + 4, &esc_hex_char_table[(hi & 0xFF) * 2]);
8897 byte_copy_2(cur + 6, &pre);
8898 byte_copy_2(cur + 8, &esc_hex_char_table[(lo >> 8) * 2]);
8899 byte_copy_2(cur + 10, &esc_hex_char_table[(lo & 0xFF) * 2]);
8900 cur += 12;
8901 src += 4;
8902 goto copy_utf8;
8903 }
8904 case CHAR_ENC_ERR_1: {
8905 goto err_one;
8906 }
8907 default: break; /* unreachable */
8908 }
8909
8910copy_end:
8911 *cur++ = '"';
8912 return cur;
8913
8914err_one:
8915 if (esc) goto err_esc;
8916 else goto err_cpy;
8917
8918err_cpy:
8919 if (!inv) return NULL;
8920 *cur++ = *src++;
8921 goto copy_utf8;
8922
8923err_esc:
8924 if (!inv) return NULL;
8925 byte_copy_2(cur + 0, &pre);
8926 byte_copy_4(cur + 2, &rep);
8927 cur += 6;
8928 src += 1;
8929 goto copy_utf8;
8930}
8931
8932
8933
8934/*==============================================================================
8935 * MARK: - JSON Writer Utilities (Private)
8936 *============================================================================*/
8937
8938/** Write null (requires 8 bytes buffer). */
8939static_inline u8 *write_null(u8 *cur) {
8940 v64 v = {{ 'n', 'u', 'l', 'l', ',', '\n', 0, 0 }};
8941 byte_copy_8(cur, &v);
8942 return cur + 4;
8943}
8944
8945/** Write bool (requires 8 bytes buffer). */
8946static_inline u8 *write_bool(u8 *cur, bool val) {
8947 v64 v0 = {{ 'f', 'a', 'l', 's', 'e', ',', '\n', 0 }};
8948 v64 v1 = {{ 't', 'r', 'u', 'e', ',', '\n', 0, 0 }};
8949 if (val) {
8950 byte_copy_8(cur, &v1);
8951 } else {
8952 byte_copy_8(cur, &v0);
8953 }
8954 return cur + 5 - val;
8955}
8956
8957/** Write indent (requires level x 4 bytes buffer).
8958 Param spaces should not larger than 4. */
8959static_inline u8 *write_indent(u8 *cur, usize level, usize spaces) {
8960 while (level-- > 0) {
8961 byte_copy_4(cur, " ");
8962 cur += spaces;
8963 }
8964 return cur;
8965}
8966
8967/** Write data to file pointer. */
8968static bool write_dat_to_fp(FILE *fp, u8 *dat, usize len,
8969 yyjson_write_err *err) {
8970 if (fwrite(dat, len, 1, fp) != 1) {
8971 err->msg = "file writing failed";
8972 err->code = YYJSON_WRITE_ERROR_FILE_WRITE;
8973 return false;
8974 }
8975 return true;
8976}
8977
8978/** Write data to file. */
8979static bool write_dat_to_file(const char *path, u8 *dat, usize len,
8980 yyjson_write_err *err) {
8981#define return_err(_code, _msg) do { \
8982 err->msg = _msg; \
8983 err->code = YYJSON_WRITE_ERROR_##_code; \
8984 if (file) fclose(file); \
8985 return false; \
8986} while (false)
8987
8988 FILE *file = fopen_writeonly(path);
8989 if (file == NULL) {
8990 return_err(FILE_OPEN, MSG_FOPEN);
8991 }
8992 if (fwrite(dat, len, 1, file) != 1) {
8993 return_err(FILE_WRITE, MSG_FWRITE);
8994 }
8995 if (fclose(file) != 0) {
8996 file = NULL;
8997 return_err(FILE_WRITE, MSG_FCLOSE);
8998 }
8999 return true;
9000
9001#undef return_err
9002}
9003
9004
9005
9006/*==============================================================================
9007 * MARK: - JSON Writer Implementation (Private)
9008 *============================================================================*/
9009
9010typedef struct yyjson_write_ctx {
9011 usize tag;
9012} yyjson_write_ctx;
9013
9014static_inline void yyjson_write_ctx_set(yyjson_write_ctx *ctx,
9015 usize size, bool is_obj) {
9016 ctx->tag = (size << 1) | (usize)is_obj;
9017}
9018
9019static_inline void yyjson_write_ctx_get(yyjson_write_ctx *ctx,
9020 usize *size, bool *is_obj) {
9021 usize tag = ctx->tag;
9022 *size = tag >> 1;
9023 *is_obj = (bool)(tag & 1);
9024}
9025
9026/** Write single JSON value. */
9027static_inline u8 *write_root_single(yyjson_val *val,
9028 yyjson_write_flag flg,
9029 yyjson_alc alc,
9030 char *buf, usize *dat_len,
9031 yyjson_write_err *err) {
9032#define return_err(_code, _msg) do { \
9033 if (hdr) alc.free(alc.ctx, (void *)hdr); \
9034 *dat_len = 0; \
9035 err->code = YYJSON_WRITE_ERROR_##_code; \
9036 err->msg = _msg; \
9037 return NULL; \
9038} while (false)
9039
9040#define incr_len(_len) do { \
9041 if (buf) hdr = *dat_len >= _len ? (u8 *)buf : (u8 *)NULL; \
9042 else hdr = (u8 *)alc.malloc(alc.ctx, _len); \
9043 if (!hdr) goto fail_alloc; \
9044 cur = hdr; \
9045} while (false)
9046
9047#define check_str_len(_len) do { \
9048 if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
9049 goto fail_alloc; \
9050} while (false)
9051
9052 u8 *hdr = NULL, *cur;
9053 usize str_len;
9054 const u8 *str_ptr;
9055 const char_enc_type *enc_table = get_enc_table_with_flag(flg);
9056 bool cpy = (enc_table == enc_table_cpy);
9057 bool esc = has_flg(ESCAPE_UNICODE) != 0;
9058 bool inv = has_allow(INVALID_UNICODE) != 0;
9059 bool newline = has_flg(NEWLINE_AT_END) != 0;
9060 const usize end_len = 2; /* '\n' and '\0' */
9061
9062 switch (unsafe_yyjson_get_type(val)) {
9063 case YYJSON_TYPE_RAW:
9064 str_len = unsafe_yyjson_get_len(val);
9065 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9066 check_str_len(str_len);
9067 incr_len(str_len + end_len);
9068 cur = write_raw(cur, str_ptr, str_len);
9069 break;
9070
9071 case YYJSON_TYPE_STR:
9072 str_len = unsafe_yyjson_get_len(val);
9073 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9074 check_str_len(str_len);
9075 incr_len(str_len * 6 + 2 + end_len);
9076 if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
9077 cur = write_str_noesc(cur, str_ptr, str_len);
9078 } else {
9079 cur = write_str(cur, esc, inv, str_ptr, str_len, enc_table);
9080 if (unlikely(!cur)) goto fail_str;
9081 }
9082 break;
9083
9084 case YYJSON_TYPE_NUM:
9085 incr_len(FP_BUF_LEN + end_len);
9086 cur = write_num(cur, val, flg);
9087 if (unlikely(!cur)) goto fail_num;
9088 break;
9089
9090 case YYJSON_TYPE_BOOL:
9091 incr_len(8);
9092 cur = write_bool(cur, unsafe_yyjson_get_bool(val));
9093 break;
9094
9095 case YYJSON_TYPE_NULL:
9096 incr_len(8);
9097 cur = write_null(cur);
9098 break;
9099
9100 case YYJSON_TYPE_ARR:
9101 incr_len(2 + end_len);
9102 byte_copy_2(cur, "[]");
9103 cur += 2;
9104 break;
9105
9106 case YYJSON_TYPE_OBJ:
9107 incr_len(2 + end_len);
9108 byte_copy_2(cur, "{}");
9109 cur += 2;
9110 break;
9111
9112 default:
9113 goto fail_type;
9114 }
9115
9116 if (newline) *cur++ = '\n';
9117 *cur = '\0';
9118 *dat_len = (usize)(cur - hdr);
9119 memset(err, 0, sizeof(yyjson_write_err));
9120 return hdr;
9121
9122fail_alloc: return_err(MEMORY_ALLOCATION, MSG_MALLOC);
9123fail_type: return_err(INVALID_VALUE_TYPE, MSG_ERR_TYPE);
9124fail_num: return_err(NAN_OR_INF, MSG_NAN_INF);
9125fail_str: return_err(INVALID_STRING, MSG_ERR_UTF8);
9126
9127#undef return_err
9128#undef check_str_len
9129#undef incr_len
9130}
9131
9132/** Write JSON document minify.
9133 The root of this document should be a non-empty container. */
9134static_inline u8 *write_root_minify(const yyjson_val *root,
9135 const yyjson_write_flag flg,
9136 const yyjson_alc alc,
9137 char *buf, usize *dat_len,
9138 yyjson_write_err *err) {
9139#define return_err(_code, _msg) do { \
9140 *dat_len = 0; \
9141 err->code = YYJSON_WRITE_ERROR_##_code; \
9142 err->msg = _msg; \
9143 if (hdr) alc.free(alc.ctx, hdr); \
9144 return NULL; \
9145} while (false)
9146
9147#define incr_len(_len) do { \
9148 ext_len = (usize)(_len); \
9149 if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
9150 usize ctx_pos = (usize)((u8 *)ctx - hdr); \
9151 usize cur_pos = (usize)(cur - hdr); \
9152 ctx_len = (usize)(end - (u8 *)ctx); \
9153 alc_inc = yyjson_max(alc_len / 2, ext_len); \
9154 alc_inc = size_align_up(alc_inc, sizeof(yyjson_write_ctx)); \
9155 if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
9156 goto fail_alloc; \
9157 alc_len += alc_inc; \
9158 tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
9159 if (unlikely(!tmp)) goto fail_alloc; \
9160 ctx_tmp = (yyjson_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
9161 memmove((void *)ctx_tmp, (void *)(tmp + ctx_pos), ctx_len); \
9162 ctx = ctx_tmp; \
9163 cur = tmp + cur_pos; \
9164 end = tmp + alc_len; \
9165 hdr = tmp; \
9166 } \
9167} while (false)
9168
9169#define check_str_len(_len) do { \
9170 if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
9171 goto fail_alloc; \
9172} while (false)
9173
9174 yyjson_val *val;
9175 yyjson_type val_type;
9176 usize ctn_len, ctn_len_tmp;
9177 bool ctn_obj, ctn_obj_tmp, is_key;
9178 u8 *hdr, *cur, *end, *tmp;
9179 yyjson_write_ctx *ctx, *ctx_tmp;
9180 usize alc_len, alc_inc, ctx_len, ext_len, str_len;
9181 const u8 *str_ptr;
9182 const char_enc_type *enc_table = get_enc_table_with_flag(flg);
9183 bool cpy = (enc_table == enc_table_cpy);
9184 bool esc = has_flg(ESCAPE_UNICODE) != 0;
9185 bool inv = has_allow(INVALID_UNICODE) != 0;
9186 bool newline = has_flg(NEWLINE_AT_END) != 0;
9187
9188 if (buf) {
9189 hdr = (u8 *)buf;
9190 alc_len = *dat_len;
9191 alc_len = size_align_down(alc_len, sizeof(yyjson_write_ctx));
9192 if (alc_len <= sizeof(yyjson_write_ctx)) goto fail_alloc;
9193 } else {
9194 alc_len = root->uni.ofs / sizeof(yyjson_val);
9195 alc_len = alc_len * YYJSON_WRITER_ESTIMATED_MINIFY_RATIO + 64;
9196 alc_len = size_align_up(alc_len, sizeof(yyjson_write_ctx));
9197 hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
9198 if (!hdr) goto fail_alloc;
9199 }
9200 cur = hdr;
9201 end = hdr + alc_len;
9202 ctx = (yyjson_write_ctx *)(void *)end;
9203
9204doc_begin:
9205 val = constcast(yyjson_val *)root;
9206 val_type = unsafe_yyjson_get_type(val);
9207 ctn_obj = (val_type == YYJSON_TYPE_OBJ);
9208 ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
9209 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
9210 val++;
9211
9212val_begin:
9213 val_type = unsafe_yyjson_get_type(val);
9214 if (val_type == YYJSON_TYPE_STR) {
9215 is_key = ((u8)ctn_obj & (u8)~ctn_len);
9216 str_len = unsafe_yyjson_get_len(val);
9217 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9218 check_str_len(str_len);
9219 incr_len(str_len * 6 + 16);
9220 if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
9221 cur = write_str_noesc(cur, str_ptr, str_len);
9222 } else {
9223 cur = write_str(cur, esc, inv, str_ptr, str_len, enc_table);
9224 if (unlikely(!cur)) goto fail_str;
9225 }
9226 *cur++ = is_key ? ':' : ',';
9227 goto val_end;
9228 }
9229 if (val_type == YYJSON_TYPE_NUM) {
9230 incr_len(FP_BUF_LEN);
9231 cur = write_num(cur, val, flg);
9232 if (unlikely(!cur)) goto fail_num;
9233 *cur++ = ',';
9234 goto val_end;
9235 }
9236 if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
9237 (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
9238 ctn_len_tmp = unsafe_yyjson_get_len(val);
9239 ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
9240 incr_len(2 * sizeof(*ctx));
9241 if (unlikely(ctn_len_tmp == 0)) {
9242 /* write empty container */
9243 *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
9244 *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
9245 *cur++ = ',';
9246 goto val_end;
9247 } else {
9248 /* push context, setup new container */
9249 yyjson_write_ctx_set(--ctx, ctn_len, ctn_obj);
9250 ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
9251 ctn_obj = ctn_obj_tmp;
9252 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
9253 val++;
9254 goto val_begin;
9255 }
9256 }
9257 if (val_type == YYJSON_TYPE_BOOL) {
9258 incr_len(16);
9259 cur = write_bool(cur, unsafe_yyjson_get_bool(val));
9260 cur++;
9261 goto val_end;
9262 }
9263 if (val_type == YYJSON_TYPE_NULL) {
9264 incr_len(16);
9265 cur = write_null(cur);
9266 cur++;
9267 goto val_end;
9268 }
9269 if (val_type == YYJSON_TYPE_RAW) {
9270 str_len = unsafe_yyjson_get_len(val);
9271 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9272 check_str_len(str_len);
9273 incr_len(str_len + 2);
9274 cur = write_raw(cur, str_ptr, str_len);
9275 *cur++ = ',';
9276 goto val_end;
9277 }
9278 goto fail_type;
9279
9280val_end:
9281 val++;
9282 ctn_len--;
9283 if (unlikely(ctn_len == 0)) goto ctn_end;
9284 goto val_begin;
9285
9286ctn_end:
9287 cur--;
9288 *cur++ = (u8)(']' | ((u8)ctn_obj << 5));
9289 *cur++ = ',';
9290 if (unlikely((u8 *)ctx >= end)) goto doc_end;
9291 yyjson_write_ctx_get(ctx++, &ctn_len, &ctn_obj);
9292 ctn_len--;
9293 if (likely(ctn_len > 0)) {
9294 goto val_begin;
9295 } else {
9296 goto ctn_end;
9297 }
9298
9299doc_end:
9300 if (newline) {
9301 incr_len(2);
9302 *(cur - 1) = '\n';
9303 cur++;
9304 }
9305 *--cur = '\0';
9306 *dat_len = (usize)(cur - hdr);
9307 memset(err, 0, sizeof(yyjson_write_err));
9308 return hdr;
9309
9310fail_alloc: return_err(MEMORY_ALLOCATION, MSG_MALLOC);
9311fail_type: return_err(INVALID_VALUE_TYPE, MSG_ERR_TYPE);
9312fail_num: return_err(NAN_OR_INF, MSG_NAN_INF);
9313fail_str: return_err(INVALID_STRING, MSG_ERR_UTF8);
9314
9315#undef return_err
9316#undef incr_len
9317#undef check_str_len
9318}
9319
9320/** Write JSON document pretty.
9321 The root of this document should be a non-empty container. */
9322static_inline u8 *write_root_pretty(const yyjson_val *root,
9323 const yyjson_write_flag flg,
9324 const yyjson_alc alc,
9325 char *buf, usize *dat_len,
9326 yyjson_write_err *err) {
9327#define return_err(_code, _msg) do { \
9328 *dat_len = 0; \
9329 err->code = YYJSON_WRITE_ERROR_##_code; \
9330 err->msg = _msg; \
9331 if (hdr) alc.free(alc.ctx, hdr); \
9332 return NULL; \
9333} while (false)
9334
9335#define incr_len(_len) do { \
9336 ext_len = (usize)(_len); \
9337 if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
9338 usize ctx_pos = (usize)((u8 *)ctx - hdr); \
9339 usize cur_pos = (usize)(cur - hdr); \
9340 ctx_len = (usize)(end - (u8 *)ctx); \
9341 alc_inc = yyjson_max(alc_len / 2, ext_len); \
9342 alc_inc = size_align_up(alc_inc, sizeof(yyjson_write_ctx)); \
9343 if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
9344 goto fail_alloc; \
9345 alc_len += alc_inc; \
9346 tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
9347 if (unlikely(!tmp)) goto fail_alloc; \
9348 ctx_tmp = (yyjson_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
9349 memmove((void *)ctx_tmp, (void *)(tmp + ctx_pos), ctx_len); \
9350 ctx = ctx_tmp; \
9351 cur = tmp + cur_pos; \
9352 end = tmp + alc_len; \
9353 hdr = tmp; \
9354 } \
9355} while (false)
9356
9357#define check_str_len(_len) do { \
9358 if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
9359 goto fail_alloc; \
9360} while (false)
9361
9362 yyjson_val *val;
9363 yyjson_type val_type;
9364 usize ctn_len, ctn_len_tmp;
9365 bool ctn_obj, ctn_obj_tmp, is_key, no_indent;
9366 u8 *hdr, *cur, *end, *tmp;
9367 yyjson_write_ctx *ctx, *ctx_tmp;
9368 usize alc_len, alc_inc, ctx_len, ext_len, str_len, level;
9369 const u8 *str_ptr;
9370 const char_enc_type *enc_table = get_enc_table_with_flag(flg);
9371 bool cpy = (enc_table == enc_table_cpy);
9372 bool esc = has_flg(ESCAPE_UNICODE) != 0;
9373 bool inv = has_allow(INVALID_UNICODE) != 0;
9374 usize spaces = has_flg(PRETTY_TWO_SPACES) ? 2 : 4;
9375 bool newline = has_flg(NEWLINE_AT_END) != 0;
9376
9377 if (buf) {
9378 hdr = (u8 *)buf;
9379 alc_len = *dat_len;
9380 alc_len = size_align_down(alc_len, sizeof(yyjson_write_ctx));
9381 if (alc_len <= sizeof(yyjson_write_ctx)) goto fail_alloc;
9382 } else {
9383 alc_len = root->uni.ofs / sizeof(yyjson_val);
9384 alc_len = alc_len * YYJSON_WRITER_ESTIMATED_PRETTY_RATIO + 64;
9385 alc_len = size_align_up(alc_len, sizeof(yyjson_write_ctx));
9386 hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
9387 if (!hdr) goto fail_alloc;
9388 }
9389 cur = hdr;
9390 end = hdr + alc_len;
9391 ctx = (yyjson_write_ctx *)(void *)end;
9392
9393doc_begin:
9394 val = constcast(yyjson_val *)root;
9395 val_type = unsafe_yyjson_get_type(val);
9396 ctn_obj = (val_type == YYJSON_TYPE_OBJ);
9397 ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
9398 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
9399 *cur++ = '\n';
9400 val++;
9401 level = 1;
9402
9403val_begin:
9404 val_type = unsafe_yyjson_get_type(val);
9405 if (val_type == YYJSON_TYPE_STR) {
9406 is_key = (bool)((u8)ctn_obj & (u8)~ctn_len);
9407 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
9408 str_len = unsafe_yyjson_get_len(val);
9409 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9410 check_str_len(str_len);
9411 incr_len(str_len * 6 + 16 + (no_indent ? 0 : level * 4));
9412 cur = write_indent(cur, no_indent ? 0 : level, spaces);
9413 if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
9414 cur = write_str_noesc(cur, str_ptr, str_len);
9415 } else {
9416 cur = write_str(cur, esc, inv, str_ptr, str_len, enc_table);
9417 if (unlikely(!cur)) goto fail_str;
9418 }
9419 *cur++ = is_key ? ':' : ',';
9420 *cur++ = is_key ? ' ' : '\n';
9421 goto val_end;
9422 }
9423 if (val_type == YYJSON_TYPE_NUM) {
9424 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
9425 incr_len(FP_BUF_LEN + (no_indent ? 0 : level * 4));
9426 cur = write_indent(cur, no_indent ? 0 : level, spaces);
9427 cur = write_num(cur, val, flg);
9428 if (unlikely(!cur)) goto fail_num;
9429 *cur++ = ',';
9430 *cur++ = '\n';
9431 goto val_end;
9432 }
9433 if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
9434 (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
9435 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
9436 ctn_len_tmp = unsafe_yyjson_get_len(val);
9437 ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
9438 incr_len(2 * sizeof(*ctx) + (no_indent ? 0 : level * 4));
9439 if (unlikely(ctn_len_tmp == 0)) {
9440 /* write empty container */
9441 cur = write_indent(cur, no_indent ? 0 : level, spaces);
9442 *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
9443 *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
9444 *cur++ = ',';
9445 *cur++ = '\n';
9446 goto val_end;
9447 } else {
9448 /* push context, setup new container */
9449 yyjson_write_ctx_set(--ctx, ctn_len, ctn_obj);
9450 ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
9451 ctn_obj = ctn_obj_tmp;
9452 cur = write_indent(cur, no_indent ? 0 : level, spaces);
9453 level++;
9454 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
9455 *cur++ = '\n';
9456 val++;
9457 goto val_begin;
9458 }
9459 }
9460 if (val_type == YYJSON_TYPE_BOOL) {
9461 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
9462 incr_len(16 + (no_indent ? 0 : level * 4));
9463 cur = write_indent(cur, no_indent ? 0 : level, spaces);
9464 cur = write_bool(cur, unsafe_yyjson_get_bool(val));
9465 cur += 2;
9466 goto val_end;
9467 }
9468 if (val_type == YYJSON_TYPE_NULL) {
9469 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
9470 incr_len(16 + (no_indent ? 0 : level * 4));
9471 cur = write_indent(cur, no_indent ? 0 : level, spaces);
9472 cur = write_null(cur);
9473 cur += 2;
9474 goto val_end;
9475 }
9476 if (val_type == YYJSON_TYPE_RAW) {
9477 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
9478 str_len = unsafe_yyjson_get_len(val);
9479 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9480 check_str_len(str_len);
9481 incr_len(str_len + 3 + (no_indent ? 0 : level * 4));
9482 cur = write_indent(cur, no_indent ? 0 : level, spaces);
9483 cur = write_raw(cur, str_ptr, str_len);
9484 *cur++ = ',';
9485 *cur++ = '\n';
9486 goto val_end;
9487 }
9488 goto fail_type;
9489
9490val_end:
9491 val++;
9492 ctn_len--;
9493 if (unlikely(ctn_len == 0)) goto ctn_end;
9494 goto val_begin;
9495
9496ctn_end:
9497 cur -= 2;
9498 *cur++ = '\n';
9499 incr_len(level * 4);
9500 cur = write_indent(cur, --level, spaces);
9501 *cur++ = (u8)(']' | ((u8)ctn_obj << 5));
9502 if (unlikely((u8 *)ctx >= end)) goto doc_end;
9503 yyjson_write_ctx_get(ctx++, &ctn_len, &ctn_obj);
9504 ctn_len--;
9505 *cur++ = ',';
9506 *cur++ = '\n';
9507 if (likely(ctn_len > 0)) {
9508 goto val_begin;
9509 } else {
9510 goto ctn_end;
9511 }
9512
9513doc_end:
9514 if (newline) {
9515 incr_len(2);
9516 *cur++ = '\n';
9517 }
9518 *cur = '\0';
9519 *dat_len = (usize)(cur - hdr);
9520 memset(err, 0, sizeof(yyjson_write_err));
9521 return hdr;
9522
9523fail_alloc: return_err(MEMORY_ALLOCATION, MSG_MALLOC);
9524fail_type: return_err(INVALID_VALUE_TYPE, MSG_ERR_TYPE);
9525fail_num: return_err(NAN_OR_INF, MSG_NAN_INF);
9526fail_str: return_err(INVALID_STRING, MSG_ERR_UTF8);
9527
9528#undef return_err
9529#undef incr_len
9530#undef check_str_len
9531}
9532
9533static char *write_root(const yyjson_val *val,
9534 yyjson_write_flag flg,
9535 const yyjson_alc *alc_ptr,
9536 char *buf, usize *dat_len,
9537 yyjson_write_err *err) {
9538 yyjson_write_err tmp_err;
9539 usize tmp_dat_len;
9540 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
9541 yyjson_val *root = constcast(yyjson_val *)val;
9542
9543 if (!err) err = &tmp_err;
9544 if (!dat_len) dat_len = &tmp_dat_len;
9545
9546 if (unlikely(!root)) {
9547 *dat_len = 0;
9548 err->msg = "input JSON is NULL";
9549 err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;
9550 return NULL;
9551 }
9552
9553 if (!unsafe_yyjson_is_ctn(root) || unsafe_yyjson_get_len(root) == 0) {
9554 return (char *)write_root_single(root, flg, alc, buf, dat_len, err);
9555 } else if (flg & (YYJSON_WRITE_PRETTY | YYJSON_WRITE_PRETTY_TWO_SPACES)) {
9556 return (char *)write_root_pretty(root, flg, alc, buf, dat_len, err);
9557 } else {
9558 return (char *)write_root_minify(root, flg, alc, buf, dat_len, err);
9559 }
9560}
9561
9562
9563
9564/*==============================================================================
9565 * MARK: - JSON Writer (Public)
9566 *============================================================================*/
9567
9568char *yyjson_val_write_opts(const yyjson_val *val,
9569 yyjson_write_flag flg,
9570 const yyjson_alc *alc_ptr,
9571 usize *dat_len,
9572 yyjson_write_err *err) {
9573 return write_root(val, flg, alc_ptr, NULL, dat_len, err);
9574}
9575
9576char *yyjson_write_opts(const yyjson_doc *doc,
9577 yyjson_write_flag flg,
9578 const yyjson_alc *alc_ptr,
9579 usize *dat_len,
9580 yyjson_write_err *err) {
9581 yyjson_val *root = doc ? doc->root : NULL;
9582 return write_root(root, flg, alc_ptr, NULL, dat_len, err);
9583}
9584
9585bool yyjson_val_write_file(const char *path,
9586 const yyjson_val *val,
9587 yyjson_write_flag flg,
9588 const yyjson_alc *alc_ptr,
9589 yyjson_write_err *err) {
9590 yyjson_write_err tmp_err;
9591 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
9592 u8 *dat;
9593 usize dat_len = 0;
9594 yyjson_val *root = constcast(yyjson_val *)val;
9595 bool suc;
9596
9597 if (!err) err = &tmp_err;
9598 if (unlikely(!path || !*path)) {
9599 err->msg = "input path is invalid";
9600 err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;
9601 return false;
9602 }
9603
9604 dat = (u8 *)write_root(root, flg, &alc, NULL, &dat_len, err);
9605 if (unlikely(!dat)) return false;
9606 suc = write_dat_to_file(path, dat, dat_len, err);
9607 alc.free(alc.ctx, dat);
9608 return suc;
9609}
9610
9611bool yyjson_val_write_fp(FILE *fp,
9612 const yyjson_val *val,
9613 yyjson_write_flag flg,
9614 const yyjson_alc *alc_ptr,
9615 yyjson_write_err *err) {
9616 yyjson_write_err tmp_err;
9617 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
9618 u8 *dat;
9619 usize dat_len = 0;
9620 yyjson_val *root = constcast(yyjson_val *)val;
9621 bool suc;
9622
9623 if (!err) err = &tmp_err;
9624 if (unlikely(!fp)) {
9625 err->msg = "input fp is invalid";
9626 err->code = YYJSON_READ_ERROR_INVALID_PARAMETER;
9627 return false;
9628 }
9629
9630 dat = (u8 *)write_root(root, flg, &alc, NULL, &dat_len, err);
9631 if (unlikely(!dat)) return false;
9632 suc = write_dat_to_fp(fp, dat, dat_len, err);
9633 alc.free(alc.ctx, dat);
9634 return suc;
9635}
9636
9637size_t yyjson_val_write_buf(char *buf, size_t buf_len,
9638 const yyjson_val *val,
9639 yyjson_write_flag flg,
9640 yyjson_write_err *err) {
9641 if (unlikely(!buf || !buf_len)) {
9642 if (err) err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
9643 if (err) err->msg = "input buf or buf_len is invalid";
9644 return 0;
9645 } else {
9646 write_root(val, flg, &YYJSON_NULL_ALC, buf, &buf_len, err);
9647 return buf_len;
9648 }
9649}
9650
9651bool yyjson_write_file(const char *path,
9652 const yyjson_doc *doc,
9653 yyjson_write_flag flg,
9654 const yyjson_alc *alc_ptr,
9655 yyjson_write_err *err) {
9656 yyjson_val *root = doc ? doc->root : NULL;
9657 return yyjson_val_write_file(path, root, flg, alc_ptr, err);
9658}
9659
9660bool yyjson_write_fp(FILE *fp,
9661 const yyjson_doc *doc,
9662 yyjson_write_flag flg,
9663 const yyjson_alc *alc_ptr,
9664 yyjson_write_err *err) {
9665 yyjson_val *root = doc ? doc->root : NULL;
9666 return yyjson_val_write_fp(fp, root, flg, alc_ptr, err);
9667}
9668
9669size_t yyjson_write_buf(char *buf, size_t buf_len,
9670 const yyjson_doc *doc,
9671 yyjson_write_flag flg,
9672 yyjson_write_err *err) {
9673 yyjson_val *root = doc ? doc->root : NULL;
9674 return yyjson_val_write_buf(buf, buf_len, root, flg, err);
9675}
9676
9677
9678
9679/*==============================================================================
9680 * MARK: - Mutable JSON Writer Implementation (Private)
9681 *============================================================================*/
9682
9683typedef struct yyjson_mut_write_ctx {
9684 usize tag;
9685 yyjson_mut_val *ctn;
9686} yyjson_mut_write_ctx;
9687
9688static_inline void yyjson_mut_write_ctx_set(yyjson_mut_write_ctx *ctx,
9689 yyjson_mut_val *ctn,
9690 usize size, bool is_obj) {
9691 ctx->tag = (size << 1) | (usize)is_obj;
9692 ctx->ctn = ctn;
9693}
9694
9695static_inline void yyjson_mut_write_ctx_get(yyjson_mut_write_ctx *ctx,
9696 yyjson_mut_val **ctn,
9697 usize *size, bool *is_obj) {
9698 usize tag = ctx->tag;
9699 *size = tag >> 1;
9700 *is_obj = (bool)(tag & 1);
9701 *ctn = ctx->ctn;
9702}
9703
9704/** Get the estimated number of values for the mutable JSON document. */
9705static_inline usize yyjson_mut_doc_estimated_val_num(
9706 const yyjson_mut_doc *doc) {
9707 usize sum = 0;
9708 yyjson_val_chunk *chunk = doc->val_pool.chunks;
9709 while (chunk) {
9710 sum += chunk->chunk_size / sizeof(yyjson_mut_val) - 1;
9711 if (chunk == doc->val_pool.chunks) {
9712 sum -= (usize)(doc->val_pool.end - doc->val_pool.cur);
9713 }
9714 chunk = chunk->next;
9715 }
9716 return sum;
9717}
9718
9719/** Write single JSON value. */
9720static_inline u8 *mut_write_root_single(yyjson_mut_val *val,
9721 yyjson_write_flag flg,
9722 yyjson_alc alc,
9723 char *buf, usize *dat_len,
9724 yyjson_write_err *err) {
9725 return write_root_single((yyjson_val *)val, flg, alc, buf, dat_len, err);
9726}
9727
9728/** Write JSON document minify.
9729 The root of this document should be a non-empty container. */
9730static_inline u8 *mut_write_root_minify(const yyjson_mut_val *root,
9731 usize estimated_val_num,
9732 yyjson_write_flag flg,
9733 yyjson_alc alc,
9734 char *buf, usize *dat_len,
9735 yyjson_write_err *err) {
9736#define return_err(_code, _msg) do { \
9737 *dat_len = 0; \
9738 err->code = YYJSON_WRITE_ERROR_##_code; \
9739 err->msg = _msg; \
9740 if (hdr) alc.free(alc.ctx, hdr); \
9741 return NULL; \
9742} while (false)
9743
9744#define incr_len(_len) do { \
9745 ext_len = (usize)(_len); \
9746 if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
9747 usize ctx_pos = (usize)((u8 *)ctx - hdr); \
9748 usize cur_pos = (usize)(cur - hdr); \
9749 ctx_len = (usize)(end - (u8 *)ctx); \
9750 alc_inc = yyjson_max(alc_len / 2, ext_len); \
9751 alc_inc = size_align_up(alc_inc, sizeof(yyjson_mut_write_ctx)); \
9752 if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
9753 goto fail_alloc; \
9754 alc_len += alc_inc; \
9755 tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
9756 if (unlikely(!tmp)) goto fail_alloc; \
9757 ctx_tmp = (yyjson_mut_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
9758 memmove((void *)ctx_tmp, (void *)(tmp + ctx_pos), ctx_len); \
9759 ctx = ctx_tmp; \
9760 cur = tmp + cur_pos; \
9761 end = tmp + alc_len; \
9762 hdr = tmp; \
9763 } \
9764} while (false)
9765
9766#define check_str_len(_len) do { \
9767 if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
9768 goto fail_alloc; \
9769} while (false)
9770
9771 yyjson_mut_val *val, *ctn;
9772 yyjson_type val_type;
9773 usize ctn_len, ctn_len_tmp;
9774 bool ctn_obj, ctn_obj_tmp, is_key;
9775 u8 *hdr, *cur, *end, *tmp;
9776 yyjson_mut_write_ctx *ctx, *ctx_tmp;
9777 usize alc_len, alc_inc, ctx_len, ext_len, str_len;
9778 const u8 *str_ptr;
9779 const char_enc_type *enc_table = get_enc_table_with_flag(flg);
9780 bool cpy = (enc_table == enc_table_cpy);
9781 bool esc = has_flg(ESCAPE_UNICODE) != 0;
9782 bool inv = has_allow(INVALID_UNICODE) != 0;
9783 bool newline = has_flg(NEWLINE_AT_END) != 0;
9784
9785 if (buf) {
9786 hdr = (u8 *)buf;
9787 alc_len = *dat_len;
9788 alc_len = size_align_down(alc_len, sizeof(yyjson_mut_write_ctx));
9789 if (alc_len <= sizeof(yyjson_mut_write_ctx)) goto fail_alloc;
9790 } else {
9791 alc_len = estimated_val_num * YYJSON_WRITER_ESTIMATED_MINIFY_RATIO + 64;
9792 alc_len = size_align_up(alc_len, sizeof(yyjson_mut_write_ctx));
9793 hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
9794 if (!hdr) goto fail_alloc;
9795 }
9796 cur = hdr;
9797 end = hdr + alc_len;
9798 ctx = (yyjson_mut_write_ctx *)(void *)end;
9799
9800doc_begin:
9801 val = constcast(yyjson_mut_val *)root;
9802 val_type = unsafe_yyjson_get_type(val);
9803 ctn_obj = (val_type == YYJSON_TYPE_OBJ);
9804 ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
9805 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
9806 ctn = val;
9807 val = (yyjson_mut_val *)val->uni.ptr; /* tail */
9808 val = ctn_obj ? val->next->next : val->next;
9809
9810val_begin:
9811 val_type = unsafe_yyjson_get_type(val);
9812 if (val_type == YYJSON_TYPE_STR) {
9813 is_key = ((u8)ctn_obj & (u8)~ctn_len);
9814 str_len = unsafe_yyjson_get_len(val);
9815 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9816 check_str_len(str_len);
9817 incr_len(str_len * 6 + 16);
9818 if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
9819 cur = write_str_noesc(cur, str_ptr, str_len);
9820 } else {
9821 cur = write_str(cur, esc, inv, str_ptr, str_len, enc_table);
9822 if (unlikely(!cur)) goto fail_str;
9823 }
9824 *cur++ = is_key ? ':' : ',';
9825 goto val_end;
9826 }
9827 if (val_type == YYJSON_TYPE_NUM) {
9828 incr_len(FP_BUF_LEN);
9829 cur = write_num(cur, (yyjson_val *)val, flg);
9830 if (unlikely(!cur)) goto fail_num;
9831 *cur++ = ',';
9832 goto val_end;
9833 }
9834 if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
9835 (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
9836 ctn_len_tmp = unsafe_yyjson_get_len(val);
9837 ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
9838 incr_len(2 * sizeof(*ctx));
9839 if (unlikely(ctn_len_tmp == 0)) {
9840 /* write empty container */
9841 *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
9842 *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
9843 *cur++ = ',';
9844 goto val_end;
9845 } else {
9846 /* push context, setup new container */
9847 yyjson_mut_write_ctx_set(--ctx, ctn, ctn_len, ctn_obj);
9848 ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
9849 ctn_obj = ctn_obj_tmp;
9850 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
9851 ctn = val;
9852 val = (yyjson_mut_val *)ctn->uni.ptr; /* tail */
9853 val = ctn_obj ? val->next->next : val->next;
9854 goto val_begin;
9855 }
9856 }
9857 if (val_type == YYJSON_TYPE_BOOL) {
9858 incr_len(16);
9859 cur = write_bool(cur, unsafe_yyjson_get_bool(val));
9860 cur++;
9861 goto val_end;
9862 }
9863 if (val_type == YYJSON_TYPE_NULL) {
9864 incr_len(16);
9865 cur = write_null(cur);
9866 cur++;
9867 goto val_end;
9868 }
9869 if (val_type == YYJSON_TYPE_RAW) {
9870 str_len = unsafe_yyjson_get_len(val);
9871 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
9872 check_str_len(str_len);
9873 incr_len(str_len + 2);
9874 cur = write_raw(cur, str_ptr, str_len);
9875 *cur++ = ',';
9876 goto val_end;
9877 }
9878 goto fail_type;
9879
9880val_end:
9881 ctn_len--;
9882 if (unlikely(ctn_len == 0)) goto ctn_end;
9883 val = val->next;
9884 goto val_begin;
9885
9886ctn_end:
9887 cur--;
9888 *cur++ = (u8)(']' | ((u8)ctn_obj << 5));
9889 *cur++ = ',';
9890 if (unlikely((u8 *)ctx >= end)) goto doc_end;
9891 val = ctn->next;
9892 yyjson_mut_write_ctx_get(ctx++, &ctn, &ctn_len, &ctn_obj);
9893 ctn_len--;
9894 if (likely(ctn_len > 0)) {
9895 goto val_begin;
9896 } else {
9897 goto ctn_end;
9898 }
9899
9900doc_end:
9901 if (newline) {
9902 incr_len(2);
9903 *(cur - 1) = '\n';
9904 cur++;
9905 }
9906 *--cur = '\0';
9907 *dat_len = (usize)(cur - hdr);
9908 err->code = YYJSON_WRITE_SUCCESS;
9909 err->msg = NULL;
9910 return hdr;
9911
9912fail_alloc: return_err(MEMORY_ALLOCATION, MSG_MALLOC);
9913fail_type: return_err(INVALID_VALUE_TYPE, MSG_ERR_TYPE);
9914fail_num: return_err(NAN_OR_INF, MSG_NAN_INF);
9915fail_str: return_err(INVALID_STRING, MSG_ERR_UTF8);
9916
9917#undef return_err
9918#undef incr_len
9919#undef check_str_len
9920}
9921
9922/** Write JSON document pretty.
9923 The root of this document should be a non-empty container. */
9924static_inline u8 *mut_write_root_pretty(const yyjson_mut_val *root,
9925 usize estimated_val_num,
9926 yyjson_write_flag flg,
9927 yyjson_alc alc,
9928 char *buf, usize *dat_len,
9929 yyjson_write_err *err) {
9930#define return_err(_code, _msg) do { \
9931 *dat_len = 0; \
9932 err->code = YYJSON_WRITE_ERROR_##_code; \
9933 err->msg = _msg; \
9934 if (hdr) alc.free(alc.ctx, hdr); \
9935 return NULL; \
9936} while (false)
9937
9938#define incr_len(_len) do { \
9939 ext_len = (usize)(_len); \
9940 if (unlikely((u8 *)(cur + ext_len) >= (u8 *)ctx)) { \
9941 usize ctx_pos = (usize)((u8 *)ctx - hdr); \
9942 usize cur_pos = (usize)(cur - hdr); \
9943 ctx_len = (usize)(end - (u8 *)ctx); \
9944 alc_inc = yyjson_max(alc_len / 2, ext_len); \
9945 alc_inc = size_align_up(alc_inc, sizeof(yyjson_mut_write_ctx)); \
9946 if ((sizeof(usize) < 8) && size_add_is_overflow(alc_len, alc_inc)) \
9947 goto fail_alloc; \
9948 alc_len += alc_inc; \
9949 tmp = (u8 *)alc.realloc(alc.ctx, hdr, alc_len - alc_inc, alc_len); \
9950 if (unlikely(!tmp)) goto fail_alloc; \
9951 ctx_tmp = (yyjson_mut_write_ctx *)(void *)(tmp + (alc_len - ctx_len)); \
9952 memmove((void *)ctx_tmp, (void *)(tmp + ctx_pos), ctx_len); \
9953 ctx = ctx_tmp; \
9954 cur = tmp + cur_pos; \
9955 end = tmp + alc_len; \
9956 hdr = tmp; \
9957 } \
9958} while (false)
9959
9960#define check_str_len(_len) do { \
9961 if ((sizeof(usize) < 8) && (_len >= (USIZE_MAX - 16) / 6)) \
9962 goto fail_alloc; \
9963} while (false)
9964
9965 yyjson_mut_val *val, *ctn;
9966 yyjson_type val_type;
9967 usize ctn_len, ctn_len_tmp;
9968 bool ctn_obj, ctn_obj_tmp, is_key, no_indent;
9969 u8 *hdr, *cur, *end, *tmp;
9970 yyjson_mut_write_ctx *ctx, *ctx_tmp;
9971 usize alc_len, alc_inc, ctx_len, ext_len, str_len, level;
9972 const u8 *str_ptr;
9973 const char_enc_type *enc_table = get_enc_table_with_flag(flg);
9974 bool cpy = (enc_table == enc_table_cpy);
9975 bool esc = has_flg(ESCAPE_UNICODE) != 0;
9976 bool inv = has_allow(INVALID_UNICODE) != 0;
9977 usize spaces = has_flg(PRETTY_TWO_SPACES) ? 2 : 4;
9978 bool newline = has_flg(NEWLINE_AT_END) != 0;
9979
9980 if (buf) {
9981 hdr = (u8 *)buf;
9982 alc_len = *dat_len;
9983 alc_len = size_align_down(alc_len, sizeof(yyjson_mut_write_ctx));
9984 if (alc_len <= sizeof(yyjson_mut_write_ctx)) goto fail_alloc;
9985 } else {
9986 alc_len = estimated_val_num * YYJSON_WRITER_ESTIMATED_PRETTY_RATIO + 64;
9987 alc_len = size_align_up(alc_len, sizeof(yyjson_mut_write_ctx));
9988 hdr = (u8 *)alc.malloc(alc.ctx, alc_len);
9989 if (!hdr) goto fail_alloc;
9990 }
9991 cur = hdr;
9992 end = hdr + alc_len;
9993 ctx = (yyjson_mut_write_ctx *)(void *)end;
9994
9995doc_begin:
9996 val = constcast(yyjson_mut_val *)root;
9997 val_type = unsafe_yyjson_get_type(val);
9998 ctn_obj = (val_type == YYJSON_TYPE_OBJ);
9999 ctn_len = unsafe_yyjson_get_len(val) << (u8)ctn_obj;
10000 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
10001 *cur++ = '\n';
10002 ctn = val;
10003 val = (yyjson_mut_val *)val->uni.ptr; /* tail */
10004 val = ctn_obj ? val->next->next : val->next;
10005 level = 1;
10006
10007val_begin:
10008 val_type = unsafe_yyjson_get_type(val);
10009 if (val_type == YYJSON_TYPE_STR) {
10010 is_key = (bool)((u8)ctn_obj & (u8)~ctn_len);
10011 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
10012 str_len = unsafe_yyjson_get_len(val);
10013 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
10014 check_str_len(str_len);
10015 incr_len(str_len * 6 + 16 + (no_indent ? 0 : level * 4));
10016 cur = write_indent(cur, no_indent ? 0 : level, spaces);
10017 if (likely(cpy) && unsafe_yyjson_get_subtype(val)) {
10018 cur = write_str_noesc(cur, str_ptr, str_len);
10019 } else {
10020 cur = write_str(cur, esc, inv, str_ptr, str_len, enc_table);
10021 if (unlikely(!cur)) goto fail_str;
10022 }
10023 *cur++ = is_key ? ':' : ',';
10024 *cur++ = is_key ? ' ' : '\n';
10025 goto val_end;
10026 }
10027 if (val_type == YYJSON_TYPE_NUM) {
10028 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
10029 incr_len(FP_BUF_LEN + (no_indent ? 0 : level * 4));
10030 cur = write_indent(cur, no_indent ? 0 : level, spaces);
10031 cur = write_num(cur, (yyjson_val *)val, flg);
10032 if (unlikely(!cur)) goto fail_num;
10033 *cur++ = ',';
10034 *cur++ = '\n';
10035 goto val_end;
10036 }
10037 if ((val_type & (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) ==
10038 (YYJSON_TYPE_ARR & YYJSON_TYPE_OBJ)) {
10039 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
10040 ctn_len_tmp = unsafe_yyjson_get_len(val);
10041 ctn_obj_tmp = (val_type == YYJSON_TYPE_OBJ);
10042 incr_len(2 * sizeof(*ctx) + (no_indent ? 0 : level * 4));
10043 if (unlikely(ctn_len_tmp == 0)) {
10044 /* write empty container */
10045 cur = write_indent(cur, no_indent ? 0 : level, spaces);
10046 *cur++ = (u8)('[' | ((u8)ctn_obj_tmp << 5));
10047 *cur++ = (u8)(']' | ((u8)ctn_obj_tmp << 5));
10048 *cur++ = ',';
10049 *cur++ = '\n';
10050 goto val_end;
10051 } else {
10052 /* push context, setup new container */
10053 yyjson_mut_write_ctx_set(--ctx, ctn, ctn_len, ctn_obj);
10054 ctn_len = ctn_len_tmp << (u8)ctn_obj_tmp;
10055 ctn_obj = ctn_obj_tmp;
10056 cur = write_indent(cur, no_indent ? 0 : level, spaces);
10057 level++;
10058 *cur++ = (u8)('[' | ((u8)ctn_obj << 5));
10059 *cur++ = '\n';
10060 ctn = val;
10061 val = (yyjson_mut_val *)ctn->uni.ptr; /* tail */
10062 val = ctn_obj ? val->next->next : val->next;
10063 goto val_begin;
10064 }
10065 }
10066 if (val_type == YYJSON_TYPE_BOOL) {
10067 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
10068 incr_len(16 + (no_indent ? 0 : level * 4));
10069 cur = write_indent(cur, no_indent ? 0 : level, spaces);
10070 cur = write_bool(cur, unsafe_yyjson_get_bool(val));
10071 cur += 2;
10072 goto val_end;
10073 }
10074 if (val_type == YYJSON_TYPE_NULL) {
10075 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
10076 incr_len(16 + (no_indent ? 0 : level * 4));
10077 cur = write_indent(cur, no_indent ? 0 : level, spaces);
10078 cur = write_null(cur);
10079 cur += 2;
10080 goto val_end;
10081 }
10082 if (val_type == YYJSON_TYPE_RAW) {
10083 no_indent = (bool)((u8)ctn_obj & (u8)ctn_len);
10084 str_len = unsafe_yyjson_get_len(val);
10085 str_ptr = (const u8 *)unsafe_yyjson_get_str(val);
10086 check_str_len(str_len);
10087 incr_len(str_len + 3 + (no_indent ? 0 : level * 4));
10088 cur = write_indent(cur, no_indent ? 0 : level, spaces);
10089 cur = write_raw(cur, str_ptr, str_len);
10090 *cur++ = ',';
10091 *cur++ = '\n';
10092 goto val_end;
10093 }
10094 goto fail_type;
10095
10096val_end:
10097 ctn_len--;
10098 if (unlikely(ctn_len == 0)) goto ctn_end;
10099 val = val->next;
10100 goto val_begin;
10101
10102ctn_end:
10103 cur -= 2;
10104 *cur++ = '\n';
10105 incr_len(level * 4);
10106 cur = write_indent(cur, --level, spaces);
10107 *cur++ = (u8)(']' | ((u8)ctn_obj << 5));
10108 if (unlikely((u8 *)ctx >= end)) goto doc_end;
10109 val = ctn->next;
10110 yyjson_mut_write_ctx_get(ctx++, &ctn, &ctn_len, &ctn_obj);
10111 ctn_len--;
10112 *cur++ = ',';
10113 *cur++ = '\n';
10114 if (likely(ctn_len > 0)) {
10115 goto val_begin;
10116 } else {
10117 goto ctn_end;
10118 }
10119
10120doc_end:
10121 if (newline) {
10122 incr_len(2);
10123 *cur++ = '\n';
10124 }
10125 *cur = '\0';
10126 *dat_len = (usize)(cur - hdr);
10127 err->code = YYJSON_WRITE_SUCCESS;
10128 err->msg = NULL;
10129 return hdr;
10130
10131fail_alloc: return_err(MEMORY_ALLOCATION, MSG_MALLOC);
10132fail_type: return_err(INVALID_VALUE_TYPE, MSG_ERR_TYPE);
10133fail_num: return_err(NAN_OR_INF, MSG_NAN_INF);
10134fail_str: return_err(INVALID_STRING, MSG_ERR_UTF8);
10135
10136#undef return_err
10137#undef incr_len
10138#undef check_str_len
10139}
10140
10141static char *mut_write_root(const yyjson_mut_val *val,
10142 usize estimated_val_num,
10143 yyjson_write_flag flg,
10144 const yyjson_alc *alc_ptr,
10145 char *buf, usize *dat_len,
10146 yyjson_write_err *err) {
10147 yyjson_write_err tmp_err;
10148 usize tmp_dat_len;
10149 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
10150 yyjson_mut_val *root = constcast(yyjson_mut_val *)val;
10151
10152 if (!err) err = &tmp_err;
10153 if (!dat_len) dat_len = &tmp_dat_len;
10154
10155 if (unlikely(!root)) {
10156 *dat_len = 0;
10157 err->msg = "input JSON is NULL";
10158 err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
10159 return NULL;
10160 }
10161
10162 if (!unsafe_yyjson_is_ctn(root) || unsafe_yyjson_get_len(root) == 0) {
10163 return (char *)mut_write_root_single(root, flg, alc, buf, dat_len, err);
10164 } else if (flg & (YYJSON_WRITE_PRETTY | YYJSON_WRITE_PRETTY_TWO_SPACES)) {
10165 return (char *)mut_write_root_pretty(root, estimated_val_num,
10166 flg, alc, buf, dat_len, err);
10167 } else {
10168 return (char *)mut_write_root_minify(root, estimated_val_num,
10169 flg, alc, buf, dat_len, err);
10170 }
10171}
10172
10173
10174
10175/*==============================================================================
10176 * MARK: - Mutable JSON Writer (Public)
10177 *============================================================================*/
10178
10179char *yyjson_mut_val_write_opts(const yyjson_mut_val *val,
10180 yyjson_write_flag flg,
10181 const yyjson_alc *alc_ptr,
10182 usize *dat_len,
10183 yyjson_write_err *err) {
10184 return mut_write_root(val, 0, flg, alc_ptr, NULL, dat_len, err);
10185}
10186
10187char *yyjson_mut_write_opts(const yyjson_mut_doc *doc,
10188 yyjson_write_flag flg,
10189 const yyjson_alc *alc_ptr,
10190 usize *dat_len,
10191 yyjson_write_err *err) {
10192 yyjson_mut_val *root;
10193 usize estimated_val_num;
10194 if (likely(doc)) {
10195 root = doc->root;
10196 estimated_val_num = yyjson_mut_doc_estimated_val_num(doc);
10197 } else {
10198 root = NULL;
10199 estimated_val_num = 0;
10200 }
10201 return mut_write_root(root, estimated_val_num,
10202 flg, alc_ptr, NULL, dat_len, err);
10203}
10204
10205bool yyjson_mut_val_write_file(const char *path,
10206 const yyjson_mut_val *val,
10207 yyjson_write_flag flg,
10208 const yyjson_alc *alc_ptr,
10209 yyjson_write_err *err) {
10210 yyjson_write_err tmp_err;
10211 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
10212 u8 *dat;
10213 usize dat_len = 0;
10214 yyjson_mut_val *root = constcast(yyjson_mut_val *)val;
10215 bool suc;
10216
10217 if (!err) err = &tmp_err;
10218 if (unlikely(!path || !*path)) {
10219 err->msg = "input path is invalid";
10220 err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
10221 return false;
10222 }
10223
10224 dat = (u8 *)yyjson_mut_val_write_opts(root, flg, &alc, &dat_len, err);
10225 if (unlikely(!dat)) return false;
10226 suc = write_dat_to_file(path, dat, dat_len, err);
10227 alc.free(alc.ctx, dat);
10228 return suc;
10229}
10230
10231bool yyjson_mut_val_write_fp(FILE *fp,
10232 const yyjson_mut_val *val,
10233 yyjson_write_flag flg,
10234 const yyjson_alc *alc_ptr,
10235 yyjson_write_err *err) {
10236 yyjson_write_err tmp_err;
10237 yyjson_alc alc = alc_ptr ? *alc_ptr : YYJSON_DEFAULT_ALC;
10238 u8 *dat;
10239 usize dat_len = 0;
10240 yyjson_mut_val *root = constcast(yyjson_mut_val *)val;
10241 bool suc;
10242
10243 if (!err) err = &tmp_err;
10244 if (unlikely(!fp)) {
10245 err->msg = "input fp is invalid";
10246 err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
10247 return false;
10248 }
10249
10250 dat = (u8 *)yyjson_mut_val_write_opts(root, flg, &alc, &dat_len, err);
10251 if (unlikely(!dat)) return false;
10252 suc = write_dat_to_fp(fp, dat, dat_len, err);
10253 alc.free(alc.ctx, dat);
10254 return suc;
10255}
10256
10257size_t yyjson_mut_val_write_buf(char *buf, size_t buf_len,
10258 const yyjson_mut_val *val,
10259 yyjson_write_flag flg,
10260 yyjson_write_err *err) {
10261 if (unlikely(!buf || !buf_len)) {
10262 if (err) err->code = YYJSON_WRITE_ERROR_INVALID_PARAMETER;
10263 if (err) err->msg = "input buf or buf_len is invalid";
10264 return 0;
10265 } else {
10266 mut_write_root(val, 0, flg, &YYJSON_NULL_ALC, buf, &buf_len, err);
10267 return buf_len;
10268 }
10269}
10270
10271bool yyjson_mut_write_file(const char *path,
10272 const yyjson_mut_doc *doc,
10273 yyjson_write_flag flg,
10274 const yyjson_alc *alc_ptr,
10275 yyjson_write_err *err) {
10276 yyjson_mut_val *root = doc ? doc->root : NULL;
10277 return yyjson_mut_val_write_file(path, root, flg, alc_ptr, err);
10278}
10279
10280bool yyjson_mut_write_fp(FILE *fp,
10281 const yyjson_mut_doc *doc,
10282 yyjson_write_flag flg,
10283 const yyjson_alc *alc_ptr,
10284 yyjson_write_err *err) {
10285 yyjson_mut_val *root = doc ? doc->root : NULL;
10286 return yyjson_mut_val_write_fp(fp, root, flg, alc_ptr, err);
10287}
10288
10289size_t yyjson_mut_write_buf(char *buf, size_t buf_len,
10290 const yyjson_mut_doc *doc,
10291 yyjson_write_flag flg,
10292 yyjson_write_err *err) {
10293 yyjson_mut_val *root = doc ? doc->root : NULL;
10294 return yyjson_mut_val_write_buf(buf, buf_len, root, flg, err);
10295}
10296
10297#undef has_flg
10298#undef has_allow
10299#endif /* YYJSON_DISABLE_WRITER */
10300
10301
10302
10303#if !YYJSON_DISABLE_UTILS
10304
10305/*==============================================================================
10306 * MARK: - JSON Pointer API (RFC 6901) (Public)
10307 *============================================================================*/
10308
10309/**
10310 Get a token from JSON pointer string.
10311 @param ptr [in] string that points to current token prefix `/`
10312 [out] string that points to next token prefix `/`, or string end
10313 @param end [in] end of the entire JSON Pointer string
10314 @param len [out] unescaped token length
10315 @param esc [out] number of escaped characters in this token
10316 @return head of the token, or NULL if syntax error
10317 */
10318static_inline const char *ptr_next_token(const char **ptr, const char *end,
10319 usize *len, usize *esc) {
10320 const char *hdr = *ptr + 1;
10321 const char *cur = hdr;
10322 /* skip unescaped characters */
10323 while (cur < end && *cur != '/' && *cur != '~') cur++;
10324 if (likely(cur == end || *cur != '~')) {
10325 /* no escaped characters, return */
10326 *ptr = cur;
10327 *len = (usize)(cur - hdr);
10328 *esc = 0;
10329 return hdr;
10330 } else {
10331 /* handle escaped characters */
10332 usize esc_num = 0;
10333 while (cur < end && *cur != '/') {
10334 if (*cur++ == '~') {
10335 if (cur == end || (*cur != '0' && *cur != '1')) {
10336 *ptr = cur - 1;
10337 return NULL;
10338 }
10339 esc_num++;
10340 }
10341 }
10342 *ptr = cur;
10343 *len = (usize)(cur - hdr) - esc_num;
10344 *esc = esc_num;
10345 return hdr;
10346 }
10347}
10348
10349/**
10350 Convert token string to index.
10351 @param cur [in] token head
10352 @param len [in] token length
10353 @param idx [out] the index number, or USIZE_MAX if token is '-'
10354 @return true if token is a valid array index
10355 */
10356static_inline bool ptr_token_to_idx(const char *cur, usize len, usize *idx) {
10357 const char *end = cur + len;
10358 usize num = 0, add;
10359 if (unlikely(len == 0 || len > USIZE_SAFE_DIG)) return false;
10360 if (*cur == '0') {
10361 if (unlikely(len > 1)) return false;
10362 *idx = 0;
10363 return true;
10364 }
10365 if (*cur == '-') {
10366 if (unlikely(len > 1)) return false;
10367 *idx = USIZE_MAX;
10368 return true;
10369 }
10370 for (; cur < end && (add = (usize)((u8)*cur - (u8)'0')) <= 9; cur++) {
10371 num = num * 10 + add;
10372 }
10373 if (unlikely(num == 0 || cur < end)) return false;
10374 *idx = num;
10375 return true;
10376}
10377
10378/**
10379 Compare JSON key with token.
10380 @param key a string key (yyjson_val or yyjson_mut_val)
10381 @param token a JSON pointer token
10382 @param len unescaped token length
10383 @param esc number of escaped characters in this token
10384 @return true if `str` is equals to `token`
10385 */
10386static_inline bool ptr_token_eq(void *key,
10387 const char *token, usize len, usize esc) {
10388 yyjson_val *val = (yyjson_val *)key;
10389 if (unsafe_yyjson_get_len(val) != len) return false;
10390 if (likely(!esc)) {
10391 return memcmp(val->uni.str, token, len) == 0;
10392 } else {
10393 const char *str = val->uni.str;
10394 for (; len-- > 0; token++, str++) {
10395 if (*token == '~') {
10396 if (*str != (*++token == '0' ? '~' : '/')) return false;
10397 } else {
10398 if (*str != *token) return false;
10399 }
10400 }
10401 return true;
10402 }
10403}
10404
10405/**
10406 Get a value from array by token.
10407 @param arr an array, should not be NULL or non-array type
10408 @param token a JSON pointer token
10409 @param len unescaped token length
10410 @param esc number of escaped characters in this token
10411 @return value at index, or NULL if token is not index or index is out of range
10412 */
10413static_inline yyjson_val *ptr_arr_get(yyjson_val *arr, const char *token,
10414 usize len, usize esc) {
10415 yyjson_val *val = unsafe_yyjson_get_first(arr);
10416 usize num = unsafe_yyjson_get_len(arr), idx = 0;
10417 if (unlikely(num == 0)) return NULL;
10418 if (unlikely(!ptr_token_to_idx(token, len, &idx))) return NULL;
10419 if (unlikely(idx >= num)) return NULL;
10420 if (unsafe_yyjson_arr_is_flat(arr)) {
10421 return val + idx;
10422 } else {
10423 while (idx-- > 0) val = unsafe_yyjson_get_next(val);
10424 return val;
10425 }
10426}
10427
10428/**
10429 Get a value from object by token.
10430 @param obj [in] an object, should not be NULL or non-object type
10431 @param token [in] a JSON pointer token
10432 @param len [in] unescaped token length
10433 @param esc [in] number of escaped characters in this token
10434 @return value associated with the token, or NULL if no value
10435 */
10436static_inline yyjson_val *ptr_obj_get(yyjson_val *obj, const char *token,
10437 usize len, usize esc) {
10438 yyjson_val *key = unsafe_yyjson_get_first(obj);
10439 usize num = unsafe_yyjson_get_len(obj);
10440 if (unlikely(num == 0)) return NULL;
10441 for (; num > 0; num--, key = unsafe_yyjson_get_next(key + 1)) {
10442 if (ptr_token_eq(key, token, len, esc)) return key + 1;
10443 }
10444 return NULL;
10445}
10446
10447/**
10448 Get a value from array by token.
10449 @param arr [in] an array, should not be NULL or non-array type
10450 @param token [in] a JSON pointer token
10451 @param len [in] unescaped token length
10452 @param esc [in] number of escaped characters in this token
10453 @param pre [out] previous (sibling) value of the returned value
10454 @param last [out] whether index is last
10455 @return value at index, or NULL if token is not index or index is out of range
10456 */
10457static_inline yyjson_mut_val *ptr_mut_arr_get(yyjson_mut_val *arr,
10458 const char *token,
10459 usize len, usize esc,
10460 yyjson_mut_val **pre,
10461 bool *last) {
10462 yyjson_mut_val *val = (yyjson_mut_val *)arr->uni.ptr; /* last (tail) */
10463 usize num = unsafe_yyjson_get_len(arr), idx;
10464 if (last) *last = false;
10465 if (pre) *pre = NULL;
10466 if (unlikely(num == 0)) {
10467 if (last && len == 1 && (*token == '0' || *token == '-')) *last = true;
10468 return NULL;
10469 }
10470 if (unlikely(!ptr_token_to_idx(token, len, &idx))) return NULL;
10471 if (last) *last = (idx == num || idx == USIZE_MAX);
10472 if (unlikely(idx >= num)) return NULL;
10473 while (idx-- > 0) val = val->next;
10474 if (pre) *pre = val;
10475 return val->next;
10476}
10477
10478/**
10479 Get a value from object by token.
10480 @param obj [in] an object, should not be NULL or non-object type
10481 @param token [in] a JSON pointer token
10482 @param len [in] unescaped token length
10483 @param esc [in] number of escaped characters in this token
10484 @param pre [out] previous (sibling) key of the returned value's key
10485 @return value associated with the token, or NULL if no value
10486 */
10487static_inline yyjson_mut_val *ptr_mut_obj_get(yyjson_mut_val *obj,
10488 const char *token,
10489 usize len, usize esc,
10490 yyjson_mut_val **pre) {
10491 yyjson_mut_val *pre_key = (yyjson_mut_val *)obj->uni.ptr, *key;
10492 usize num = unsafe_yyjson_get_len(obj);
10493 if (pre) *pre = NULL;
10494 if (unlikely(num == 0)) return NULL;
10495 for (; num > 0; num--, pre_key = key) {
10496 key = pre_key->next->next;
10497 if (ptr_token_eq(key, token, len, esc)) {
10498 if (pre) *pre = pre_key;
10499 return key->next;
10500 }
10501 }
10502 return NULL;
10503}
10504
10505/**
10506 Create a string value with JSON pointer token.
10507 @param token [in] a JSON pointer token
10508 @param len [in] unescaped token length
10509 @param esc [in] number of escaped characters in this token
10510 @param doc [in] used for memory allocation when creating value
10511 @return new string value, or NULL if memory allocation failed
10512 */
10513static_inline yyjson_mut_val *ptr_new_key(const char *token,
10514 usize len, usize esc,
10515 yyjson_mut_doc *doc) {
10516 const char *src = token;
10517 if (likely(!esc)) {
10518 return yyjson_mut_strncpy(doc, src, len);
10519 } else {
10520 const char *end = src + len + esc;
10521 char *dst = unsafe_yyjson_mut_str_alc(doc, len + esc);
10522 char *str = dst;
10523 if (unlikely(!dst)) return NULL;
10524 for (; src < end; src++, dst++) {
10525 if (*src != '~') *dst = *src;
10526 else *dst = (*++src == '0' ? '~' : '/');
10527 }
10528 *dst = '\0';
10529 return yyjson_mut_strn(doc, str, len);
10530 }
10531}
10532
10533/* macros for yyjson_ptr */
10534#define return_err(_ret, _code, _pos, _msg) do { \
10535 if (err) { \
10536 err->code = YYJSON_PTR_ERR_##_code; \
10537 err->msg = _msg; \
10538 err->pos = (usize)(_pos); \
10539 } \
10540 return _ret; \
10541} while (false)
10542
10543#define return_err_resolve(_ret, _pos) \
10544 return_err(_ret, RESOLVE, _pos, "JSON pointer cannot be resolved")
10545#define return_err_syntax(_ret, _pos) \
10546 return_err(_ret, SYNTAX, _pos, "invalid escaped character")
10547#define return_err_alloc(_ret) \
10548 return_err(_ret, MEMORY_ALLOCATION, 0, "failed to create value")
10549
10550yyjson_val *unsafe_yyjson_ptr_getx(yyjson_val *val,
10551 const char *ptr, size_t ptr_len,
10552 yyjson_ptr_err *err) {
10553
10554 const char *hdr = ptr, *end = ptr + ptr_len, *token;
10555 usize len, esc;
10556 yyjson_type type;
10557
10558 while (true) {
10559 token = ptr_next_token(&ptr, end, &len, &esc);
10560 if (unlikely(!token)) return_err_syntax(NULL, ptr - hdr);
10561 type = unsafe_yyjson_get_type(val);
10562 if (type == YYJSON_TYPE_OBJ) {
10563 val = ptr_obj_get(val, token, len, esc);
10564 } else if (type == YYJSON_TYPE_ARR) {
10565 val = ptr_arr_get(val, token, len, esc);
10566 } else {
10567 val = NULL;
10568 }
10569 if (!val) return_err_resolve(NULL, token - hdr);
10570 if (ptr == end) return val;
10571 }
10572}
10573
10574yyjson_mut_val *unsafe_yyjson_mut_ptr_getx(
10575 yyjson_mut_val *val, const char *ptr, size_t ptr_len,
10576 yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {
10577
10578 const char *hdr = ptr, *end = ptr + ptr_len, *token;
10579 usize len, esc;
10580 yyjson_mut_val *ctn, *pre = NULL;
10581 yyjson_type type;
10582 bool idx_is_last = false;
10583
10584 while (true) {
10585 token = ptr_next_token(&ptr, end, &len, &esc);
10586 if (unlikely(!token)) return_err_syntax(NULL, ptr - hdr);
10587 ctn = val;
10588 type = unsafe_yyjson_get_type(val);
10589 if (type == YYJSON_TYPE_OBJ) {
10590 val = ptr_mut_obj_get(val, token, len, esc, &pre);
10591 } else if (type == YYJSON_TYPE_ARR) {
10592 val = ptr_mut_arr_get(val, token, len, esc, &pre, &idx_is_last);
10593 } else {
10594 val = NULL;
10595 }
10596 if (ctx && (ptr == end)) {
10597 if (type == YYJSON_TYPE_OBJ ||
10598 (type == YYJSON_TYPE_ARR && (val || idx_is_last))) {
10599 ctx->ctn = ctn;
10600 ctx->pre = pre;
10601 }
10602 }
10603 if (!val) return_err_resolve(NULL, token - hdr);
10604 if (ptr == end) return val;
10605 }
10606}
10607
10608bool unsafe_yyjson_mut_ptr_putx(
10609 yyjson_mut_val *val, const char *ptr, size_t ptr_len,
10610 yyjson_mut_val *new_val, yyjson_mut_doc *doc, bool create_parent,
10611 bool insert_new, yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {
10612
10613 const char *hdr = ptr, *end = ptr + ptr_len, *token;
10614 usize token_len, esc, ctn_len;
10615 yyjson_mut_val *ctn, *key, *pre = NULL;
10616 yyjson_mut_val *sep_ctn = NULL, *sep_key = NULL, *sep_val = NULL;
10617 yyjson_type ctn_type;
10618 bool idx_is_last = false;
10619
10620 /* skip exist parent nodes */
10621 while (true) {
10622 token = ptr_next_token(&ptr, end, &token_len, &esc);
10623 if (unlikely(!token)) return_err_syntax(false, ptr - hdr);
10624 ctn = val;
10625 ctn_type = unsafe_yyjson_get_type(ctn);
10626 if (ctn_type == YYJSON_TYPE_OBJ) {
10627 val = ptr_mut_obj_get(ctn, token, token_len, esc, &pre);
10628 } else if (ctn_type == YYJSON_TYPE_ARR) {
10629 val = ptr_mut_arr_get(ctn, token, token_len, esc, &pre,
10630 &idx_is_last);
10631 } else return_err_resolve(false, token - hdr);
10632 if (!val) break;
10633 if (ptr == end) break; /* is last token */
10634 }
10635
10636 /* create parent nodes if not exist */
10637 if (unlikely(ptr != end)) { /* not last token */
10638 if (!create_parent) return_err_resolve(false, token - hdr);
10639
10640 /* add value at last index if container is array */
10641 if (ctn_type == YYJSON_TYPE_ARR) {
10642 if (!idx_is_last || !insert_new) {
10643 return_err_resolve(false, token - hdr);
10644 }
10645 val = yyjson_mut_obj(doc);
10646 if (!val) return_err_alloc(false);
10647
10648 /* delay attaching until all operations are completed */
10649 sep_ctn = ctn;
10650 sep_key = NULL;
10651 sep_val = val;
10652
10653 /* move to next token */
10654 ctn = val;
10655 val = NULL;
10656 ctn_type = YYJSON_TYPE_OBJ;
10657 token = ptr_next_token(&ptr, end, &token_len, &esc);
10658 if (unlikely(!token)) return_err_resolve(false, token - hdr);
10659 }
10660
10661 /* container is object, create parent nodes */
10662 while (ptr != end) { /* not last token */
10663 key = ptr_new_key(token, token_len, esc, doc);
10664 if (!key) return_err_alloc(false);
10665 val = yyjson_mut_obj(doc);
10666 if (!val) return_err_alloc(false);
10667
10668 /* delay attaching until all operations are completed */
10669 if (!sep_ctn) {
10670 sep_ctn = ctn;
10671 sep_key = key;
10672 sep_val = val;
10673 } else {
10674 yyjson_mut_obj_add(ctn, key, val);
10675 }
10676
10677 /* move to next token */
10678 ctn = val;
10679 val = NULL;
10680 token = ptr_next_token(&ptr, end, &token_len, &esc);
10681 if (unlikely(!token)) return_err_syntax(false, ptr - hdr);
10682 }
10683 }
10684
10685 /* JSON pointer is resolved, insert or replace target value */
10686 ctn_len = unsafe_yyjson_get_len(ctn);
10687 if (ctn_type == YYJSON_TYPE_OBJ) {
10688 if (ctx) ctx->ctn = ctn;
10689 if (!val || insert_new) {
10690 /* insert new key-value pair */
10691 key = ptr_new_key(token, token_len, esc, doc);
10692 if (unlikely(!key)) return_err_alloc(false);
10693 if (ctx) ctx->pre = ctn_len ? (yyjson_mut_val *)ctn->uni.ptr : key;
10694 unsafe_yyjson_mut_obj_add(ctn, key, new_val, ctn_len);
10695 } else {
10696 /* replace exist value */
10697 key = pre->next->next;
10698 if (ctx) ctx->pre = pre;
10699 if (ctx) ctx->old = val;
10700 yyjson_mut_obj_put(ctn, key, new_val);
10701 }
10702 } else {
10703 /* array */
10704 if (ctx && (val || idx_is_last)) ctx->ctn = ctn;
10705 if (insert_new) {
10706 /* append new value */
10707 if (val) {
10708 pre->next = new_val;
10709 new_val->next = val;
10710 if (ctx) ctx->pre = pre;
10711 unsafe_yyjson_set_len(ctn, ctn_len + 1);
10712 } else if (idx_is_last) {
10713 if (ctx) ctx->pre = ctn_len ?
10714 (yyjson_mut_val *)ctn->uni.ptr : new_val;
10715 yyjson_mut_arr_append(ctn, new_val);
10716 } else {
10717 return_err_resolve(false, token - hdr);
10718 }
10719 } else {
10720 /* replace exist value */
10721 if (!val) return_err_resolve(false, token - hdr);
10722 if (ctn_len > 1) {
10723 new_val->next = val->next;
10724 pre->next = new_val;
10725 if (ctn->uni.ptr == val) ctn->uni.ptr = new_val;
10726 } else {
10727 new_val->next = new_val;
10728 ctn->uni.ptr = new_val;
10729 pre = new_val;
10730 }
10731 if (ctx) ctx->pre = pre;
10732 if (ctx) ctx->old = val;
10733 }
10734 }
10735
10736 /* all operations are completed, attach the new components to the target */
10737 if (unlikely(sep_ctn)) {
10738 if (sep_key) yyjson_mut_obj_add(sep_ctn, sep_key, sep_val);
10739 else yyjson_mut_arr_append(sep_ctn, sep_val);
10740 }
10741 return true;
10742}
10743
10744yyjson_mut_val *unsafe_yyjson_mut_ptr_replacex(
10745 yyjson_mut_val *val, const char *ptr, size_t len, yyjson_mut_val *new_val,
10746 yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {
10747
10748 yyjson_mut_val *cur_val;
10749 yyjson_ptr_ctx cur_ctx;
10750 memset(&cur_ctx, 0, sizeof(cur_ctx));
10751 if (!ctx) ctx = &cur_ctx;
10752 cur_val = unsafe_yyjson_mut_ptr_getx(val, ptr, len, ctx, err);
10753 if (!cur_val) return NULL;
10754
10755 if (yyjson_mut_is_obj(ctx->ctn)) {
10756 yyjson_mut_val *key = ctx->pre->next->next;
10757 yyjson_mut_obj_put(ctx->ctn, key, new_val);
10758 } else {
10759 yyjson_ptr_ctx_replace(ctx, new_val);
10760 }
10761 ctx->old = cur_val;
10762 return cur_val;
10763}
10764
10765yyjson_mut_val *unsafe_yyjson_mut_ptr_removex(
10766 yyjson_mut_val *val, const char *ptr, size_t len,
10767 yyjson_ptr_ctx *ctx, yyjson_ptr_err *err) {
10768
10769 yyjson_mut_val *cur_val;
10770 yyjson_ptr_ctx cur_ctx;
10771 memset(&cur_ctx, 0, sizeof(cur_ctx));
10772 if (!ctx) ctx = &cur_ctx;
10773 cur_val = unsafe_yyjson_mut_ptr_getx(val, ptr, len, ctx, err);
10774 if (cur_val) {
10775 if (yyjson_mut_is_obj(ctx->ctn)) {
10776 yyjson_mut_val *key = ctx->pre->next->next;
10777 yyjson_mut_obj_put(ctx->ctn, key, NULL);
10778 } else {
10779 yyjson_ptr_ctx_remove(ctx);
10780 }
10781 ctx->pre = NULL;
10782 ctx->old = cur_val;
10783 }
10784 return cur_val;
10785}
10786
10787/* macros for yyjson_ptr */
10788#undef return_err
10789#undef return_err_resolve
10790#undef return_err_syntax
10791#undef return_err_alloc
10792
10793
10794
10795/*==============================================================================
10796 * MARK: - JSON Patch API (RFC 6902) (Public)
10797 *============================================================================*/
10798
10799/* JSON Patch operation */
10800typedef enum patch_op {
10801 PATCH_OP_ADD, /* path, value */
10802 PATCH_OP_REMOVE, /* path */
10803 PATCH_OP_REPLACE, /* path, value */
10804 PATCH_OP_MOVE, /* from, path */
10805 PATCH_OP_COPY, /* from, path */
10806 PATCH_OP_TEST, /* path, value */
10807 PATCH_OP_NONE /* invalid */
10808} patch_op;
10809
10810static patch_op patch_op_get(yyjson_val *op) {
10811 const char *str = op->uni.str;
10812 switch (unsafe_yyjson_get_len(op)) {
10813 case 3:
10814 if (!memcmp(str, "add", 3)) return PATCH_OP_ADD;
10815 return PATCH_OP_NONE;
10816 case 4:
10817 if (!memcmp(str, "move", 4)) return PATCH_OP_MOVE;
10818 if (!memcmp(str, "copy", 4)) return PATCH_OP_COPY;
10819 if (!memcmp(str, "test", 4)) return PATCH_OP_TEST;
10820 return PATCH_OP_NONE;
10821 case 6:
10822 if (!memcmp(str, "remove", 6)) return PATCH_OP_REMOVE;
10823 return PATCH_OP_NONE;
10824 case 7:
10825 if (!memcmp(str, "replace", 7)) return PATCH_OP_REPLACE;
10826 return PATCH_OP_NONE;
10827 default:
10828 return PATCH_OP_NONE;
10829 }
10830}
10831
10832/* macros for yyjson_patch */
10833#define return_err(_code, _msg) do { \
10834 if (err->ptr.code == YYJSON_PTR_ERR_MEMORY_ALLOCATION) { \
10835 err->code = YYJSON_PATCH_ERROR_MEMORY_ALLOCATION; \
10836 err->msg = _msg; \
10837 memset(&err->ptr, 0, sizeof(yyjson_ptr_err)); \
10838 } else { \
10839 err->code = YYJSON_PATCH_ERROR_##_code; \
10840 err->msg = _msg; \
10841 err->idx = iter.idx ? iter.idx - 1 : 0; \
10842 } \
10843 return NULL; \
10844} while (false)
10845
10846#define return_err_copy() \
10847 return_err(MEMORY_ALLOCATION, "failed to copy value")
10848#define return_err_key(_key) \
10849 return_err(MISSING_KEY, "missing key " _key)
10850#define return_err_val(_key) \
10851 return_err(INVALID_MEMBER, "invalid member " _key)
10852
10853#define ptr_get(_ptr) yyjson_mut_ptr_getx( \
10854 root, _ptr->uni.str, _ptr##_len, NULL, &err->ptr)
10855#define ptr_add(_ptr, _val) yyjson_mut_ptr_addx( \
10856 root, _ptr->uni.str, _ptr##_len, _val, doc, false, NULL, &err->ptr)
10857#define ptr_remove(_ptr) yyjson_mut_ptr_removex( \
10858 root, _ptr->uni.str, _ptr##_len, NULL, &err->ptr)
10859#define ptr_replace(_ptr, _val)yyjson_mut_ptr_replacex( \
10860 root, _ptr->uni.str, _ptr##_len, _val, NULL, &err->ptr)
10861
10862yyjson_mut_val *yyjson_patch(yyjson_mut_doc *doc,
10863 yyjson_val *orig,
10864 yyjson_val *patch,
10865 yyjson_patch_err *err) {
10866
10867 yyjson_mut_val *root;
10868 yyjson_val *obj;
10869 yyjson_arr_iter iter;
10870 yyjson_patch_err err_tmp;
10871 if (!err) err = &err_tmp;
10872 memset(err, 0, sizeof(*err));
10873 memset(&iter, 0, sizeof(iter));
10874
10875 if (unlikely(!doc || !orig || !patch)) {
10876 return_err(INVALID_PARAMETER, "input parameter is NULL");
10877 }
10878 if (unlikely(!yyjson_is_arr(patch))) {
10879 return_err(INVALID_PARAMETER, "input patch is not array");
10880 }
10881 root = yyjson_val_mut_copy(doc, orig);
10882 if (unlikely(!root)) return_err_copy();
10883
10884 /* iterate through the patch array */
10885 yyjson_arr_iter_init(patch, &iter);
10886 while ((obj = yyjson_arr_iter_next(&iter))) {
10887 patch_op op_enum;
10888 yyjson_val *op, *path, *from = NULL, *value;
10889 yyjson_mut_val *val = NULL, *test;
10890 usize path_len, from_len = 0;
10891 if (unlikely(!unsafe_yyjson_is_obj(obj))) {
10892 return_err(INVALID_OPERATION, "JSON patch operation is not object");
10893 }
10894
10895 /* get required member: op */
10896 op = yyjson_obj_get(obj, "op");
10897 if (unlikely(!op)) return_err_key("`op`");
10898 if (unlikely(!yyjson_is_str(op))) return_err_val("`op`");
10899 op_enum = patch_op_get(op);
10900
10901 /* get required member: path */
10902 path = yyjson_obj_get(obj, "path");
10903 if (unlikely(!path)) return_err_key("`path`");
10904 if (unlikely(!yyjson_is_str(path))) return_err_val("`path`");
10905 path_len = unsafe_yyjson_get_len(path);
10906
10907 /* get required member: value, from */
10908 switch ((int)op_enum) {
10909 case PATCH_OP_ADD: case PATCH_OP_REPLACE: case PATCH_OP_TEST:
10910 value = yyjson_obj_get(obj, "value");
10911 if (unlikely(!value)) return_err_key("`value`");
10912 val = yyjson_val_mut_copy(doc, value);
10913 if (unlikely(!val)) return_err_copy();
10914 break;
10915 case PATCH_OP_MOVE: case PATCH_OP_COPY:
10916 from = yyjson_obj_get(obj, "from");
10917 if (unlikely(!from)) return_err_key("`from`");
10918 if (unlikely(!yyjson_is_str(from))) return_err_val("`from`");
10919 from_len = unsafe_yyjson_get_len(from);
10920 break;
10921 default:
10922 break;
10923 }
10924
10925 /* perform an operation */
10926 switch ((int)op_enum) {
10927 case PATCH_OP_ADD: /* add(path, val) */
10928 if (unlikely(path_len == 0)) { root = val; break; }
10929 if (unlikely(!ptr_add(path, val))) {
10930 return_err(POINTER, "failed to add `path`");
10931 }
10932 break;
10933 case PATCH_OP_REMOVE: /* remove(path) */
10934 if (unlikely(!ptr_remove(path))) {
10935 return_err(POINTER, "failed to remove `path`");
10936 }
10937 break;
10938 case PATCH_OP_REPLACE: /* replace(path, val) */
10939 if (unlikely(path_len == 0)) { root = val; break; }
10940 if (unlikely(!ptr_replace(path, val))) {
10941 return_err(POINTER, "failed to replace `path`");
10942 }
10943 break;
10944 case PATCH_OP_MOVE: /* val = remove(from), add(path, val) */
10945 if (unlikely(from_len == 0 && path_len == 0)) break;
10946 val = ptr_remove(from);
10947 if (unlikely(!val)) {
10948 return_err(POINTER, "failed to remove `from`");
10949 }
10950 if (unlikely(path_len == 0)) { root = val; break; }
10951 if (unlikely(!ptr_add(path, val))) {
10952 return_err(POINTER, "failed to add `path`");
10953 }
10954 break;
10955 case PATCH_OP_COPY: /* val = get(from).copy, add(path, val) */
10956 val = ptr_get(from);
10957 if (unlikely(!val)) {
10958 return_err(POINTER, "failed to get `from`");
10959 }
10960 if (unlikely(path_len == 0)) { root = val; break; }
10961 val = yyjson_mut_val_mut_copy(doc, val);
10962 if (unlikely(!val)) return_err_copy();
10963 if (unlikely(!ptr_add(path, val))) {
10964 return_err(POINTER, "failed to add `path`");
10965 }
10966 break;
10967 case PATCH_OP_TEST: /* test = get(path), test.eq(val) */
10968 test = ptr_get(path);
10969 if (unlikely(!test)) {
10970 return_err(POINTER, "failed to get `path`");
10971 }
10972 if (unlikely(!yyjson_mut_equals(val, test))) {
10973 return_err(EQUAL, "failed to test equal");
10974 }
10975 break;
10976 default:
10977 return_err(INVALID_MEMBER, "unsupported `op`");
10978 }
10979 }
10980 return root;
10981}
10982
10983yyjson_mut_val *yyjson_mut_patch(yyjson_mut_doc *doc,
10984 yyjson_mut_val *orig,
10985 yyjson_mut_val *patch,
10986 yyjson_patch_err *err) {
10987 yyjson_mut_val *root, *obj;
10988 yyjson_mut_arr_iter iter;
10989 yyjson_patch_err err_tmp;
10990 if (!err) err = &err_tmp;
10991 memset(err, 0, sizeof(*err));
10992 memset(&iter, 0, sizeof(iter));
10993
10994 if (unlikely(!doc || !orig || !patch)) {
10995 return_err(INVALID_PARAMETER, "input parameter is NULL");
10996 }
10997 if (unlikely(!yyjson_mut_is_arr(patch))) {
10998 return_err(INVALID_PARAMETER, "input patch is not array");
10999 }
11000 root = yyjson_mut_val_mut_copy(doc, orig);
11001 if (unlikely(!root)) return_err_copy();
11002
11003 /* iterate through the patch array */
11004 yyjson_mut_arr_iter_init(patch, &iter);
11005 while ((obj = yyjson_mut_arr_iter_next(&iter))) {
11006 patch_op op_enum;
11007 yyjson_mut_val *op, *path, *from = NULL, *value;
11008 yyjson_mut_val *val = NULL, *test;
11009 usize path_len, from_len = 0;
11010 if (!unsafe_yyjson_is_obj(obj)) {
11011 return_err(INVALID_OPERATION, "JSON patch operation is not object");
11012 }
11013
11014 /* get required member: op */
11015 op = yyjson_mut_obj_get(obj, "op");
11016 if (unlikely(!op)) return_err_key("`op`");
11017 if (unlikely(!yyjson_mut_is_str(op))) return_err_val("`op`");
11018 op_enum = patch_op_get((yyjson_val *)(void *)op);
11019
11020 /* get required member: path */
11021 path = yyjson_mut_obj_get(obj, "path");
11022 if (unlikely(!path)) return_err_key("`path`");
11023 if (unlikely(!yyjson_mut_is_str(path))) return_err_val("`path`");
11024 path_len = unsafe_yyjson_get_len(path);
11025
11026 /* get required member: value, from */
11027 switch ((int)op_enum) {
11028 case PATCH_OP_ADD: case PATCH_OP_REPLACE: case PATCH_OP_TEST:
11029 value = yyjson_mut_obj_get(obj, "value");
11030 if (unlikely(!value)) return_err_key("`value`");
11031 val = yyjson_mut_val_mut_copy(doc, value);
11032 if (unlikely(!val)) return_err_copy();
11033 break;
11034 case PATCH_OP_MOVE: case PATCH_OP_COPY:
11035 from = yyjson_mut_obj_get(obj, "from");
11036 if (unlikely(!from)) return_err_key("`from`");
11037 if (unlikely(!yyjson_mut_is_str(from))) {
11038 return_err_val("`from`");
11039 }
11040 from_len = unsafe_yyjson_get_len(from);
11041 break;
11042 default:
11043 break;
11044 }
11045
11046 /* perform an operation */
11047 switch ((int)op_enum) {
11048 case PATCH_OP_ADD: /* add(path, val) */
11049 if (unlikely(path_len == 0)) { root = val; break; }
11050 if (unlikely(!ptr_add(path, val))) {
11051 return_err(POINTER, "failed to add `path`");
11052 }
11053 break;
11054 case PATCH_OP_REMOVE: /* remove(path) */
11055 if (unlikely(!ptr_remove(path))) {
11056 return_err(POINTER, "failed to remove `path`");
11057 }
11058 break;
11059 case PATCH_OP_REPLACE: /* replace(path, val) */
11060 if (unlikely(path_len == 0)) { root = val; break; }
11061 if (unlikely(!ptr_replace(path, val))) {
11062 return_err(POINTER, "failed to replace `path`");
11063 }
11064 break;
11065 case PATCH_OP_MOVE: /* val = remove(from), add(path, val) */
11066 if (unlikely(from_len == 0 && path_len == 0)) break;
11067 val = ptr_remove(from);
11068 if (unlikely(!val)) {
11069 return_err(POINTER, "failed to remove `from`");
11070 }
11071 if (unlikely(path_len == 0)) { root = val; break; }
11072 if (unlikely(!ptr_add(path, val))) {
11073 return_err(POINTER, "failed to add `path`");
11074 }
11075 break;
11076 case PATCH_OP_COPY: /* val = get(from).copy, add(path, val) */
11077 val = ptr_get(from);
11078 if (unlikely(!val)) {
11079 return_err(POINTER, "failed to get `from`");
11080 }
11081 if (unlikely(path_len == 0)) { root = val; break; }
11082 val = yyjson_mut_val_mut_copy(doc, val);
11083 if (unlikely(!val)) return_err_copy();
11084 if (unlikely(!ptr_add(path, val))) {
11085 return_err(POINTER, "failed to add `path`");
11086 }
11087 break;
11088 case PATCH_OP_TEST: /* test = get(path), test.eq(val) */
11089 test = ptr_get(path);
11090 if (unlikely(!test)) {
11091 return_err(POINTER, "failed to get `path`");
11092 }
11093 if (unlikely(!yyjson_mut_equals(val, test))) {
11094 return_err(EQUAL, "failed to test equal");
11095 }
11096 break;
11097 default:
11098 return_err(INVALID_MEMBER, "unsupported `op`");
11099 }
11100 }
11101 return root;
11102}
11103
11104/* macros for yyjson_patch */
11105#undef return_err
11106#undef return_err_copy
11107#undef return_err_key
11108#undef return_err_val
11109#undef ptr_get
11110#undef ptr_add
11111#undef ptr_remove
11112#undef ptr_replace
11113
11114
11115
11116/*==============================================================================
11117 * MARK: - JSON Merge-Patch API (RFC 7386) (Public)
11118 *============================================================================*/
11119
11120yyjson_mut_val *yyjson_merge_patch(yyjson_mut_doc *doc,
11121 yyjson_val *orig,
11122 yyjson_val *patch) {
11123 usize idx, max;
11124 yyjson_val *key, *orig_val, *patch_val, local_orig;
11125 yyjson_mut_val *builder, *mut_key, *mut_val, *merged_val;
11126
11127 if (unlikely(!yyjson_is_obj(patch))) {
11128 return yyjson_val_mut_copy(doc, patch);
11129 }
11130
11131 builder = yyjson_mut_obj(doc);
11132 if (unlikely(!builder)) return NULL;
11133
11134 memset(&local_orig, 0, sizeof(local_orig));
11135 if (!yyjson_is_obj(orig)) {
11136 orig = &local_orig;
11137 orig->tag = builder->tag;
11138 orig->uni = builder->uni;
11139 }
11140
11141 /* If orig is contributing, copy any items not modified by the patch */
11142 if (orig != &local_orig) {
11143 yyjson_obj_foreach(orig, idx, max, key, orig_val) {
11144 patch_val = yyjson_obj_getn(patch,
11145 unsafe_yyjson_get_str(key),
11146 unsafe_yyjson_get_len(key));
11147 if (!patch_val) {
11148 mut_key = yyjson_val_mut_copy(doc, key);
11149 mut_val = yyjson_val_mut_copy(doc, orig_val);
11150 if (!yyjson_mut_obj_add(builder, mut_key, mut_val)) return NULL;
11151 }
11152 }
11153 }
11154
11155 /* Merge items modified by the patch. */
11156 yyjson_obj_foreach(patch, idx, max, key, patch_val) {
11157 /* null indicates the field is removed. */
11158 if (unsafe_yyjson_is_null(patch_val)) {
11159 continue;
11160 }
11161 mut_key = yyjson_val_mut_copy(doc, key);
11162 orig_val = yyjson_obj_getn(orig,
11163 unsafe_yyjson_get_str(key),
11164 unsafe_yyjson_get_len(key));
11165 merged_val = yyjson_merge_patch(doc, orig_val, patch_val);
11166 if (!yyjson_mut_obj_add(builder, mut_key, merged_val)) return NULL;
11167 }
11168
11169 return builder;
11170}
11171
11172yyjson_mut_val *yyjson_mut_merge_patch(yyjson_mut_doc *doc,
11173 yyjson_mut_val *orig,
11174 yyjson_mut_val *patch) {
11175 usize idx, max;
11176 yyjson_mut_val *key, *orig_val, *patch_val, local_orig;
11177 yyjson_mut_val *builder, *mut_key, *mut_val, *merged_val;
11178
11179 if (unlikely(!yyjson_mut_is_obj(patch))) {
11180 return yyjson_mut_val_mut_copy(doc, patch);
11181 }
11182
11183 builder = yyjson_mut_obj(doc);
11184 if (unlikely(!builder)) return NULL;
11185
11186 memset(&local_orig, 0, sizeof(local_orig));
11187 if (!yyjson_mut_is_obj(orig)) {
11188 orig = &local_orig;
11189 orig->tag = builder->tag;
11190 orig->uni = builder->uni;
11191 }
11192
11193 /* If orig is contributing, copy any items not modified by the patch */
11194 if (orig != &local_orig) {
11195 yyjson_mut_obj_foreach(orig, idx, max, key, orig_val) {
11196 patch_val = yyjson_mut_obj_getn(patch,
11197 unsafe_yyjson_get_str(key),
11198 unsafe_yyjson_get_len(key));
11199 if (!patch_val) {
11200 mut_key = yyjson_mut_val_mut_copy(doc, key);
11201 mut_val = yyjson_mut_val_mut_copy(doc, orig_val);
11202 if (!yyjson_mut_obj_add(builder, mut_key, mut_val)) return NULL;
11203 }
11204 }
11205 }
11206
11207 /* Merge items modified by the patch. */
11208 yyjson_mut_obj_foreach(patch, idx, max, key, patch_val) {
11209 /* null indicates the field is removed. */
11210 if (unsafe_yyjson_is_null(patch_val)) {
11211 continue;
11212 }
11213 mut_key = yyjson_mut_val_mut_copy(doc, key);
11214 orig_val = yyjson_mut_obj_getn(orig,
11215 unsafe_yyjson_get_str(key),
11216 unsafe_yyjson_get_len(key));
11217 merged_val = yyjson_mut_merge_patch(doc, orig_val, patch_val);
11218 if (!yyjson_mut_obj_add(builder, mut_key, merged_val)) return NULL;
11219 }
11220
11221 return builder;
11222}
11223
11224#endif /* YYJSON_DISABLE_UTILS */