forked from ugorji/go
/
json.go
1423 lines (1292 loc) · 34.1 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-2018 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.
//
// Note:
// - we cannot use strconv.Quote and strconv.Unquote because json quotes/unquotes differently.
// We implement it here.
// Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver
// MUST not call one-another.
import (
"bytes"
"encoding/base64"
"math"
"reflect"
"strconv"
"time"
"unicode"
"unicode/utf16"
"unicode/utf8"
)
//--------------------------------
var jsonLiterals = [...]byte{
'"', 't', 'r', 'u', 'e', '"',
'"', 'f', 'a', 'l', 's', 'e', '"',
'"', 'n', 'u', 'l', 'l', '"',
}
const (
jsonLitTrueQ = 0
jsonLitTrue = 1
jsonLitFalseQ = 6
jsonLitFalse = 7
jsonLitNullQ = 13
jsonLitNull = 14
)
const (
jsonU4Chk2 = '0'
jsonU4Chk1 = 'a' - 10
jsonU4Chk0 = 'A' - 10
jsonScratchArrayLen = 64
)
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
jsonSpacesOrTabsLen = 128
jsonAlwaysReturnInternString = false
)
var (
// jsonTabs and jsonSpaces are used as caches for indents
jsonTabs, jsonSpaces [jsonSpacesOrTabsLen]byte
jsonCharHtmlSafeSet bitset128
jsonCharSafeSet bitset128
jsonCharWhitespaceSet bitset256
jsonNumSet bitset256
)
func init() {
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) " \ < > &
var i byte
for i = 32; i < utf8.RuneSelf; i++ {
switch i {
case '"', '\\':
case '<', '>', '&':
jsonCharSafeSet.set(i) // = true
default:
jsonCharSafeSet.set(i)
jsonCharHtmlSafeSet.set(i)
}
}
for i = 0; i <= utf8.RuneSelf; i++ {
switch i {
case ' ', '\t', '\r', '\n':
jsonCharWhitespaceSet.set(i)
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-':
jsonNumSet.set(i)
}
}
}
// ----------------
type jsonEncDriverTypical struct {
w encWriter
// w *encWriterSwitch
b *[jsonScratchArrayLen]byte
tw bool // term white space
c containerState
}
func (e *jsonEncDriverTypical) typical() {}
func (e *jsonEncDriverTypical) reset(ee *jsonEncDriver) {
e.w = ee.ew
// e.w = &ee.e.encWriterSwitch
e.b = &ee.b
e.tw = ee.h.TermWhitespace
e.c = 0
}
func (e *jsonEncDriverTypical) WriteArrayStart(length int) {
e.w.writen1('[')
e.c = containerArrayStart
}
func (e *jsonEncDriverTypical) WriteArrayElem() {
if e.c != containerArrayStart {
e.w.writen1(',')
}
e.c = containerArrayElem
}
func (e *jsonEncDriverTypical) WriteArrayEnd() {
e.w.writen1(']')
e.c = containerArrayEnd
}
func (e *jsonEncDriverTypical) WriteMapStart(length int) {
e.w.writen1('{')
e.c = containerMapStart
}
func (e *jsonEncDriverTypical) WriteMapElemKey() {
if e.c != containerMapStart {
e.w.writen1(',')
}
e.c = containerMapKey
}
func (e *jsonEncDriverTypical) WriteMapElemValue() {
e.w.writen1(':')
e.c = containerMapValue
}
func (e *jsonEncDriverTypical) WriteMapEnd() {
e.w.writen1('}')
e.c = containerMapEnd
}
func (e *jsonEncDriverTypical) EncodeBool(b bool) {
if b {
e.w.writeb(jsonLiterals[jsonLitTrue : jsonLitTrue+4])
} else {
e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5])
}
}
func (e *jsonEncDriverTypical) EncodeFloat64(f float64) {
fmt, prec := jsonFloatStrconvFmtPrec(f)
e.w.writeb(strconv.AppendFloat(e.b[:0], f, fmt, prec, 64))
}
func (e *jsonEncDriverTypical) EncodeInt(v int64) {
e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
}
func (e *jsonEncDriverTypical) EncodeUint(v uint64) {
e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
}
func (e *jsonEncDriverTypical) EncodeFloat32(f float32) {
e.EncodeFloat64(float64(f))
}
func (e *jsonEncDriverTypical) atEndOfEncode() {
if e.tw {
e.w.writen1(' ')
}
}
// ----------------
type jsonEncDriverGeneric struct {
w encWriter // encWriter // *encWriterSwitch
b *[jsonScratchArrayLen]byte
c containerState
// ds string // indent string
di int8 // indent per
d bool // indenting?
dt bool // indent using tabs
dl uint16 // indent level
ks bool // map key as string
is byte // integer as string
tw bool // term white space
_ [7]byte // padding
}
// 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 *jsonEncDriverGeneric) reset(ee *jsonEncDriver) {
e.w = ee.ew
e.b = &ee.b
e.tw = ee.h.TermWhitespace
e.c = 0
e.d, e.dt, e.dl, e.di = false, false, 0, 0
h := ee.h
if h.Indent > 0 {
e.d = true
e.di = int8(h.Indent)
} else if h.Indent < 0 {
e.d = true
e.dt = true
e.di = int8(-h.Indent)
}
e.ks = h.MapKeyAsString
e.is = h.IntegerAsString
}
func (e *jsonEncDriverGeneric) WriteArrayStart(length int) {
if e.d {
e.dl++
}
e.w.writen1('[')
e.c = containerArrayStart
}
func (e *jsonEncDriverGeneric) WriteArrayElem() {
if e.c != containerArrayStart {
e.w.writen1(',')
}
if e.d {
e.writeIndent()
}
e.c = containerArrayElem
}
func (e *jsonEncDriverGeneric) WriteArrayEnd() {
if e.d {
e.dl--
if e.c != containerArrayStart {
e.writeIndent()
}
}
e.w.writen1(']')
e.c = containerArrayEnd
}
func (e *jsonEncDriverGeneric) WriteMapStart(length int) {
if e.d {
e.dl++
}
e.w.writen1('{')
e.c = containerMapStart
}
func (e *jsonEncDriverGeneric) WriteMapElemKey() {
if e.c != containerMapStart {
e.w.writen1(',')
}
if e.d {
e.writeIndent()
}
e.c = containerMapKey
}
func (e *jsonEncDriverGeneric) WriteMapElemValue() {
if e.d {
e.w.writen2(':', ' ')
} else {
e.w.writen1(':')
}
e.c = containerMapValue
}
func (e *jsonEncDriverGeneric) WriteMapEnd() {
if e.d {
e.dl--
if e.c != containerMapStart {
e.writeIndent()
}
}
e.w.writen1('}')
e.c = containerMapEnd
}
func (e *jsonEncDriverGeneric) writeIndent() {
e.w.writen1('\n')
x := int(e.di) * int(e.dl)
if e.dt {
for x > jsonSpacesOrTabsLen {
e.w.writeb(jsonTabs[:])
x -= jsonSpacesOrTabsLen
}
e.w.writeb(jsonTabs[:x])
} else {
for x > jsonSpacesOrTabsLen {
e.w.writeb(jsonSpaces[:])
x -= jsonSpacesOrTabsLen
}
e.w.writeb(jsonSpaces[:x])
}
}
func (e *jsonEncDriverGeneric) EncodeBool(b bool) {
if e.ks && e.c == containerMapKey {
if b {
e.w.writeb(jsonLiterals[jsonLitTrueQ : jsonLitTrueQ+6])
} else {
e.w.writeb(jsonLiterals[jsonLitFalseQ : jsonLitFalseQ+7])
}
} else {
if b {
e.w.writeb(jsonLiterals[jsonLitTrue : jsonLitTrue+4])
} else {
e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5])
}
}
}
func (e *jsonEncDriverGeneric) EncodeFloat64(f float64) {
// instead of using 'g', specify whether to use 'e' or 'f'
fmt, prec := jsonFloatStrconvFmtPrec(f)
var blen int
if e.ks && e.c == containerMapKey {
blen = 2 + len(strconv.AppendFloat(e.b[1:1], f, fmt, prec, 64))
e.b[0] = '"'
e.b[blen-1] = '"'
} else {
blen = len(strconv.AppendFloat(e.b[:0], f, fmt, prec, 64))
}
e.w.writeb(e.b[:blen])
}
func (e *jsonEncDriverGeneric) EncodeInt(v int64) {
x := e.is
if x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) || (e.ks && e.c == containerMapKey) {
blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10))
e.b[0] = '"'
e.b[blen-1] = '"'
e.w.writeb(e.b[:blen])
return
}
e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
}
func (e *jsonEncDriverGeneric) EncodeUint(v uint64) {
x := e.is
if x == 'A' || x == 'L' && v > 1<<53 || (e.ks && e.c == containerMapKey) {
blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10))
e.b[0] = '"'
e.b[blen-1] = '"'
e.w.writeb(e.b[:blen])
return
}
e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
}
func (e *jsonEncDriverGeneric) EncodeFloat32(f float32) {
// e.encodeFloat(float64(f), 32)
// always encode all floats as IEEE 64-bit floating point.
// It also ensures that we can decode in full precision even if into a float32,
// as what is written is always to float64 precision.
e.EncodeFloat64(float64(f))
}
func (e *jsonEncDriverGeneric) atEndOfEncode() {
if e.tw {
if e.d {
e.w.writen1('\n')
} else {
e.w.writen1(' ')
}
}
}
// --------------------
type jsonEncDriver struct {
noBuiltInTypes
e *Encoder
h *JsonHandle
ew encWriter // encWriter // *encWriterSwitch
se extWrapper
// ---- cpu cache line boundary?
bs []byte // scratch
// ---- cpu cache line boundary?
b [jsonScratchArrayLen]byte // scratch (encode time,
}
func (e *jsonEncDriver) EncodeNil() {
// We always encode nil as just null (never in quotes)
// This allows us to easily decode if a nil in the json stream
// ie if initial token is n.
e.ew.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4])
// if e.h.MapKeyAsString && e.c == containerMapKey {
// e.ew.writeb(jsonLiterals[jsonLitNullQ : jsonLitNullQ+6])
// } else {
// e.ew.writeb(jsonLiterals[jsonLitNull : jsonLitNull+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 := t.AppendFormat(e.b[1:1], time.RFC3339Nano)
e.b[len(b)+1] = '"'
e.ew.writeb(e.b[:len(b)+2])
}
// v, err := t.MarshalJSON(); if err != nil { e.e.error(err) } e.ew.writeb(v)
}
func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
if v := ext.ConvertExt(rv); v == nil {
e.EncodeNil()
} else {
en.encode(v)
}
}
func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
// only encodes re.Value (never re.Data)
if re.Value == nil {
e.EncodeNil()
} else {
en.encode(re.Value)
}
}
func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
e.quoteStr(v)
}
func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
// if encoding raw bytes and RawBytesExt is configured, use it to encode
if v == nil {
e.EncodeNil()
return
}
if c == cRAW {
if e.se.InterfaceExt != nil {
e.EncodeExt(v, 0, &e.se, e.e)
return
}
slen := base64.StdEncoding.EncodedLen(len(v))
if cap(e.bs) >= slen+2 {
e.bs = e.bs[:slen+2]
} else {
e.bs = make([]byte, slen+2)
}
e.bs[0] = '"'
base64.StdEncoding.Encode(e.bs[1:], v)
e.bs[slen+1] = '"'
e.ew.writeb(e.bs)
} else {
e.quoteStr(stringView(v))
}
}
func (e *jsonEncDriver) EncodeAsis(v []byte) {
e.ew.writeb(v)
}
func (e *jsonEncDriver) quoteStr(s string) {
// adapted from std pkg encoding/json
const hex = "0123456789abcdef"
w := e.ew
htmlasis := e.h.HTMLCharsAsIs
w.writen1('"')
var start int
for i, slen := 0, len(s); i < slen; {
// encode all bytes < 0x20 (except \r, \n).
// also encode < > & to prevent security holes when served to some browsers.
if b := s[i]; b < utf8.RuneSelf {
// if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
// if (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b) {
if jsonCharHtmlSafeSet.isset(b) || (htmlasis && jsonCharSafeSet.isset(b)) {
i++
continue
}
if start < i {
w.writestr(s[start:i])
}
switch b {
case '\\', '"':
w.writen2('\\', b)
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[b>>4], hex[b&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 {
if start < i {
w.writestr(s[start:i])
}
w.writestr(`\ufffd`)
i += size
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 c == '\u2028' || c == '\u2029' {
if start < i {
w.writestr(s[start:i])
}
w.writestr(`\u202`)
w.writen1(hex[c&0xF])
i += size
start = i
continue
}
i += size
}
if start < len(s) {
w.writestr(s[start:])
}
w.writen1('"')
}
type jsonDecDriver struct {
noBuiltInTypes
d *Decoder
h *JsonHandle
r decReader // *decReaderSwitch // decReader
se extWrapper
// ---- writable fields during execution --- *try* to keep in sep cache line
c containerState
// tok is used to store the token read right after skipWhiteSpace.
tok uint8
fnull bool // found null from appendStringAsBytes
bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
bstr [8]byte // scratch used for string \UXXX parsing
// ---- cpu cache line boundary?
b [jsonScratchArrayLen]byte // scratch 1, used for parsing strings or numbers or time.Time
b2 [jsonScratchArrayLen]byte // scratch 2, used only for readUntil, decNumBytes
_ [3]uint64 // padding
// n jsonNum
}
// func jsonIsWS(b byte) bool {
// // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
// return jsonCharWhitespaceSet.isset(b)
// }
func (d *jsonDecDriver) uncacheRead() {
if d.tok != 0 {
d.r.unreadn1()
d.tok = 0
}
}
func (d *jsonDecDriver) ReadMapStart() int {
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
const xc uint8 = '{'
if d.tok != xc {
d.d.errorf("read map - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
d.c = containerMapStart
return -1
}
func (d *jsonDecDriver) ReadArrayStart() int {
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
const xc uint8 = '['
if d.tok != xc {
d.d.errorf("read array - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
d.c = containerArrayStart
return -1
}
func (d *jsonDecDriver) CheckBreak() bool {
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
return d.tok == '}' || d.tok == ']'
}
// For the ReadXXX methods below, we could just delegate to helper functions
// readContainerState(c containerState, xc uint8, check bool)
// - ReadArrayElem would become:
// readContainerState(containerArrayElem, ',', d.c != containerArrayStart)
//
// However, until mid-stack inlining comes in go1.11 which supports inlining of
// one-liners, we explicitly write them all 5 out to elide the extra func call.
//
// TODO: For Go 1.11, if inlined, consider consolidating these.
func (d *jsonDecDriver) ReadArrayElem() {
const xc uint8 = ','
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
if d.c != containerArrayStart {
if d.tok != xc {
d.d.errorf("read array element - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
}
d.c = containerArrayElem
}
func (d *jsonDecDriver) ReadArrayEnd() {
const xc uint8 = ']'
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
if d.tok != xc {
d.d.errorf("read array end - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
d.c = containerArrayEnd
}
func (d *jsonDecDriver) ReadMapElemKey() {
const xc uint8 = ','
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
if d.c != containerMapStart {
if d.tok != xc {
d.d.errorf("read map key - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
}
d.c = containerMapKey
}
func (d *jsonDecDriver) ReadMapElemValue() {
const xc uint8 = ':'
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
if d.tok != xc {
d.d.errorf("read map value - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
d.c = containerMapValue
}
func (d *jsonDecDriver) ReadMapEnd() {
const xc uint8 = '}'
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
if d.tok != xc {
d.d.errorf("read map end - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
d.c = containerMapEnd
}
func (d *jsonDecDriver) readLit(length, fromIdx uint8) {
bs := d.r.readx(int(length))
d.tok = 0
if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) {
d.d.errorf("expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs)
return
}
}
func (d *jsonDecDriver) TryDecodeAsNil() bool {
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
// we shouldn't try to see if "null" was here, right?
// only the plain string: `null` denotes a nil (ie not quotes)
if d.tok == 'n' {
d.readLit(3, jsonLitNull+1) // (n)ull
return true
}
return false
}
func (d *jsonDecDriver) DecodeBool() (v bool) {
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
fquot := d.c == containerMapKey && d.tok == '"'
if fquot {
d.tok = d.r.readn1()
}
switch d.tok {
case 'f':
d.readLit(4, jsonLitFalse+1) // (f)alse
// v = false
case 't':
d.readLit(3, jsonLitTrue+1) // (t)rue
v = true
default:
d.d.errorf("decode bool: got first char %c", d.tok)
// v = false // "unreachable"
}
if fquot {
d.r.readn1()
}
return
}
func (d *jsonDecDriver) DecodeTime() (t time.Time) {
// read string, and pass the string into json.unmarshal
d.appendStringAsBytes()
if d.fnull {
return
}
t, err := time.Parse(time.RFC3339, stringView(d.bs))
if err != nil {
d.d.errorv(err)
}
return
}
func (d *jsonDecDriver) ContainerType() (vt valueType) {
// check container type by checking the first char
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
// 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 b := d.tok; b == '{' {
return valueTypeMap
} else if b == '[' {
return valueTypeArray
} else if b == 'n' {
return valueTypeNil
} else if b == '"' {
return valueTypeString
}
return valueTypeUnset
}
func (d *jsonDecDriver) decNumBytes() (bs []byte) {
// stores num bytes in d.bs
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
if d.tok == '"' {
bs = d.r.readUntil(d.b2[:0], '"')
bs = bs[:len(bs)-1]
} else {
d.r.unreadn1()
bs = d.r.readTo(d.bs[:0], &jsonNumSet)
}
d.tok = 0
return bs
}
func (d *jsonDecDriver) DecodeUint64() (u uint64) {
bs := d.decNumBytes()
n, neg, badsyntax, overflow := jsonParseInteger(bs)
if overflow {
d.d.errorf("overflow parsing unsigned integer: %s", bs)
} else if neg {
d.d.errorf("minus found parsing unsigned integer: %s", bs)
} else if badsyntax {
// fallback: try to decode as float, and cast
n = d.decUint64ViaFloat(stringView(bs))
}
return n
}
func (d *jsonDecDriver) DecodeInt64() (i int64) {
const cutoff = uint64(1 << uint(64-1))
bs := d.decNumBytes()
n, neg, badsyntax, overflow := jsonParseInteger(bs)
if overflow {
d.d.errorf("overflow parsing integer: %s", bs)
} else if badsyntax {
// d.d.errorf("invalid syntax for integer: %s", bs)
// fallback: try to decode as float, and cast
if neg {
n = d.decUint64ViaFloat(stringView(bs[1:]))
} else {
n = d.decUint64ViaFloat(stringView(bs))
}
}
if neg {
if n > cutoff {
d.d.errorf("overflow parsing integer: %s", bs)
}
i = -(int64(n))
} else {
if n >= cutoff {
d.d.errorf("overflow parsing integer: %s", bs)
}
i = int64(n)
}
return
}
func (d *jsonDecDriver) decUint64ViaFloat(s string) (u uint64) {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
d.d.errorf("invalid syntax for integer: %s", s)
// d.d.errorv(err)
}
fi, ff := math.Modf(f)
if ff > 0 {
d.d.errorf("fractional part found parsing integer: %s", s)
} else if fi > float64(math.MaxUint64) {
d.d.errorf("overflow parsing integer: %s", s)
}
return uint64(fi)
}
func (d *jsonDecDriver) DecodeFloat64() (f float64) {
bs := d.decNumBytes()
f, err := strconv.ParseFloat(stringView(bs), 64)
if err != nil {
d.d.errorv(err)
}
return
}
func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
if ext == nil {
re := rv.(*RawExt)
re.Tag = xtag
d.d.decode(&re.Value)
} else {
var v interface{}
d.d.decode(&v)
ext.UpdateExt(rv, v)
}
return
}
func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
// if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
if d.se.InterfaceExt != nil {
bsOut = bs
d.DecodeExt(&bsOut, 0, &d.se)
return
}
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
// check if an "array" of uint8's (see ContainerType for how to infer if an array)
if d.tok == '[' {
bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
return
}
d.appendStringAsBytes()
// base64 encodes []byte{} as "", and we encode nil []byte as null.
// Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
// appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
// However, it sets a fnull field to true, so we can check if a null was found.
if len(d.bs) == 0 {
if d.fnull {
return nil
}
return []byte{}
}
bs0 := d.bs
slen := base64.StdEncoding.DecodedLen(len(bs0))
if slen <= cap(bs) {
bsOut = bs[:slen]
} else if zerocopy && slen <= cap(d.b2) {
bsOut = d.b2[:slen]
} else {
bsOut = make([]byte, slen)
}
slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
if err != nil {
d.d.errorf("error decoding base64 binary '%s': %v", bs0, err)
return nil
}
if slen != slen2 {
bsOut = bsOut[:slen2]
}
return
}
func (d *jsonDecDriver) DecodeString() (s string) {
d.appendStringAsBytes()
return d.bsToString()
}
func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
d.appendStringAsBytes()
return d.bs
}
func (d *jsonDecDriver) appendStringAsBytes() {
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
d.fnull = false
if d.tok != '"' {
// d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok)
// handle non-string scalar: null, true, false or a number
switch d.tok {
case 'n':
d.readLit(3, jsonLitNull+1) // (n)ull
d.bs = d.bs[:0]
d.fnull = true
case 'f':
d.readLit(4, jsonLitFalse+1) // (f)alse
d.bs = d.bs[:5]
copy(d.bs, "false")
case 't':
d.readLit(3, jsonLitTrue+1) // (t)rue
d.bs = d.bs[:4]
copy(d.bs, "true")
default:
// try to parse a valid number
bs := d.decNumBytes()
if len(bs) <= cap(d.bs) {
d.bs = d.bs[:len(bs)]
} else {
d.bs = make([]byte, len(bs))
}
copy(d.bs, bs)
}
return
}
d.tok = 0
r := d.r
var cs = r.readUntil(d.b2[:0], '"')
var cslen = len(cs)
var c uint8
v := d.bs[:0]
// append on each byte seen can be expensive, so we just
// keep track of where we last read a contiguous set of
// non-special bytes (using cursor variable),
// and when we see a special byte
// e.g. end-of-slice, " or \,
// we will append the full range into the v slice before proceeding
for i, cursor := 0, 0; ; {
if i == cslen {
v = append(v, cs[cursor:]...)
cs = r.readUntil(d.b2[:0], '"')
cslen = len(cs)
i, cursor = 0, 0
}
c = cs[i]
if c == '"' {