-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy pathjson.go
1463 lines (1294 loc) · 36.5 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
// By default, this json support uses base64 encoding for bytes, because you cannot
// store and read any arbitrary string in json (only unicode).
// However, the user can configre how to encode/decode bytes.
//
// This library specifically supports UTF-8 for encoding and decoding only.
//
// Note that the library will happily encode/decode things which are not valid
// json e.g. a map[int64]string. We do it for consistency. With valid json,
// we will encode and decode appropriately.
// Users can specify their map type if necessary to force it.
//
// We cannot use strconv.(Q|Unq)uote because json quotes/unquotes differently.
import (
"encoding/base64"
"math"
"reflect"
"strconv"
"time"
"unicode"
"unicode/utf16"
"unicode/utf8"
)
//--------------------------------
// jsonLits and jsonLitb are defined at the package level,
// so they are guaranteed to be stored efficiently, making
// for better append/string comparison/etc.
//
// (anecdotal evidence from some benchmarking on go 1.20 devel in 20220104)
const jsonLits = `"true"false"null"`
var jsonLitb = []byte(jsonLits)
const (
jsonLitT = 1
jsonLitF = 6
jsonLitN = 12
)
const jsonEncodeUintSmallsString = "" +
"00010203040506070809" +
"10111213141516171819" +
"20212223242526272829" +
"30313233343536373839" +
"40414243444546474849" +
"50515253545556575859" +
"60616263646566676869" +
"70717273747576777879" +
"80818283848586878889" +
"90919293949596979899"
var jsonEncodeUintSmallsStringBytes = []byte(jsonEncodeUintSmallsString)
const (
jsonU4Chk2 = '0'
jsonU4Chk1 = 'a' - 10
jsonU4Chk0 = 'A' - 10
)
const (
// If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
// - If we see first character of null, false or true,
// do not validate subsequent characters.
// - e.g. if we see a n, assume null and skip next 3 characters,
// and do not validate they are ull.
// P.S. Do not expect a significant decoding boost from this.
jsonValidateSymbols = true
// jsonEscapeMultiByteUnicodeSep controls whether some unicode characters
// that are valid json but may bomb in some contexts are escaped during encoeing.
//
// U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
// Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
jsonEscapeMultiByteUnicodeSep = true
// jsonRecognizeBoolNullInQuotedStr is used during decoding into a blank interface{}
// to control whether we detect quoted values of bools and null where a map key is expected,
// and treat as nil, true or false.
jsonNakedBoolNullInQuotedStr = true
// jsonManualInlineDecRdInHotZones controls whether we manually inline some decReader calls.
//
// encode performance is at par with libraries that just iterate over bytes directly,
// because encWr (with inlined bytesEncAppender calls) is inlined.
// Conversely, decode performance suffers because decRd (with inlined bytesDecReader calls)
// isn't inlinable.
//
// To improve decode performamnce from json:
// - readn1 is only called for \u
// - consequently, to optimize json decoding, we specifically need inlining
// for bytes use-case of some other decReader methods:
// - jsonReadAsisChars, skipWhitespace (advance) and jsonReadNum
// - AND THEN readn3, readn4 (for ull, rue and alse).
// - (readn1 is only called when a char is escaped).
// - without inlining, we still pay the cost of a method invocationK, and this dominates time
// - To mitigate, we manually inline in hot zones
// *excluding places where used sparingly (e.g. nextValueBytes, and other atypical cases)*.
// - jsonReadAsisChars *only* called in: appendStringAsBytes
// - advance called: everywhere
// - jsonReadNum: decNumBytes, DecodeNaked
// - From running go test (our anecdotal findings):
// - calling jsonReadAsisChars in appendStringAsBytes: 23431
// - calling jsonReadNum in decNumBytes: 15251
// - calling jsonReadNum in DecodeNaked: 612
// Consequently, we manually inline jsonReadAsisChars (in appendStringAsBytes)
// and jsonReadNum (in decNumbytes)
jsonManualInlineDecRdInHotZones = true
jsonSpacesOrTabsLen = 128
// jsonAlwaysReturnInternString = false
)
var (
// jsonTabs and jsonSpaces are used as caches for indents
jsonTabs, jsonSpaces [jsonSpacesOrTabsLen]byte
jsonCharHtmlSafeSet bitset256
jsonCharSafeSet bitset256
)
func init() {
var i byte
for i = 0; i < jsonSpacesOrTabsLen; i++ {
jsonSpaces[i] = ' '
jsonTabs[i] = '\t'
}
// populate the safe values as true: note: ASCII control characters are (0-31)
// jsonCharSafeSet: all true except (0-31) " \
// jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
for i = 32; i < utf8.RuneSelf; i++ {
switch i {
case '"', '\\':
case '<', '>', '&':
jsonCharSafeSet.set(i) // = true
default:
jsonCharSafeSet.set(i)
jsonCharHtmlSafeSet.set(i)
}
}
}
// ----------------
type jsonEncState struct {
di int8 // indent per: if negative, use tabs
d bool // indenting?
dl uint16 // indent level
}
func (x jsonEncState) captureState() interface{} { return x }
func (x *jsonEncState) restoreState(v interface{}) { *x = v.(jsonEncState) }
type jsonEncDriver struct {
noBuiltInTypes
h *JsonHandle
// se interfaceExtWrapper
// ---- cpu cache line boundary?
jsonEncState
ks bool // map key as string
is byte // integer as string
typical bool
rawext bool // rawext configured on the handle
s *bitset256 // safe set for characters (taking h.HTMLAsIs into consideration)
// buf *[]byte // used mostly for encoding []byte
// scratch buffer for: encode time, numbers, etc
//
// RFC3339Nano uses 35 chars: 2006-01-02T15:04:05.999999999Z07:00
// MaxUint64 uses 20 chars: 18446744073709551615
// floats are encoded using: f/e fmt, and -1 precision, or 1 if no fractions.
// This means we are limited by the number of characters for the
// mantissa (up to 17), exponent (up to 3), signs (up to 3), dot (up to 1), E (up to 1)
// for a total of 24 characters.
// -xxx.yyyyyyyyyyyye-zzz
// Consequently, 35 characters should be sufficient for encoding time, integers or floats.
// We use up all the remaining bytes to make this use full cache lines.
b [48]byte
e Encoder
}
func (e *jsonEncDriver) encoder() *Encoder { return &e.e }
func (e *jsonEncDriver) writeIndent() {
e.e.encWr.writen1('\n')
x := int(e.di) * int(e.dl)
if e.di < 0 {
x = -x
for x > jsonSpacesOrTabsLen {
e.e.encWr.writeb(jsonTabs[:])
x -= jsonSpacesOrTabsLen
}
e.e.encWr.writeb(jsonTabs[:x])
} else {
for x > jsonSpacesOrTabsLen {
e.e.encWr.writeb(jsonSpaces[:])
x -= jsonSpacesOrTabsLen
}
e.e.encWr.writeb(jsonSpaces[:x])
}
}
func (e *jsonEncDriver) WriteArrayElem() {
if e.e.c != containerArrayStart {
e.e.encWr.writen1(',')
}
if e.d {
e.writeIndent()
}
}
func (e *jsonEncDriver) WriteMapElemKey() {
if e.e.c != containerMapStart {
e.e.encWr.writen1(',')
}
if e.d {
e.writeIndent()
}
}
func (e *jsonEncDriver) WriteMapElemValue() {
if e.d {
e.e.encWr.writen2(':', ' ')
} else {
e.e.encWr.writen1(':')
}
}
func (e *jsonEncDriver) EncodeNil() {
// We always encode nil as just null (never in quotes)
// so we can easily decode if a nil in the json stream ie if initial token is n.
e.e.encWr.writestr(jsonLits[jsonLitN : jsonLitN+4])
}
func (e *jsonEncDriver) EncodeTime(t time.Time) {
// Do NOT use MarshalJSON, as it allocates internally.
// instead, we call AppendFormat directly, using our scratch buffer (e.b)
if t.IsZero() {
e.EncodeNil()
} else {
e.b[0] = '"'
b := fmtTime(t, time.RFC3339Nano, e.b[1:1])
e.b[len(b)+1] = '"'
e.e.encWr.writeb(e.b[:len(b)+2])
}
}
func (e *jsonEncDriver) EncodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
if ext == SelfExt {
e.e.encodeValue(baseRV(rv), e.h.fnNoExt(basetype))
} else if v := ext.ConvertExt(rv); v == nil {
e.EncodeNil()
} else {
e.e.encode(v)
}
}
func (e *jsonEncDriver) EncodeRawExt(re *RawExt) {
// only encodes re.Value (never re.Data)
if re.Value == nil {
e.EncodeNil()
} else {
e.e.encode(re.Value)
}
}
var jsonEncBoolStrs = [2][2]string{
{jsonLits[jsonLitF : jsonLitF+5], jsonLits[jsonLitT : jsonLitT+4]},
{jsonLits[jsonLitF-1 : jsonLitF+6], jsonLits[jsonLitT-1 : jsonLitT+5]},
}
func (e *jsonEncDriver) EncodeBool(b bool) {
e.e.encWr.writestr(
jsonEncBoolStrs[bool2int(e.ks && e.e.c == containerMapKey)%2][bool2int(b)%2])
}
// func (e *jsonEncDriver) EncodeBool(b bool) {
// if e.ks && e.e.c == containerMapKey {
// if b {
// e.e.encWr.writestr(jsonLits[jsonLitT-1 : jsonLitT+5])
// } else {
// e.e.encWr.writestr(jsonLits[jsonLitF-1 : jsonLitF+6])
// }
// } else {
// if b {
// e.e.encWr.writestr(jsonLits[jsonLitT : jsonLitT+4])
// } else {
// e.e.encWr.writestr(jsonLits[jsonLitF : jsonLitF+5])
// }
// }
// }
func (e *jsonEncDriver) encodeFloat(f float64, bitsize, fmt byte, prec int8) {
var blen uint
if e.ks && e.e.c == containerMapKey {
blen = 2 + uint(len(strconv.AppendFloat(e.b[1:1], f, fmt, int(prec), int(bitsize))))
// _ = e.b[:blen]
e.b[0] = '"'
e.b[blen-1] = '"'
e.e.encWr.writeb(e.b[:blen])
} else {
e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, int(prec), int(bitsize)))
}
}
func (e *jsonEncDriver) EncodeFloat64(f float64) {
if math.IsNaN(f) || math.IsInf(f, 0) {
e.EncodeNil()
return
}
fmt, prec := jsonFloatStrconvFmtPrec64(f)
e.encodeFloat(f, 64, fmt, prec)
}
func (e *jsonEncDriver) EncodeFloat32(f float32) {
if math.IsNaN(float64(f)) || math.IsInf(float64(f), 0) {
e.EncodeNil()
return
}
fmt, prec := jsonFloatStrconvFmtPrec32(f)
e.encodeFloat(float64(f), 32, fmt, prec)
}
func (e *jsonEncDriver) encodeUint(neg bool, quotes bool, u uint64) {
// copied mostly from std library: strconv
// this should only be called on 64bit OS.
// const smallsString = jsonEncodeUintSmallsString
var ss = jsonEncodeUintSmallsStringBytes
// typically, 19 or 20 bytes sufficient for decimal encoding a uint64
// var a [24]byte
var a = e.b[0:24]
var i = uint(len(a))
if quotes {
i--
setByteAt(a, i, '"')
// a[i] = '"'
}
// u guaranteed to fit into a uint (as we are not 32bit OS)
var is uint
var us = uint(u)
for us >= 100 {
is = us % 100 * 2
us /= 100
i -= 2
setByteAt(a, i+1, byteAt(ss, is+1))
setByteAt(a, i, byteAt(ss, is))
// a[i+1] = smallsString[is+1]
// a[i+0] = smallsString[is+0]
}
// us < 100
is = us * 2
i--
setByteAt(a, i, byteAt(ss, is+1))
// a[i] = smallsString[is+1]
if us >= 10 {
i--
setByteAt(a, i, byteAt(ss, is))
// a[i] = smallsString[is]
}
if neg {
i--
setByteAt(a, i, '-')
// a[i] = '-'
}
if quotes {
i--
setByteAt(a, i, '"')
// a[i] = '"'
}
e.e.encWr.writeb(a[i:])
}
func (e *jsonEncDriver) EncodeInt(v int64) {
quotes := e.is == 'A' || e.is == 'L' && (v > 1<<53 || v < -(1<<53)) ||
(e.ks && e.e.c == containerMapKey)
if cpu32Bit {
if quotes {
blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10))
e.b[0] = '"'
e.b[blen-1] = '"'
e.e.encWr.writeb(e.b[:blen])
} else {
e.e.encWr.writeb(strconv.AppendInt(e.b[:0], v, 10))
}
return
}
if v < 0 {
e.encodeUint(true, quotes, uint64(-v))
} else {
e.encodeUint(false, quotes, uint64(v))
}
}
func (e *jsonEncDriver) EncodeUint(v uint64) {
quotes := e.is == 'A' || e.is == 'L' && v > 1<<53 ||
(e.ks && e.e.c == containerMapKey)
if cpu32Bit {
// use strconv directly, as optimized encodeUint only works on 64-bit alone
if quotes {
blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10))
e.b[0] = '"'
e.b[blen-1] = '"'
e.e.encWr.writeb(e.b[:blen])
} else {
e.e.encWr.writeb(strconv.AppendUint(e.b[:0], v, 10))
}
return
}
e.encodeUint(false, quotes, v)
}
func (e *jsonEncDriver) EncodeString(v string) {
if e.h.StringToRaw {
e.EncodeStringBytesRaw(bytesView(v))
return
}
e.quoteStr(v)
}
func (e *jsonEncDriver) EncodeStringBytesRaw(v []byte) {
// if encoding raw bytes and RawBytesExt is configured, use it to encode
if v == nil {
e.EncodeNil()
return
}
if e.rawext {
iv := e.h.RawBytesExt.ConvertExt(v)
if iv == nil {
e.EncodeNil()
} else {
e.e.encode(iv)
}
return
}
slen := base64.StdEncoding.EncodedLen(len(v)) + 2
// bs := e.e.blist.check(*e.buf, n)[:slen]
// *e.buf = bs
bs := e.e.blist.peek(slen, false)
bs = bs[:slen]
base64.StdEncoding.Encode(bs[1:], v)
bs[len(bs)-1] = '"'
bs[0] = '"'
e.e.encWr.writeb(bs)
}
// indent is done as below:
// - newline and indent are added before each mapKey or arrayElem
// - newline and indent are added before each ending,
// except there was no entry (so we can have {} or [])
func (e *jsonEncDriver) WriteArrayStart(length int) {
if e.d {
e.dl++
}
e.e.encWr.writen1('[')
}
func (e *jsonEncDriver) WriteArrayEnd() {
if e.d {
e.dl--
e.writeIndent()
}
e.e.encWr.writen1(']')
}
func (e *jsonEncDriver) WriteMapStart(length int) {
if e.d {
e.dl++
}
e.e.encWr.writen1('{')
}
func (e *jsonEncDriver) WriteMapEnd() {
if e.d {
e.dl--
if e.e.c != containerMapStart {
e.writeIndent()
}
}
e.e.encWr.writen1('}')
}
func (e *jsonEncDriver) quoteStr(s string) {
// adapted from std pkg encoding/json
const hex = "0123456789abcdef"
w := e.e.w()
w.writen1('"')
var i, start uint
for i < uint(len(s)) {
// encode all bytes < 0x20 (except \r, \n).
// also encode < > & to prevent security holes when served to some browsers.
// We optimize for ascii, by assumining that most characters are in the BMP
// and natively consumed by json without much computation.
// if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
// if (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b) {
if e.s.isset(s[i]) {
i++
continue
}
// b := s[i]
if s[i] < utf8.RuneSelf {
if start < i {
w.writestr(s[start:i])
}
switch s[i] {
case '\\', '"':
w.writen2('\\', s[i])
case '\n':
w.writen2('\\', 'n')
case '\r':
w.writen2('\\', 'r')
case '\b':
w.writen2('\\', 'b')
case '\f':
w.writen2('\\', 'f')
case '\t':
w.writen2('\\', 't')
default:
w.writestr(`\u00`)
w.writen2(hex[s[i]>>4], hex[s[i]&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 { // meaning invalid encoding (so output as-is)
if start < i {
w.writestr(s[start:i])
}
w.writestr(`\uFFFD`)
i++
start = i
continue
}
// U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
// Both technically valid JSON, but bomb on JSONP, so fix here *unconditionally*.
if jsonEscapeMultiByteUnicodeSep && (c == '\u2028' || c == '\u2029') {
if start < i {
w.writestr(s[start:i])
}
w.writestr(`\u202`)
w.writen1(hex[c&0xF])
i += uint(size)
start = i
continue
}
i += uint(size)
}
if start < uint(len(s)) {
w.writestr(s[start:])
}
w.writen1('"')
}
func (e *jsonEncDriver) atEndOfEncode() {
if e.h.TermWhitespace {
var c byte = ' ' // default is that scalar is written, so output space
if e.e.c != 0 {
c = '\n' // for containers (map/list), output a newline
}
e.e.encWr.writen1(c)
}
}
// ----------
type jsonDecState struct {
rawext bool // rawext configured on the handle
tok uint8 // used to store the token read right after skipWhiteSpace
_ bool // found null
_ byte // padding
bstr [4]byte // scratch used for string \UXXX parsing
// scratch buffer used for base64 decoding (DecodeBytes in reuseBuf mode),
// or reading doubleQuoted string (DecodeStringAsBytes, DecodeNaked)
buf *[]byte
}
func (x jsonDecState) captureState() interface{} { return x }
func (x *jsonDecState) restoreState(v interface{}) { *x = v.(jsonDecState) }
type jsonDecDriver struct {
noBuiltInTypes
decDriverNoopNumberHelper
h *JsonHandle
jsonDecState
// se interfaceExtWrapper
// ---- cpu cache line boundary?
d Decoder
}
func (d *jsonDecDriver) descBd() (s string) { panic("descBd unsupported") }
func (d *jsonDecDriver) decoder() *Decoder {
return &d.d
}
func (d *jsonDecDriver) ReadMapStart() int {
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return containerLenNil
}
if d.tok != '{' {
d.d.errorf("read map - expect char '%c' but got char '%c'", '{', d.tok)
}
d.tok = 0
return containerLenUnknown
}
func (d *jsonDecDriver) ReadArrayStart() int {
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return containerLenNil
}
if d.tok != '[' {
d.d.errorf("read array - expect char '%c' but got char '%c'", '[', d.tok)
}
d.tok = 0
return containerLenUnknown
}
// MARKER:
// We attempted making sure CheckBreak can be inlined, by moving the skipWhitespace
// call to an explicit (noinline) function call.
// However, this forces CheckBreak to always incur a function call if there was whitespace,
// with no clear benefit.
func (d *jsonDecDriver) CheckBreak() bool {
d.advance()
return d.tok == '}' || d.tok == ']'
}
func (d *jsonDecDriver) ReadArrayElem() {
const xc uint8 = ','
if d.d.c != containerArrayStart {
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
}
func (d *jsonDecDriver) ReadArrayEnd() {
const xc uint8 = ']'
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
func (d *jsonDecDriver) ReadMapElemKey() {
const xc uint8 = ','
if d.d.c != containerMapStart {
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
}
func (d *jsonDecDriver) ReadMapElemValue() {
const xc uint8 = ':'
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
func (d *jsonDecDriver) ReadMapEnd() {
const xc uint8 = '}'
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
func (d *jsonDecDriver) readDelimError(xc uint8) {
d.d.errorf("read json delimiter - expect char '%c' but got char '%c'", xc, d.tok)
}
// MARKER: checkLit takes the readn(3|4) result as a parameter so they can be inlined.
// We pass the array directly to errorf, as passing slice pushes past inlining threshold,
// and passing slice also might cause allocation of the bs array on the heap.
func (d *jsonDecDriver) checkLit3(got, expect [3]byte) {
d.tok = 0
if jsonValidateSymbols && got != expect {
d.d.errorf("expecting %s: got %s", expect, got)
}
}
func (d *jsonDecDriver) checkLit4(got, expect [4]byte) {
d.tok = 0
if jsonValidateSymbols && got != expect {
d.d.errorf("expecting %s: got %s", expect, got)
}
}
func (d *jsonDecDriver) skipWhitespace() {
d.tok = d.d.decRd.skipWhitespace()
}
func (d *jsonDecDriver) advance() {
if d.tok == 0 {
d.skipWhitespace()
}
}
func (d *jsonDecDriver) nextValueBytes(v []byte) []byte {
v, cursor := d.nextValueBytesR(v)
decNextValueBytesHelper{d: &d.d}.bytesRdV(&v, cursor)
return v
}
func (d *jsonDecDriver) nextValueBytesR(v0 []byte) (v []byte, cursor uint) {
v = v0
var h = decNextValueBytesHelper{d: &d.d}
dr := &d.d.decRd
consumeString := func() {
TOP:
bs := dr.jsonReadAsisChars()
h.appendN(&v, bs...)
if bs[len(bs)-1] != '"' {
// last char is '\', so consume next one and try again
h.append1(&v, dr.readn1())
goto TOP
}
}
d.advance() // ignore leading whitespace
cursor = d.d.rb.c - 1 // cursor starts just before non-whitespace token
switch d.tok {
default:
h.appendN(&v, dr.jsonReadNum()...)
case 'n':
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
h.appendS(&v, jsonLits[jsonLitN:jsonLitN+4])
case 'f':
d.checkLit4([4]byte{'a', 'l', 's', 'e'}, d.d.decRd.readn4())
h.appendS(&v, jsonLits[jsonLitF:jsonLitF+5])
case 't':
d.checkLit3([3]byte{'r', 'u', 'e'}, d.d.decRd.readn3())
h.appendS(&v, jsonLits[jsonLitT:jsonLitT+4])
case '"':
h.append1(&v, '"')
consumeString()
case '{', '[':
var elem struct{}
var stack []struct{}
stack = append(stack, elem)
h.append1(&v, d.tok)
for len(stack) != 0 {
c := dr.readn1()
h.append1(&v, c)
switch c {
case '"':
consumeString()
case '{', '[':
stack = append(stack, elem)
case '}', ']':
stack = stack[:len(stack)-1]
}
}
}
d.tok = 0
return
}
func (d *jsonDecDriver) TryNil() bool {
d.advance()
// we shouldn't try to see if quoted "null" was here, right?
// only the plain string: `null` denotes a nil (ie not quotes)
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return true
}
return false
}
func (d *jsonDecDriver) DecodeBool() (v bool) {
d.advance()
// bool can be in quotes if and only if it's a map key
fquot := d.d.c == containerMapKey && d.tok == '"'
if fquot {
d.tok = d.d.decRd.readn1()
}
switch d.tok {
case 'f':
d.checkLit4([4]byte{'a', 'l', 's', 'e'}, d.d.decRd.readn4())
// v = false
case 't':
d.checkLit3([3]byte{'r', 'u', 'e'}, d.d.decRd.readn3())
v = true
case 'n':
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
// v = false
default:
d.d.errorf("decode bool: got first char %c", d.tok)
// v = false // "unreachable"
}
if fquot {
d.d.decRd.readn1()
}
return
}
func (d *jsonDecDriver) DecodeTime() (t time.Time) {
// read string, and pass the string into json.unmarshal
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return
}
d.ensureReadingString()
bs := d.readUnescapedString()
t, err := time.Parse(time.RFC3339, stringView(bs))
d.d.onerror(err)
return
}
func (d *jsonDecDriver) ContainerType() (vt valueType) {
// check container type by checking the first char
d.advance()
// optimize this, so we don't do 4 checks but do one computation.
// return jsonContainerSet[d.tok]
// ContainerType is mostly called for Map and Array,
// so this conditional is good enough (max 2 checks typically)
if d.tok == '{' {
return valueTypeMap
} else if d.tok == '[' {
return valueTypeArray
} else if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return valueTypeNil
} else if d.tok == '"' {
return valueTypeString
}
return valueTypeUnset
}
func (d *jsonDecDriver) decNumBytes() (bs []byte) {
d.advance()
dr := &d.d.decRd
if d.tok == '"' {
bs = dr.readUntil('"')
} else if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, dr.readn3())
} else {
if jsonManualInlineDecRdInHotZones {
if dr.bytes {
bs = dr.rb.jsonReadNum()
} else {
bs = dr.ri.jsonReadNum()
}
} else {
bs = dr.jsonReadNum()
}
}
d.tok = 0
return
}
func (d *jsonDecDriver) DecodeUint64() (u uint64) {
b := d.decNumBytes()
u, neg, ok := parseInteger_bytes(b)
if neg {
d.d.errorf("negative number cannot be decoded as uint64")
}
if !ok {
d.d.onerror(strconvParseErr(b, "ParseUint"))
}
return
}
func (d *jsonDecDriver) DecodeInt64() (v int64) {
b := d.decNumBytes()
u, neg, ok := parseInteger_bytes(b)
if !ok {
d.d.onerror(strconvParseErr(b, "ParseInt"))
}
if chkOvf.Uint2Int(u, neg) {
d.d.errorf("overflow decoding number from %s", b)
}
if neg {
v = -int64(u)
} else {
v = int64(u)
}
return
}
func (d *jsonDecDriver) DecodeFloat64() (f float64) {
var err error
bs := d.decNumBytes()
if len(bs) == 0 {
return
}
f, err = parseFloat64(bs)
d.d.onerror(err)
return
}
func (d *jsonDecDriver) DecodeFloat32() (f float32) {
var err error
bs := d.decNumBytes()
if len(bs) == 0 {
return
}
f, err = parseFloat32(bs)
d.d.onerror(err)
return
}
func (d *jsonDecDriver) DecodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return
}
if ext == nil {
re := rv.(*RawExt)
re.Tag = xtag
d.d.decode(&re.Value)
} else if ext == SelfExt {
d.d.decodeValue(baseRV(rv), d.h.fnNoExt(basetype))
} else {
d.d.interfaceExtConvertAndDecode(rv, ext)
}
}
func (d *jsonDecDriver) decBytesFromArray(bs []byte) []byte {
if bs != nil {
bs = bs[:0]
}
d.tok = 0
bs = append(bs, uint8(d.DecodeUint64()))
d.tok = d.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
for d.tok != ']' {
if d.tok != ',' {
d.d.errorf("read array element - expect char '%c' but got char '%c'", ',', d.tok)
}
d.tok = 0
bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
d.tok = d.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
}
d.tok = 0
return bs
}