-
-
Notifications
You must be signed in to change notification settings - Fork 487
Expand file tree
/
Copy pathtinygltf_json.h
More file actions
2112 lines (1899 loc) · 75.1 KB
/
tinygltf_json.h
File metadata and controls
2112 lines (1899 loc) · 75.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* tinygltf_json.h - Fast JSON parser for tinygltf
*
* The MIT License (MIT)
* Copyright (c) 2015 - Present Syoyo Fujita, Aurelien Chatelain and many
* contributors.
*
* A custom JSON parser optimized for glTF processing.
*
* Design goals:
* - C-style implementation core (structs, raw pointers, malloc/free)
* - Minimal C++ wrappers for tinygltf interface compatibility
* - SIMD-accelerated whitespace skipping and string scanning
* - Flat storage arrays for cache-friendly memory layout
*
* SIMD activation (default: SIMD disabled):
* Define TINYGLTF_JSON_USE_SIMD to auto-detect CPU SIMD support, OR
* define one or more of the following explicitly:
* TINYGLTF_JSON_SIMD_SSE2 - Enable SSE2 (x86/x86-64)
* TINYGLTF_JSON_SIMD_AVX2 - Enable AVX2 (x86-64, implies SSE2)
* TINYGLTF_JSON_SIMD_NEON - Enable ARM NEON
*
* Exception handling (default: exceptions disabled):
* By default, parse errors silently return a null value.
* Define TINYGLTF_JSON_USE_EXCEPTIONS before including this header to
* allow tinygltf_json::parse() to throw std::invalid_argument on error
* when its allow_exceptions parameter is true.
*/
#ifndef TINYGLTF_JSON_H_
#define TINYGLTF_JSON_H_
/* C standard headers (keep these first for C compatibility) */
#include <stddef.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
/* C++ headers (minimal) */
#include <string>
#include <cstddef> /* for std::nullptr_t */
#include <new> /* for placement-new */
/* Exception opt-in: define TINYGLTF_JSON_USE_EXCEPTIONS to enable throws.
* TINYGLTF_JSON_NO_EXCEPTIONS is the internal guard derived from the absence
* of TINYGLTF_JSON_USE_EXCEPTIONS; users should not define it directly. */
#ifndef TINYGLTF_JSON_USE_EXCEPTIONS
# define TINYGLTF_JSON_NO_EXCEPTIONS
#endif
#ifndef TINYGLTF_JSON_NO_EXCEPTIONS
# include <stdexcept>
#endif
/* ======================================================================
* SIMD detection
* ====================================================================== */
#ifdef TINYGLTF_JSON_USE_SIMD
# if defined(__AVX2__)
# define TINYGLTF_JSON_SIMD_AVX2
# endif
# if defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || \
(defined(_M_IX86_FP) && _M_IX86_FP >= 2)
# define TINYGLTF_JSON_SIMD_SSE2
# endif
# if defined(__ARM_NEON) || defined(__ARM_NEON__)
# define TINYGLTF_JSON_SIMD_NEON
# endif
#endif
#ifdef TINYGLTF_JSON_SIMD_AVX2
# include <immintrin.h>
#elif defined(TINYGLTF_JSON_SIMD_SSE2)
# include <emmintrin.h>
#endif
#ifdef TINYGLTF_JSON_SIMD_NEON
# include <arm_neon.h>
#endif
/* ======================================================================
* JSON VALUE TYPE CONSTANTS (C-style integer constants)
* ====================================================================== */
#define CJ_NULL 0
#define CJ_BOOL 1
#define CJ_INT 2
#define CJ_REAL 3
#define CJ_STRING 4
#define CJ_ARRAY 5
#define CJ_OBJECT 6
/* ======================================================================
* SIMD WHITESPACE SKIPPING
*
* Whitespace characters in JSON: space(0x20), tab(0x09), CR(0x0D), LF(0x0A)
* ====================================================================== */
static const char *cj_skip_ws_scalar(const char *p, const char *end) {
while (p < end) {
unsigned char c = (unsigned char)*p;
if (c != 0x20u && c != 0x09u && c != 0x0Du && c != 0x0Au) break;
++p;
}
return p;
}
#if defined(TINYGLTF_JSON_SIMD_AVX2)
static const char *cj_skip_ws(const char *p, const char *end) {
while (p + 32 <= end) {
__m256i chunk = _mm256_loadu_si256((const __m256i *)(const void *)p);
__m256i sp = _mm256_cmpeq_epi8(chunk, _mm256_set1_epi8(' '));
__m256i tab = _mm256_cmpeq_epi8(chunk, _mm256_set1_epi8('\t'));
__m256i cr = _mm256_cmpeq_epi8(chunk, _mm256_set1_epi8('\r'));
__m256i lf = _mm256_cmpeq_epi8(chunk, _mm256_set1_epi8('\n'));
__m256i ws = _mm256_or_si256(_mm256_or_si256(sp, tab),
_mm256_or_si256(cr, lf));
unsigned int mask = (unsigned int)_mm256_movemask_epi8(ws);
if (mask != 0xFFFFFFFFu) {
#if defined(__GNUC__) || defined(__clang__)
return p + (int)__builtin_ctz(~mask);
#else
unsigned int inv = ~mask, idx = 0;
while (!(inv & (1u << idx))) ++idx;
return p + idx;
#endif
}
p += 32;
}
return cj_skip_ws_scalar(p, end);
}
#elif defined(TINYGLTF_JSON_SIMD_SSE2)
static const char *cj_skip_ws(const char *p, const char *end) {
while (p + 16 <= end) {
__m128i chunk = _mm_loadu_si128((const __m128i *)(const void *)p);
__m128i sp = _mm_cmpeq_epi8(chunk, _mm_set1_epi8(' '));
__m128i tab = _mm_cmpeq_epi8(chunk, _mm_set1_epi8('\t'));
__m128i cr = _mm_cmpeq_epi8(chunk, _mm_set1_epi8('\r'));
__m128i lf = _mm_cmpeq_epi8(chunk, _mm_set1_epi8('\n'));
__m128i ws = _mm_or_si128(_mm_or_si128(sp, tab),
_mm_or_si128(cr, lf));
unsigned int mask = (unsigned int)_mm_movemask_epi8(ws);
if (mask != 0xFFFFu) {
unsigned int inv = (~mask) & 0xFFFFu;
#if defined(__GNUC__) || defined(__clang__)
return p + (int)__builtin_ctz(inv);
#else
unsigned int idx = 0;
while (!(inv & (1u << idx))) ++idx;
return p + idx;
#endif
}
p += 16;
}
return cj_skip_ws_scalar(p, end);
}
#elif defined(TINYGLTF_JSON_SIMD_NEON)
static const char *cj_skip_ws(const char *p, const char *end) {
while (p + 16 <= end) {
uint8x16_t chunk = vld1q_u8((const uint8_t *)p);
uint8x16_t sp = vceqq_u8(chunk, vdupq_n_u8(' '));
uint8x16_t tab = vceqq_u8(chunk, vdupq_n_u8('\t'));
uint8x16_t cr = vceqq_u8(chunk, vdupq_n_u8('\r'));
uint8x16_t lf = vceqq_u8(chunk, vdupq_n_u8('\n'));
uint8x16_t ws = vorrq_u8(vorrq_u8(sp, tab), vorrq_u8(cr, lf));
uint64x2_t ws64 = vreinterpretq_u64_u8(ws);
uint64_t lo = vgetq_lane_u64(ws64, 0);
uint64_t hi = vgetq_lane_u64(ws64, 1);
if (lo != UINT64_C(0xFFFFFFFFFFFFFFFF) ||
hi != UINT64_C(0xFFFFFFFFFFFFFFFF)) {
uint8_t tmp[16];
vst1q_u8(tmp, ws);
for (int i = 0; i < 16; ++i) {
if (!tmp[i]) return p + i;
}
}
p += 16;
}
return cj_skip_ws_scalar(p, end);
}
#else
static const char *cj_skip_ws(const char *p, const char *end) {
return cj_skip_ws_scalar(p, end);
}
#endif /* SIMD whitespace */
/* ======================================================================
* SIMD STRING SCANNING (find '"', '\', or control char)
* ====================================================================== */
static const char *cj_scan_str_scalar(const char *p, const char *end) {
while (p < end) {
unsigned char c = (unsigned char)*p;
if (c == '"' || c == '\\' || c < 0x20u) break;
++p;
}
return p;
}
#if defined(TINYGLTF_JSON_SIMD_AVX2)
static const char *cj_scan_str(const char *p, const char *end) {
while (p + 32 <= end) {
__m256i chunk = _mm256_loadu_si256((const __m256i *)(const void *)p);
__m256i eq_q = _mm256_cmpeq_epi8(chunk, _mm256_set1_epi8('"'));
__m256i eq_bs = _mm256_cmpeq_epi8(chunk, _mm256_set1_epi8('\\'));
/* Control chars: byte <= 0x1F <=> min(byte, 0x1F) == byte */
__m256i ctrl = _mm256_cmpeq_epi8(
_mm256_min_epu8(chunk, _mm256_set1_epi8(0x1F)),
chunk);
__m256i special = _mm256_or_si256(_mm256_or_si256(eq_q, eq_bs), ctrl);
unsigned int mask = (unsigned int)_mm256_movemask_epi8(special);
if (mask) {
#if defined(__GNUC__) || defined(__clang__)
return p + (int)__builtin_ctz(mask);
#else
unsigned int idx = 0;
while (!(mask & (1u << idx))) ++idx;
return p + idx;
#endif
}
p += 32;
}
return cj_scan_str_scalar(p, end);
}
#elif defined(TINYGLTF_JSON_SIMD_SSE2)
static const char *cj_scan_str(const char *p, const char *end) {
while (p + 16 <= end) {
__m128i chunk = _mm_loadu_si128((const __m128i *)(const void *)p);
__m128i eq_q = _mm_cmpeq_epi8(chunk, _mm_set1_epi8('"'));
__m128i eq_bs = _mm_cmpeq_epi8(chunk, _mm_set1_epi8('\\'));
__m128i ctrl = _mm_cmpeq_epi8(
_mm_min_epu8(chunk, _mm_set1_epi8(0x1F)),
chunk);
__m128i special = _mm_or_si128(_mm_or_si128(eq_q, eq_bs), ctrl);
unsigned int mask = (unsigned int)_mm_movemask_epi8(special);
if (mask) {
#if defined(__GNUC__) || defined(__clang__)
return p + (int)__builtin_ctz(mask);
#else
unsigned int idx = 0;
while (!(mask & (1u << idx))) ++idx;
return p + idx;
#endif
}
p += 16;
}
return cj_scan_str_scalar(p, end);
}
#elif defined(TINYGLTF_JSON_SIMD_NEON)
static const char *cj_scan_str(const char *p, const char *end) {
uint8x16_t vquote = vdupq_n_u8('"');
uint8x16_t vbslash = vdupq_n_u8('\\');
uint8x16_t v20 = vdupq_n_u8(0x20u);
while (p + 16 <= end) {
uint8x16_t chunk = vld1q_u8((const uint8_t *)p);
uint8x16_t eq_q = vceqq_u8(chunk, vquote);
uint8x16_t eq_bs = vceqq_u8(chunk, vbslash);
uint8x16_t ctrl = vcltq_u8(chunk, v20);
uint8x16_t special = vorrq_u8(vorrq_u8(eq_q, eq_bs), ctrl);
uint64x2_t s64 = vreinterpretq_u64_u8(special);
if (vgetq_lane_u64(s64, 0) || vgetq_lane_u64(s64, 1)) {
uint8_t tmp[16];
vst1q_u8(tmp, special);
for (int i = 0; i < 16; ++i) {
if (tmp[i]) return p + i;
}
}
p += 16;
}
return cj_scan_str_scalar(p, end);
}
#else
static const char *cj_scan_str(const char *p, const char *end) {
return cj_scan_str_scalar(p, end);
}
#endif /* SIMD string scan */
/* ======================================================================
* FAST NUMBER PARSING (C-style)
*
* Uses Clinger's fast path for float conversion, avoiding strtod() for the
* vast majority of JSON numbers. The fast path itself is locale-independent
* and typically 4-10x faster than strtod; however, rare fallback paths may
* still invoke the C library's strtod(), which can be locale-dependent.
*
* Optional float32 mode (CJ_FLOAT32_MODE flag in cj_parse_number):
* Parses floating-point values to float (single) precision and stores
* the result as double. Faster because fewer significant digits are
* needed and the fast path covers a wider exponent range.
* Breaks strict JSON/IEEE-754-double conformance.
* ====================================================================== */
/* Safe double-to-int64 cast: returns 0 for NaN; clamps +inf/out-of-range-high
* to INT64_MAX and -inf/out-of-range-low to INT64_MIN. */
static int64_t cj_dbl_to_i64(double d) {
if (d != d) return 0; /* NaN */
if (d >= (double)INT64_MAX) return INT64_MAX;
if (d <= (double)INT64_MIN) return INT64_MIN;
return (int64_t)d;
}
/* Exact powers of 10 that are representable as IEEE 754 double.
* 10^0 through 10^22 are all exactly representable. */
static const double cj_exact_pow10[23] = {
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7,
1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22
};
/* Clinger's fast path: mantissa * 10^exp10 → double.
* Requires mantissa <= 2^53 (exactly representable as double).
* Returns 1 on success, 0 if fallback needed. */
static int cj_fast_dbl_convert(uint64_t mantissa, int exp10, int neg, double *out) {
if (mantissa == 0) {
*out = neg ? -0.0 : 0.0;
return 1;
}
/* Primary: |exp10| <= 22, mantissa fits in double mantissa bits */
if (mantissa <= (1ULL << 53)) {
double d;
if (exp10 >= 0 && exp10 <= 22) {
d = (double)mantissa * cj_exact_pow10[exp10];
*out = neg ? -d : d;
return 1;
}
if (exp10 < 0 && exp10 >= -22) {
d = (double)mantissa / cj_exact_pow10[-exp10];
*out = neg ? -d : d;
return 1;
}
/* Extended: split exponent into two steps, each <= 22.
* Positive: exp10 = 22 + remainder, both halves exact.
* Negative: exp10 = -22 + remainder. */
if (exp10 > 22 && exp10 <= 22 + 22) {
d = (double)mantissa * cj_exact_pow10[exp10 - 22];
d *= cj_exact_pow10[22];
*out = neg ? -d : d;
return 1;
}
if (exp10 < -22 && exp10 >= -(22 + 22)) {
d = (double)mantissa / cj_exact_pow10[-exp10 - 22];
d /= cj_exact_pow10[22];
*out = neg ? -d : d;
return 1;
}
}
return 0;
}
/* Fast path for float32: wider range because float mantissa is only 24 bits. */
static int cj_fast_flt_convert(uint64_t mantissa, int exp10, int neg, float *out) {
if (mantissa == 0) {
*out = neg ? -0.0f : 0.0f;
return 1;
}
/* Direct float path: mantissa fits in 24 bits, pow10 exact in float */
if (mantissa <= (1ULL << 24)) {
if (exp10 >= 0 && exp10 <= 10) {
float f = (float)mantissa * (float)cj_exact_pow10[exp10];
*out = neg ? -f : f;
return 1;
}
if (exp10 < 0 && exp10 >= -10) {
float f = (float)mantissa / (float)cj_exact_pow10[-exp10];
*out = neg ? -f : f;
return 1;
}
}
/* Wider path via double arithmetic (still float-precision result) */
if (mantissa <= (1ULL << 53)) {
double d;
if (exp10 >= 0 && exp10 <= 22) {
d = (double)mantissa * cj_exact_pow10[exp10];
*out = neg ? -(float)d : (float)d;
return 1;
}
if (exp10 < 0 && exp10 >= -22) {
d = (double)mantissa / cj_exact_pow10[-exp10];
*out = neg ? -(float)d : (float)d;
return 1;
}
if (exp10 > 22 && exp10 <= 44) {
d = (double)mantissa * cj_exact_pow10[exp10 - 22];
d *= cj_exact_pow10[22];
*out = neg ? -(float)d : (float)d;
return 1;
}
if (exp10 < -22 && exp10 >= -44) {
d = (double)mantissa / cj_exact_pow10[-exp10 - 22];
d /= cj_exact_pow10[22];
*out = neg ? -(float)d : (float)d;
return 1;
}
}
return 0;
}
/* Parse a JSON number starting at [p, end).
* Sets *is_int, *ival (integer result), *dval (floating-point result).
* Returns pointer past the last character consumed, or NULL on error.
*
* float32_mode: when non-zero, floating-point values are parsed at float
* (single) precision — only 9 significant digits are tracked for the
* fraction part, and the result is stored as (double)(float)value. This
* is faster but not JSON-conformant for high-precision doubles. Integer-
* only tokens (no '.'/'e') are always parsed at full int64 precision
* regardless of this flag.
*
* Uses Clinger's fast path (no strtod) for ~99% of JSON float values.
* Falls back to strtod only for extreme exponents or >19 significant digits. */
static const char *cj_parse_number(const char *p, const char *end,
int *is_int, int64_t *ival, double *dval,
int float32_mode) {
const char *start = p;
int neg = 0;
if (p < end && *p == '-') { neg = 1; ++p; }
if (p >= end) return NULL;
/* Accumulate ALL digits (integer + fraction) into a single mantissa.
* Track the decimal exponent adjustment from the '.' position. */
uint64_t mantissa = 0;
int ndigits = 0; /* total significant digits consumed */
int exp10 = 0; /* decimal exponent adjustment */
int mantissa_overflow = 0; /* set if >19 significant digits */
int has_frac = 0, has_exp = 0;
/* Max significant digits we track:
* Integer part: always 19, so integer-only tokens (no '.'/'e') are always
* accumulated fully and can be typed as int64 regardless of float32_mode.
* Fraction part: 9 in float32_mode (single precision), 19 otherwise. */
int max_sig_int = 19;
int max_sig_frac = float32_mode ? 9 : 19;
/* Integer part */
if (*p == '0') {
++p;
} else if ((unsigned)(*p - '1') <= 8u) {
while (p < end && (unsigned)(*p - '0') <= 9u) {
unsigned d = (unsigned)(*p - '0');
if (ndigits < max_sig_int) {
mantissa = mantissa * 10 + d;
} else {
exp10++; /* excess digit: bump exponent instead */
if (ndigits >= 19) mantissa_overflow = 1;
}
ndigits++;
++p;
}
} else {
return NULL;
}
/* Fraction part */
if (p < end && *p == '.') {
has_frac = 1;
++p;
/* JSON requires at least one digit after '.' */
if (p >= end || (unsigned)(*p - '0') > 9u) return NULL;
while (p < end && (unsigned)(*p - '0') <= 9u) {
unsigned d = (unsigned)(*p - '0');
if (ndigits < max_sig_frac) {
mantissa = mantissa * 10 + d;
exp10--;
}
/* else: ignore trailing fraction digits beyond precision */
ndigits++;
++p;
}
}
/* Exponent part */
if (p < end && (*p == 'e' || *p == 'E')) {
has_exp = 1;
++p;
int exp_neg = 0;
if (p < end && *p == '+') ++p;
else if (p < end && *p == '-') { exp_neg = 1; ++p; }
/* JSON requires at least one digit in exponent */
if (p >= end || (unsigned)(*p - '0') > 9u) return NULL;
int exp_val = 0;
while (p < end && (unsigned)(*p - '0') <= 9u) {
exp_val = exp_val * 10 + (*p - '0');
if (exp_val > 9999) {
/* Prevent overflow; will fall through to strtod */
while (p < end && (unsigned)(*p - '0') <= 9u) ++p;
break;
}
++p;
}
exp10 += exp_neg ? -exp_val : exp_val;
}
/* ---- Integer fast path (no fraction, no exponent, fits int64) ---- */
/* exp10 == 0 ensures all digits were accumulated (none truncated by max_sig) */
if (!has_frac && !has_exp && !mantissa_overflow && exp10 == 0) {
uint64_t mag = mantissa;
int fits;
if (!neg)
fits = (mag <= (uint64_t)INT64_MAX);
else
fits = (mag <= (uint64_t)INT64_MAX + 1u);
if (fits) {
int64_t sv;
if (neg && mag == (uint64_t)INT64_MAX + 1u)
sv = INT64_MIN;
else
sv = neg ? -(int64_t)mag : (int64_t)mag;
*is_int = 1;
*ival = sv;
*dval = (double)sv;
return p;
}
}
/* ---- Float fast path (Clinger's algorithm) ---- */
if (!mantissa_overflow) {
if (float32_mode) {
float f;
if (cj_fast_flt_convert(mantissa, exp10, neg, &f)) {
*is_int = 0;
*dval = (double)f;
*ival = cj_dbl_to_i64((double)f);
return p;
}
} else {
double d;
if (cj_fast_dbl_convert(mantissa, exp10, neg, &d)) {
*is_int = 0;
*dval = d;
*ival = cj_dbl_to_i64(d);
return p;
}
}
}
/* ---- Fallback: strtod (handles extreme exponents, >19 digits) ---- */
char *eptr = NULL;
double d = strtod(start, &eptr);
if (eptr == start) return NULL;
if (float32_mode) d = (double)(float)d;
*is_int = 0;
*dval = d;
*ival = cj_dbl_to_i64(d);
return eptr;
}
/* ======================================================================
* STRING UNESCAPING (C-style)
* ====================================================================== */
static int cj_hex4(const char *p) {
int v = 0;
for (int i = 0; i < 4; ++i) {
char c = p[i];
int d;
if (c >= '0' && c <= '9') d = c - '0';
else if (c >= 'a' && c <= 'f') d = c - 'a' + 10;
else if (c >= 'A' && c <= 'F') d = c - 'A' + 10;
else return -1;
v = (v << 4) | d;
}
return v;
}
static int cj_encode_utf8(unsigned int cp, char *buf) {
if (cp <= 0x7Fu) {
buf[0] = (char)cp;
return 1;
} else if (cp <= 0x7FFu) {
buf[0] = (char)(0xC0u | (cp >> 6));
buf[1] = (char)(0x80u | (cp & 0x3Fu));
return 2;
} else if (cp <= 0xFFFFu) {
buf[0] = (char)(0xE0u | (cp >> 12));
buf[1] = (char)(0x80u | ((cp >> 6) & 0x3Fu));
buf[2] = (char)(0x80u | (cp & 0x3Fu));
return 3;
} else if (cp <= 0x10FFFFu) {
buf[0] = (char)(0xF0u | (cp >> 18));
buf[1] = (char)(0x80u | ((cp >> 12) & 0x3Fu));
buf[2] = (char)(0x80u | ((cp >> 6) & 0x3Fu));
buf[3] = (char)(0x80u | (cp & 0x3Fu));
return 4;
}
return 0;
}
/*
* Parse and unescape a JSON string from [p, end) where p is AFTER the
* opening '"' and end is the INCLUSIVE closing '"'.
* Caller must free() the returned pointer.
* Returns NULL on allocation failure.
*/
static char *cj_unescape_string(const char *p, const char *str_end,
size_t *out_len) {
size_t alloc = (size_t)(str_end - p) + 1;
char *out = (char *)malloc(alloc);
if (!out) return NULL;
char *dst = out;
while (p < str_end) {
/* Track start of literal run so we can copy it before processing
* the special character that ends it. */
const char *run = p;
p = cj_scan_str(p, str_end);
/* Copy non-special (literal) bytes from run to p */
if (p > run) {
size_t n = (size_t)(p - run);
memcpy(dst, run, n);
dst += n;
}
if (p >= str_end) break;
unsigned char c = (unsigned char)*p;
if (c == '"') {
break; /* should not happen - caller passes str_end=position of '"' */
} else if (c == '\\') {
++p;
if (p >= str_end) { free(out); return NULL; }
unsigned char esc = (unsigned char)*p++;
switch (esc) {
case '"': *dst++ = '"'; break;
case '\\': *dst++ = '\\'; break;
case '/': *dst++ = '/'; break;
case 'b': *dst++ = '\b'; break;
case 'f': *dst++ = '\f'; break;
case 'n': *dst++ = '\n'; break;
case 'r': *dst++ = '\r'; break;
case 't': *dst++ = '\t'; break;
case 'u': {
if (p + 4 > str_end) { free(out); return NULL; }
int cp = cj_hex4(p);
if (cp < 0) { free(out); return NULL; }
p += 4;
if (cp >= 0xD800 && cp <= 0xDBFF &&
p + 6 <= str_end && p[0] == '\\' && p[1] == 'u') {
int cp2 = cj_hex4(p + 2);
if (cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
unsigned int full = 0x10000u +
(((unsigned int)cp - 0xD800u) << 10) +
((unsigned int)cp2 - 0xDC00u);
dst += cj_encode_utf8(full, dst);
p += 6;
break;
}
}
dst += cj_encode_utf8((unsigned int)cp, dst);
break;
}
default:
/* Unknown escape sequence is invalid in JSON */
free(out);
return NULL;
}
} else if (c < 0x20u) {
/* Invalid unescaped control character in JSON string: treat as error */
free(out);
return NULL;
} else {
/* Should not be reached since scan_str stops here only for
special chars - but guard just in case */
*dst++ = (char)c;
++p;
}
}
*dst = '\0';
*out_len = (size_t)(dst - out);
return out;
}
/* ======================================================================
* FORWARD DECLARATIONS
* ====================================================================== */
/*
* tinygltf_json is the main JSON value class.
* Its data layout is C-style (all members public, named with trailing _).
*/
class tinygltf_json;
/*
* tinygltf_json_member stores one key-value pair in a JSON object.
* Must be defined AFTER tinygltf_json is complete (contains json by value).
*/
struct tinygltf_json_member;
/* ======================================================================
* tinygltf_json CLASS DECLARATION
*
* All data members are public (C-style struct convention).
* Methods are declared here and implemented after tinygltf_json_member
* is fully defined.
* ====================================================================== */
class tinygltf_json {
public:
/* ------------------------------------------------------------------
* nlohmann-compatible value type enum
* ------------------------------------------------------------------ */
enum class value_t : uint8_t {
null = 0,
boolean = 1,
number_integer = 2,
number_unsigned = 3,
number_float = 4,
string = 5,
array = 6,
object = 7,
/* Aliases from nlohmann/json that tinygltf.h references */
discarded = 8,
binary = 9
};
/* ------------------------------------------------------------------
* C-style data storage (all public for direct access from C functions)
* ------------------------------------------------------------------ */
/* Type tag: one of CJ_NULL, CJ_BOOL, CJ_INT, CJ_REAL, CJ_STRING,
CJ_ARRAY, CJ_OBJECT */
int type_;
/* Primitive values (union for space efficiency) */
union {
int64_t i_; /* CJ_INT */
double d_; /* CJ_REAL */
int b_; /* CJ_BOOL: 0 or 1 */
};
/* String storage */
char *str_; /* CJ_STRING: owned, null-terminated */
size_t str_len_;
/* Array storage: flat array of tinygltf_json objects (owned) */
tinygltf_json *arr_data_;
size_t arr_size_;
size_t arr_cap_;
/* Object storage: flat array of tinygltf_json_member (owned) */
tinygltf_json_member *obj_data_;
size_t obj_size_;
size_t obj_cap_;
/* ------------------------------------------------------------------
* Iterator type (forward-declared here, defined later)
* ------------------------------------------------------------------ */
class iterator;
using const_iterator = iterator;
/* ------------------------------------------------------------------
* Low-level helpers (implementations deferred until member is complete)
* ------------------------------------------------------------------ */
void init_null_();
void destroy_();
void copy_from_(const tinygltf_json &o);
tinygltf_json_member *find_member_(const char *key) const;
int obj_reserve_();
int arr_reserve_();
void make_object_();
void make_array_();
/* ------------------------------------------------------------------
* Constructors and destructor
* ------------------------------------------------------------------ */
tinygltf_json();
tinygltf_json(std::nullptr_t);
tinygltf_json(bool b);
tinygltf_json(int i);
tinygltf_json(int64_t i);
tinygltf_json(uint64_t u);
tinygltf_json(double d);
tinygltf_json(float f);
tinygltf_json(const char *s);
tinygltf_json(const std::string &s);
tinygltf_json(const tinygltf_json &o);
tinygltf_json(tinygltf_json &&o) noexcept;
~tinygltf_json();
tinygltf_json &operator=(const tinygltf_json &o);
tinygltf_json &operator=(tinygltf_json &&o) noexcept;
/* ------------------------------------------------------------------
* Type checks (nlohmann-compatible)
* ------------------------------------------------------------------ */
value_t type() const;
bool is_null() const { return type_ == CJ_NULL; }
bool is_boolean() const { return type_ == CJ_BOOL; }
bool is_number() const { return type_ == CJ_INT || type_ == CJ_REAL; }
bool is_number_integer() const { return type_ == CJ_INT; }
bool is_number_unsigned() const { return type_ == CJ_INT && i_ >= 0; }
bool is_number_float() const { return type_ == CJ_REAL; }
bool is_string() const { return type_ == CJ_STRING; }
bool is_array() const { return type_ == CJ_ARRAY; }
bool is_object() const { return type_ == CJ_OBJECT; }
/* ------------------------------------------------------------------
* Value access (template specializations after class)
* ------------------------------------------------------------------ */
template<typename T> T get() const;
/* ------------------------------------------------------------------
* Container methods
* ------------------------------------------------------------------ */
size_t size() const;
bool empty() const;
/* ------------------------------------------------------------------
* Array operations
* ------------------------------------------------------------------ */
void push_back(tinygltf_json &&v);
void push_back(const tinygltf_json &v);
/* Ensure value is an array (no-op if already array). */
void set_array() { if (type_ != CJ_ARRAY) make_array_(); }
/* ------------------------------------------------------------------
* Object operations
* ------------------------------------------------------------------ */
tinygltf_json &operator[](const char *key);
tinygltf_json &operator[](const std::string &key);
/* ------------------------------------------------------------------
* Iterators
* ------------------------------------------------------------------ */
iterator begin();
iterator end();
iterator begin() const;
iterator end() const;
iterator find(const char *key) const;
iterator find(const char *key);
void erase(iterator &it);
/* ------------------------------------------------------------------
* Static factories
* ------------------------------------------------------------------ */
static tinygltf_json object();
/* ------------------------------------------------------------------
* Serialization / deserialization
* ------------------------------------------------------------------ */
std::string dump(int indent = -1) const;
/* allow_exceptions is honoured only when TINYGLTF_JSON_USE_EXCEPTIONS is
* defined; otherwise it is accepted for API compatibility but has no
* effect — parse errors always return a null value silently. */
static tinygltf_json parse(const char *first, const char *last,
std::nullptr_t = nullptr,
bool allow_exceptions = false);
/* Parse with float32 mode: floating-point values are parsed at single
* precision for speed. Breaks strict JSON double-precision conformance
* but sufficient for glTF (which stores geometry/animation data as
* single-precision floats in buffers anyway). */
static tinygltf_json parse_float32(const char *first, const char *last);
};
/* ======================================================================
* tinygltf_json_member FULL DEFINITION
* (tinygltf_json must be complete before this)
* ====================================================================== */
struct tinygltf_json_member {
char *key; /* owned, null-terminated */
size_t key_len;
tinygltf_json val; /* value stored inline */
tinygltf_json_member() : key(NULL), key_len(0), val() {}
~tinygltf_json_member() { free(key); key = NULL; }
tinygltf_json_member(const tinygltf_json_member &o)
: key(NULL), key_len(o.key_len), val(o.val) {
if (o.key) {
key = (char *)malloc(o.key_len + 1);
if (key) memcpy(key, o.key, o.key_len + 1);
else key_len = 0; /* malloc failure: keep key==NULL, len==0 */
}
}
tinygltf_json_member(tinygltf_json_member &&o) noexcept
: key(o.key), key_len(o.key_len),
val(static_cast<tinygltf_json &&>(o.val)) {
o.key = NULL;
o.key_len = 0;
}
tinygltf_json_member &operator=(const tinygltf_json_member &o) {
if (this != &o) {
free(key);
key = NULL;
key_len = o.key_len;
val = o.val;
if (o.key) {
key = (char *)malloc(o.key_len + 1);
if (key) memcpy(key, o.key, o.key_len + 1);
else key_len = 0; /* malloc failure: keep key==NULL, len==0 */
}
}
return *this;
}
tinygltf_json_member &operator=(tinygltf_json_member &&o) noexcept {
if (this != &o) {
free(key);
key = o.key;
key_len = o.key_len;
val = static_cast<tinygltf_json &&>(o.val);
o.key = NULL;
o.key_len = 0;
}
return *this;
}
};
/* ======================================================================
* tinygltf_json::iterator
* ====================================================================== */
class tinygltf_json::iterator {
public:
static const int MODE_ARRAY = 0;
static const int MODE_OBJECT = 1;
int mode_;
union {
tinygltf_json *arr_ptr_;
tinygltf_json_member *obj_ptr_;
};
iterator() : mode_(MODE_ARRAY), arr_ptr_(NULL) {}
explicit iterator(tinygltf_json *p)
: mode_(MODE_ARRAY), arr_ptr_(p) {}
explicit iterator(tinygltf_json_member *p)
: mode_(MODE_OBJECT), obj_ptr_(p) {}
/* Pre-increment */
iterator &operator++() {
if (mode_ == MODE_ARRAY) ++arr_ptr_;
else ++obj_ptr_;
return *this;
}
/* Post-increment */
iterator operator++(int) {
iterator tmp = *this;
++(*this);
return tmp;
}
tinygltf_json &operator*() {
return (mode_ == MODE_ARRAY) ? *arr_ptr_ : obj_ptr_->val;
}
const tinygltf_json &operator*() const {
return (mode_ == MODE_ARRAY) ? *arr_ptr_ : obj_ptr_->val;
}
tinygltf_json *operator->() {
return (mode_ == MODE_ARRAY) ? arr_ptr_ : &obj_ptr_->val;
}
const tinygltf_json *operator->() const {
return (mode_ == MODE_ARRAY) ? arr_ptr_ : &obj_ptr_->val;
}
std::string key() const {
if (mode_ == MODE_OBJECT && obj_ptr_ && obj_ptr_->key)
return std::string(obj_ptr_->key, obj_ptr_->key_len);
return std::string();
}
tinygltf_json &value() {
return operator*();
}
const tinygltf_json &value() const {
return operator*();
}
bool operator==(const iterator &o) const {
if (mode_ != o.mode_) return false;