Debian Codegraph @

vendor/github.com/ugorji/go/codec/json.go

raw
1 // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
2 // Use of this source code is governed by a MIT license found in the LICENSE file.
3
4 package codec
5
6 // By default, this json support uses base64 encoding for bytes, because you cannot
7 // store and read any arbitrary string in json (only unicode).
8 // However, the user can configre how to encode/decode bytes.
9 //
10 // This library specifically supports UTF-8 for encoding and decoding only.
11 //
12 // Note that the library will happily encode/decode things which are not valid
13 // json e.g. a map[int64]string. We do it for consistency. With valid json,
14 // we will encode and decode appropriately.
15 // Users can specify their map type if necessary to force it.
16 //
17 // Note:
18 // - we cannot use strconv.Quote and strconv.Unquote because json quotes/unquotes differently.
19 // We implement it here.
20 // - Also, strconv.ParseXXX for floats and integers
21 // - only works on strings resulting in unnecessary allocation and []byte-string conversion.
22 // - it does a lot of redundant checks, because json numbers are simpler that what it supports.
23 // - We parse numbers (floats and integers) directly here.
24 // We only delegate parsing floats if it is a hairy float which could cause a loss of precision.
25 // In that case, we delegate to strconv.ParseFloat.
26 //
27 // Note:
28 // - encode does not beautify. There is no whitespace when encoding.
29 // - rpc calls which take single integer arguments or write single numeric arguments will need care.
30
31 // Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver
32 // MUST not call one-another.
33
34 import (
35 "bytes"
36 "encoding/base64"
37 "reflect"
38 "strconv"
39 "unicode/utf16"
40 "unicode/utf8"
41 )
42
43 //--------------------------------
44
45 var (
46 // jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'}
47
48 // jsonFloat64Pow10 = [...]float64{
49 // 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
50 // 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
51 // 1e20, 1e21, 1e22,
52 // }
53
54 // jsonUint64Pow10 = [...]uint64{
55 // 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
56 // 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
57 // }
58
59 // jsonTabs and jsonSpaces are used as caches for indents
60 jsonTabs, jsonSpaces string
61
62 jsonCharHtmlSafeSet bitset128
63 jsonCharSafeSet bitset128
64 jsonCharWhitespaceSet bitset256
65 jsonNumSet bitset256
66 // jsonIsFloatSet bitset256
67
68 jsonU4Set [256]byte
69 )
70
71 const (
72 // jsonUnreadAfterDecNum controls whether we unread after decoding a number.
73 //
74 // instead of unreading, just update d.tok (iff it's not a whitespace char)
75 // However, doing this means that we may HOLD onto some data which belongs to another stream.
76 // Thus, it is safest to unread the data when done.
77 // keep behind a constant flag for now.
78 jsonUnreadAfterDecNum = true
79
80 // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
81 // - If we see first character of null, false or true,
82 // do not validate subsequent characters.
83 // - e.g. if we see a n, assume null and skip next 3 characters,
84 // and do not validate they are ull.
85 // P.S. Do not expect a significant decoding boost from this.
86 jsonValidateSymbols = true
87
88 jsonSpacesOrTabsLen = 128
89
90 jsonU4SetErrVal = 128
91 )
92
93 func init() {
94 var bs [jsonSpacesOrTabsLen]byte
95 for i := 0; i < jsonSpacesOrTabsLen; i++ {
96 bs[i] = ' '
97 }
98 jsonSpaces = string(bs[:])
99
100 for i := 0; i < jsonSpacesOrTabsLen; i++ {
101 bs[i] = '\t'
102 }
103 jsonTabs = string(bs[:])
104
105 // populate the safe values as true: note: ASCII control characters are (0-31)
106 // jsonCharSafeSet: all true except (0-31) " \
107 // jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
108 var i byte
109 for i = 32; i < utf8.RuneSelf; i++ {
110 switch i {
111 case '"', '\\':
112 case '<', '>', '&':
113 jsonCharSafeSet.set(i) // = true
114 default:
115 jsonCharSafeSet.set(i)
116 jsonCharHtmlSafeSet.set(i)
117 }
118 }
119 for i = 0; i <= utf8.RuneSelf; i++ {
120 switch i {
121 case ' ', '\t', '\r', '\n':
122 jsonCharWhitespaceSet.set(i)
123 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-':
124 jsonNumSet.set(i)
125 }
126 }
127 for j := range jsonU4Set {
128 switch i = byte(j); i {
129 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
130 jsonU4Set[i] = i - '0'
131 case 'a', 'b', 'c', 'd', 'e', 'f':
132 jsonU4Set[i] = i - 'a' + 10
133 case 'A', 'B', 'C', 'D', 'E', 'F':
134 jsonU4Set[i] = i - 'A' + 10
135 default:
136 jsonU4Set[i] = jsonU4SetErrVal
137 }
138 // switch i = byte(j); i {
139 // case 'e', 'E', '.':
140 // jsonIsFloatSet.set(i)
141 // }
142 }
143 // jsonU4Set[255] = jsonU4SetErrVal
144 }
145
146 type jsonEncDriver struct {
147 e *Encoder
148 w encWriter
149 h *JsonHandle
150 b [64]byte // scratch
151 bs []byte // scratch
152 se setExtWrapper
153 ds string // indent string
154 dl uint16 // indent level
155 dt bool // indent using tabs
156 d bool // indent
157 c containerState
158 noBuiltInTypes
159 }
160
161 // indent is done as below:
162 // - newline and indent are added before each mapKey or arrayElem
163 // - newline and indent are added before each ending,
164 // except there was no entry (so we can have {} or [])
165
166 func (e *jsonEncDriver) WriteArrayStart(length int) {
167 if e.d {
168 e.dl++
169 }
170 e.w.writen1('[')
171 e.c = containerArrayStart
172 }
173
174 func (e *jsonEncDriver) WriteArrayElem() {
175 if e.c != containerArrayStart {
176 e.w.writen1(',')
177 }
178 if e.d {
179 e.writeIndent()
180 }
181 e.c = containerArrayElem
182 }
183
184 func (e *jsonEncDriver) WriteArrayEnd() {
185 if e.d {
186 e.dl--
187 if e.c != containerArrayStart {
188 e.writeIndent()
189 }
190 }
191 e.w.writen1(']')
192 e.c = containerArrayEnd
193 }
194
195 func (e *jsonEncDriver) WriteMapStart(length int) {
196 if e.d {
197 e.dl++
198 }
199 e.w.writen1('{')
200 e.c = containerMapStart
201 }
202
203 func (e *jsonEncDriver) WriteMapElemKey() {
204 if e.c != containerMapStart {
205 e.w.writen1(',')
206 }
207 if e.d {
208 e.writeIndent()
209 }
210 e.c = containerMapKey
211 }
212
213 func (e *jsonEncDriver) WriteMapElemValue() {
214 if e.d {
215 e.w.writen2(':', ' ')
216 } else {
217 e.w.writen1(':')
218 }
219 e.c = containerMapValue
220 }
221
222 func (e *jsonEncDriver) WriteMapEnd() {
223 if e.d {
224 e.dl--
225 if e.c != containerMapStart {
226 e.writeIndent()
227 }
228 }
229 e.w.writen1('}')
230 e.c = containerMapEnd
231 }
232
233 // func (e *jsonEncDriver) sendContainerState(c containerState) {
234 // // determine whether to output separators
235 // switch c {
236 // case containerMapKey:
237 // if e.c != containerMapStart {
238 // e.w.writen1(',')
239 // }
240 // if e.d {
241 // e.writeIndent()
242 // }
243 // case containerMapValue:
244 // if e.d {
245 // e.w.writen2(':', ' ')
246 // } else {
247 // e.w.writen1(':')
248 // }
249 // case containerMapEnd:
250 // if e.d {
251 // e.dl--
252 // if e.c != containerMapStart {
253 // e.writeIndent()
254 // }
255 // }
256 // e.w.writen1('}')
257 // case containerArrayElem:
258 // if e.c != containerArrayStart {
259 // e.w.writen1(',')
260 // }
261 // if e.d {
262 // e.writeIndent()
263 // }
264 // case containerArrayEnd:
265 // if e.d {
266 // e.dl--
267 // if e.c != containerArrayStart {
268 // e.writeIndent()
269 // }
270 // }
271 // e.w.writen1(']')
272 // }
273 // e.c = c
274 // }
275
276 func (e *jsonEncDriver) writeIndent() {
277 e.w.writen1('\n')
278 if x := len(e.ds) * int(e.dl); x <= jsonSpacesOrTabsLen {
279 if e.dt {
280 e.w.writestr(jsonTabs[:x])
281 } else {
282 e.w.writestr(jsonSpaces[:x])
283 }
284 } else {
285 for i := uint16(0); i < e.dl; i++ {
286 e.w.writestr(e.ds)
287 }
288 }
289 }
290
291 func (e *jsonEncDriver) EncodeNil() {
292 e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null
293 }
294
295 func (e *jsonEncDriver) EncodeBool(b bool) {
296 if b {
297 e.w.writen4('t', 'r', 'u', 'e') // e.w.writeb(jsonLiterals[0:4]) // true
298 } else {
299 e.w.writen5('f', 'a', 'l', 's', 'e') // e.w.writeb(jsonLiterals[4:9]) // false
300 }
301 }
302
303 func (e *jsonEncDriver) EncodeFloat32(f float32) {
304 e.encodeFloat(float64(f), 32)
305 }
306
307 func (e *jsonEncDriver) EncodeFloat64(f float64) {
308 e.encodeFloat(f, 64)
309 }
310
311 func (e *jsonEncDriver) encodeFloat(f float64, numbits int) {
312 x := strconv.AppendFloat(e.b[:0], f, 'G', -1, numbits)
313 // if bytes.IndexByte(x, 'E') == -1 && bytes.IndexByte(x, '.') == -1 {
314 if !jsonIsFloatBytesB2(x) {
315 x = append(x, '.', '0')
316 }
317 e.w.writeb(x)
318 }
319
320 func (e *jsonEncDriver) EncodeInt(v int64) {
321 if x := e.h.IntegerAsString; x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) {
322 e.w.writen1('"')
323 e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
324 e.w.writen1('"')
325 return
326 }
327 e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
328 }
329
330 func (e *jsonEncDriver) EncodeUint(v uint64) {
331 if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 {
332 e.w.writen1('"')
333 e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
334 e.w.writen1('"')
335 return
336 }
337 e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
338 }
339
340 func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
341 if v := ext.ConvertExt(rv); v == nil {
342 e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
343 } else {
344 en.encode(v)
345 }
346 }
347
348 func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
349 // only encodes re.Value (never re.Data)
350 if re.Value == nil {
351 e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
352 } else {
353 en.encode(re.Value)
354 }
355 }
356
357 func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
358 e.quoteStr(v)
359 }
360
361 func (e *jsonEncDriver) EncodeSymbol(v string) {
362 e.quoteStr(v)
363 }
364
365 func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
366 // if encoding raw bytes and RawBytesExt is configured, use it to encode
367 if c == c_RAW && e.se.i != nil {
368 e.EncodeExt(v, 0, &e.se, e.e)
369 return
370 }
371 if c == c_RAW {
372 slen := base64.StdEncoding.EncodedLen(len(v))
373 if cap(e.bs) >= slen {
374 e.bs = e.bs[:slen]
375 } else {
376 e.bs = make([]byte, slen)
377 }
378 base64.StdEncoding.Encode(e.bs, v)
379 e.w.writen1('"')
380 e.w.writeb(e.bs)
381 e.w.writen1('"')
382 } else {
383 e.quoteStr(stringView(v))
384 }
385 }
386
387 func (e *jsonEncDriver) EncodeAsis(v []byte) {
388 e.w.writeb(v)
389 }
390
391 func (e *jsonEncDriver) quoteStr(s string) {
392 // adapted from std pkg encoding/json
393 const hex = "0123456789abcdef"
394 w := e.w
395 w.writen1('"')
396 var start int
397 for i, slen := 0, len(s); i < slen; {
398 // encode all bytes < 0x20 (except \r, \n).
399 // also encode < > & to prevent security holes when served to some browsers.
400 if b := s[i]; b < utf8.RuneSelf {
401 // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
402 if jsonCharHtmlSafeSet.isset(b) || (e.h.HTMLCharsAsIs && jsonCharSafeSet.isset(b)) {
403 i++
404 continue
405 }
406 if start < i {
407 w.writestr(s[start:i])
408 }
409 switch b {
410 case '\\', '"':
411 w.writen2('\\', b)
412 case '\n':
413 w.writen2('\\', 'n')
414 case '\r':
415 w.writen2('\\', 'r')
416 case '\b':
417 w.writen2('\\', 'b')
418 case '\f':
419 w.writen2('\\', 'f')
420 case '\t':
421 w.writen2('\\', 't')
422 default:
423 w.writestr(`\u00`)
424 w.writen2(hex[b>>4], hex[b&0xF])
425 }
426 i++
427 start = i
428 continue
429 }
430 c, size := utf8.DecodeRuneInString(s[i:])
431 if c == utf8.RuneError && size == 1 {
432 if start < i {
433 w.writestr(s[start:i])
434 }
435 w.writestr(`\ufffd`)
436 i += size
437 start = i
438 continue
439 }
440 // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
441 // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
442 if c == '\u2028' || c == '\u2029' {
443 if start < i {
444 w.writestr(s[start:i])
445 }
446 w.writestr(`\u202`)
447 w.writen1(hex[c&0xF])
448 i += size
449 start = i
450 continue
451 }
452 i += size
453 }
454 if start < len(s) {
455 w.writestr(s[start:])
456 }
457 w.writen1('"')
458 }
459
460 func (e *jsonEncDriver) atEndOfEncode() {
461 if e.h.TermWhitespace {
462 if e.d {
463 e.w.writen1('\n')
464 } else {
465 e.w.writen1(' ')
466 }
467 }
468 }
469
470 type jsonDecDriver struct {
471 noBuiltInTypes
472 d *Decoder
473 h *JsonHandle
474 r decReader
475
476 c containerState
477 // tok is used to store the token read right after skipWhiteSpace.
478 tok uint8
479
480 fnull bool // found null from appendStringAsBytes
481
482 bstr [8]byte // scratch used for string \UXXX parsing
483 b [64]byte // scratch, used for parsing strings or numbers
484 b2 [64]byte // scratch, used only for decodeBytes (after base64)
485 bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
486
487 se setExtWrapper
488
489 // n jsonNum
490 }
491
492 func jsonIsWS(b byte) bool {
493 // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
494 return jsonCharWhitespaceSet.isset(b)
495 }
496
497 func (d *jsonDecDriver) uncacheRead() {
498 if d.tok != 0 {
499 d.r.unreadn1()
500 d.tok = 0
501 }
502 }
503
504 func (d *jsonDecDriver) ReadMapStart() int {
505 if d.tok == 0 {
506 d.tok = d.r.skip(&jsonCharWhitespaceSet)
507 }
508 if d.tok != '{' {
509 d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
510 }
511 d.tok = 0
512 d.c = containerMapStart
513 return -1
514 }
515
516 func (d *jsonDecDriver) ReadArrayStart() int {
517 if d.tok == 0 {
518 d.tok = d.r.skip(&jsonCharWhitespaceSet)
519 }
520 if d.tok != '[' {
521 d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
522 }
523 d.tok = 0
524 d.c = containerArrayStart
525 return -1
526 }
527
528 func (d *jsonDecDriver) CheckBreak() bool {
529 if d.tok == 0 {
530 d.tok = d.r.skip(&jsonCharWhitespaceSet)
531 }
532 return d.tok == '}' || d.tok == ']'
533 }
534
535 func (d *jsonDecDriver) ReadArrayElem() {
536 if d.tok == 0 {
537 d.tok = d.r.skip(&jsonCharWhitespaceSet)
538 }
539 if d.c != containerArrayStart {
540 const xc uint8 = ','
541 if d.tok != xc {
542 d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
543 }
544 d.tok = 0
545 }
546 d.c = containerArrayElem
547 }
548
549 func (d *jsonDecDriver) ReadArrayEnd() {
550 if d.tok == 0 {
551 d.tok = d.r.skip(&jsonCharWhitespaceSet)
552 }
553 const xc uint8 = ']'
554 if d.tok != xc {
555 d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
556 }
557 d.tok = 0
558 d.c = containerArrayEnd
559 }
560
561 func (d *jsonDecDriver) ReadMapElemKey() {
562 if d.tok == 0 {
563 d.tok = d.r.skip(&jsonCharWhitespaceSet)
564 }
565 if d.c != containerMapStart {
566 const xc uint8 = ','
567 if d.tok != xc {
568 d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
569 }
570 d.tok = 0
571 }
572 d.c = containerMapKey
573 }
574
575 func (d *jsonDecDriver) ReadMapElemValue() {
576 if d.tok == 0 {
577 d.tok = d.r.skip(&jsonCharWhitespaceSet)
578 }
579 const xc uint8 = ':'
580 if d.tok != xc {
581 d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
582 }
583 d.tok = 0
584 d.c = containerMapValue
585 }
586
587 func (d *jsonDecDriver) ReadMapEnd() {
588 if d.tok == 0 {
589 d.tok = d.r.skip(&jsonCharWhitespaceSet)
590 }
591 const xc uint8 = '}'
592 if d.tok != xc {
593 d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
594 }
595 d.tok = 0
596 d.c = containerMapEnd
597 }
598
599 // func (d *jsonDecDriver) readContainerState(c containerState, xc uint8, check bool) {
600 // if d.tok == 0 {
601 // d.tok = d.r.skip(&jsonCharWhitespaceSet)
602 // }
603 // if check {
604 // if d.tok != xc {
605 // d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
606 // }
607 // d.tok = 0
608 // }
609 // d.c = c
610 // }
611
612 // func (d *jsonDecDriver) sendContainerState(c containerState) {
613 // if d.tok == 0 {
614 // d.tok = d.r.skip(&jsonCharWhitespaceSet)
615 // }
616 // var xc uint8 // char expected
617 // switch c {
618 // case containerMapKey:
619 // if d.c != containerMapStart {
620 // xc = ','
621 // }
622 // case containerMapValue:
623 // xc = ':'
624 // case containerMapEnd:
625 // xc = '}'
626 // case containerArrayElem:
627 // if d.c != containerArrayStart {
628 // xc = ','
629 // }
630 // case containerArrayEnd:
631 // xc = ']'
632 // }
633 // if xc != 0 {
634 // if d.tok != xc {
635 // d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
636 // }
637 // d.tok = 0
638 // }
639 // d.c = c
640 // }
641
642 // func (d *jsonDecDriver) readLiteralIdx(fromIdx, toIdx uint8) {
643 // bs := d.r.readx(int(toIdx - fromIdx))
644 // d.tok = 0
645 // if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
646 // d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
647 // return
648 // }
649 // }
650
651 func (d *jsonDecDriver) readSymbol3(v1, v2, v3 uint8) {
652 b1, b2, b3 := d.r.readn3()
653 d.tok = 0
654 if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3) {
655 d.d.errorf("json: expecting %c, %c, %c: got %c, %c, %c", b1, b2, b3, v1, v2, v3)
656 return
657 }
658 }
659
660 func (d *jsonDecDriver) readSymbol4(v1, v2, v3, v4 uint8) {
661 b1, b2, b3, b4 := d.r.readn4()
662 d.tok = 0
663 if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3 || b4 != v4) {
664 d.d.errorf("json: expecting %c, %c, %c, %c: got %c, %c, %c, %c", b1, b2, b3, b4, v1, v2, v3, v4)
665 return
666 }
667 }
668
669 func (d *jsonDecDriver) TryDecodeAsNil() bool {
670 if d.tok == 0 {
671 d.tok = d.r.skip(&jsonCharWhitespaceSet)
672 }
673 if d.tok == 'n' {
674 d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
675 return true
676 }
677 return false
678 }
679
680 func (d *jsonDecDriver) DecodeBool() bool {
681 if d.tok == 0 {
682 d.tok = d.r.skip(&jsonCharWhitespaceSet)
683 }
684 if d.tok == 'f' {
685 d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
686 return false
687 }
688 if d.tok == 't' {
689 d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
690 return true
691 }
692 d.d.errorf("json: decode bool: got first char %c", d.tok)
693 return false // "unreachable"
694 }
695
696 func (d *jsonDecDriver) ContainerType() (vt valueType) {
697 // check container type by checking the first char
698 if d.tok == 0 {
699 d.tok = d.r.skip(&jsonCharWhitespaceSet)
700 }
701 if b := d.tok; b == '{' {
702 return valueTypeMap
703 } else if b == '[' {
704 return valueTypeArray
705 } else if b == 'n' {
706 return valueTypeNil
707 } else if b == '"' {
708 return valueTypeString
709 }
710 return valueTypeUnset
711 // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
712 // return false // "unreachable"
713 }
714
715 func (d *jsonDecDriver) decNumBytes() (bs []byte) {
716 // stores num bytes in d.bs
717 if d.tok == 0 {
718 d.tok = d.r.skip(&jsonCharWhitespaceSet)
719 }
720 if d.tok == '"' {
721 bs = d.r.readUntil(d.b2[:0], '"')
722 bs = bs[:len(bs)-1]
723 } else {
724 d.r.unreadn1()
725 bs = d.r.readTo(d.bs[:0], &jsonNumSet)
726 }
727 d.tok = 0
728 return bs
729 }
730
731 func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
732 bs := d.decNumBytes()
733 u, err := strconv.ParseUint(stringView(bs), 10, int(bitsize))
734 if err != nil {
735 d.d.errorf("json: decode uint from %s: %v", bs, err)
736 return
737 }
738 return
739 }
740
741 func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
742 bs := d.decNumBytes()
743 i, err := strconv.ParseInt(stringView(bs), 10, int(bitsize))
744 if err != nil {
745 d.d.errorf("json: decode int from %s: %v", bs, err)
746 return
747 }
748 return
749 }
750
751 func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
752 bs := d.decNumBytes()
753 bitsize := 64
754 if chkOverflow32 {
755 bitsize = 32
756 }
757 f, err := strconv.ParseFloat(stringView(bs), bitsize)
758 if err != nil {
759 d.d.errorf("json: decode float from %s: %v", bs, err)
760 return
761 }
762 return
763 }
764
765 func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
766 if ext == nil {
767 re := rv.(*RawExt)
768 re.Tag = xtag
769 d.d.decode(&re.Value)
770 } else {
771 var v interface{}
772 d.d.decode(&v)
773 ext.UpdateExt(rv, v)
774 }
775 return
776 }
777
778 func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
779 // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
780 if d.se.i != nil {
781 bsOut = bs
782 d.DecodeExt(&bsOut, 0, &d.se)
783 return
784 }
785 d.appendStringAsBytes()
786 // base64 encodes []byte{} as "", and we encode nil []byte as null.
787 // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
788 // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
789 // However, it sets a fnull field to true, so we can check if a null was found.
790 if len(d.bs) == 0 {
791 if d.fnull {
792 return nil
793 }
794 return []byte{}
795 }
796 bs0 := d.bs
797 slen := base64.StdEncoding.DecodedLen(len(bs0))
798 if slen <= cap(bs) {
799 bsOut = bs[:slen]
800 } else if zerocopy && slen <= cap(d.b2) {
801 bsOut = d.b2[:slen]
802 } else {
803 bsOut = make([]byte, slen)
804 }
805 slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
806 if err != nil {
807 d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
808 return nil
809 }
810 if slen != slen2 {
811 bsOut = bsOut[:slen2]
812 }
813 return
814 }
815
816 const jsonAlwaysReturnInternString = false
817
818 func (d *jsonDecDriver) DecodeString() (s string) {
819 d.appendStringAsBytes()
820 // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
821 if jsonAlwaysReturnInternString || d.c == containerMapKey {
822 return d.d.string(d.bs)
823 }
824 return string(d.bs)
825 }
826
827 func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
828 d.appendStringAsBytes()
829 return d.bs
830 }
831
832 func (d *jsonDecDriver) appendStringAsBytes() {
833 if d.tok == 0 {
834 d.tok = d.r.skip(&jsonCharWhitespaceSet)
835 }
836
837 d.fnull = false
838 if d.tok != '"' {
839 // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
840 // handle non-string scalar: null, true, false or a number
841 switch d.tok {
842 case 'n':
843 d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
844 d.bs = d.bs[:0]
845 d.fnull = true
846 case 'f':
847 d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
848 d.bs = d.bs[:5]
849 copy(d.bs, "false")
850 case 't':
851 d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
852 d.bs = d.bs[:4]
853 copy(d.bs, "true")
854 default:
855 // try to parse a valid number
856 bs := d.decNumBytes()
857 d.bs = d.bs[:len(bs)]
858 copy(d.bs, bs)
859 }
860 return
861 }
862
863 d.tok = 0
864 r := d.r
865 var cs = r.readUntil(d.b2[:0], '"')
866 var cslen = len(cs)
867 var c uint8
868 v := d.bs[:0]
869 // append on each byte seen can be expensive, so we just
870 // keep track of where we last read a contiguous set of
871 // non-special bytes (using cursor variable),
872 // and when we see a special byte
873 // e.g. end-of-slice, " or \,
874 // we will append the full range into the v slice before proceeding
875 for i, cursor := 0, 0; ; {
876 if i == cslen {
877 v = append(v, cs[cursor:]...)
878 cs = r.readUntil(d.b2[:0], '"')
879 cslen = len(cs)
880 i, cursor = 0, 0
881 }
882 c = cs[i]
883 if c == '"' {
884 v = append(v, cs[cursor:i]...)
885 break
886 }
887 if c != '\\' {
888 i++
889 continue
890 }
891 v = append(v, cs[cursor:i]...)
892 i++
893 c = cs[i]
894 switch c {
895 case '"', '\\', '/', '\'':
896 v = append(v, c)
897 case 'b':
898 v = append(v, '\b')
899 case 'f':
900 v = append(v, '\f')
901 case 'n':
902 v = append(v, '\n')
903 case 'r':
904 v = append(v, '\r')
905 case 't':
906 v = append(v, '\t')
907 case 'u':
908 var r rune
909 var rr uint32
910 c = cs[i+4] // may help reduce bounds-checking
911 for j := 1; j < 5; j++ {
912 c = jsonU4Set[cs[i+j]]
913 if c == jsonU4SetErrVal {
914 d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
915 }
916 rr = rr*16 + uint32(c)
917 }
918 r = rune(rr)
919 i += 4
920 if utf16.IsSurrogate(r) {
921 if !(cs[i+2] == 'u' && cs[i+i] == '\\') {
922 d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
923 return
924 }
925 i += 2
926 c = cs[i+4] // may help reduce bounds-checking
927 var rr1 uint32
928 for j := 1; j < 5; j++ {
929 c = jsonU4Set[cs[i+j]]
930 if c == jsonU4SetErrVal {
931 d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
932 }
933 rr1 = rr1*16 + uint32(c)
934 }
935 r = utf16.DecodeRune(r, rune(rr1))
936 i += 4
937 }
938 w2 := utf8.EncodeRune(d.bstr[:], r)
939 v = append(v, d.bstr[:w2]...)
940 default:
941 d.d.errorf("json: unsupported escaped value: %c", c)
942 }
943 i++
944 cursor = i
945 }
946 d.bs = v
947 }
948
949 // func (d *jsonDecDriver) jsonU4Arr(bs [4]byte) (r rune) {
950 // // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
951 // var u uint32
952 // for _, v := range bs {
953 // if '0' <= v && v <= '9' {
954 // v = v - '0'
955 // } else if 'a' <= v && v <= 'f' {
956 // v = v - 'a' + 10
957 // } else if 'A' <= v && v <= 'f' {
958 // v = v - 'A' + 10
959 // } else {
960 // // d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
961 // return utf8.RuneError
962 // }
963 // u = u*16 + uint32(v)
964 // }
965 // return rune(u)
966 // }
967
968 func (d *jsonDecDriver) DecodeNaked() {
969 z := d.d.n
970 // var decodeFurther bool
971
972 if d.tok == 0 {
973 d.tok = d.r.skip(&jsonCharWhitespaceSet)
974 }
975 switch d.tok {
976 case 'n':
977 d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
978 z.v = valueTypeNil
979 case 'f':
980 d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
981 z.v = valueTypeBool
982 z.b = false
983 case 't':
984 d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
985 z.v = valueTypeBool
986 z.b = true
987 case '{':
988 z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
989 case '[':
990 z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
991 case '"':
992 z.v = valueTypeString
993 z.s = d.DecodeString()
994 default: // number
995 bs := d.decNumBytes()
996 var err error
997 if len(bs) == 0 {
998 d.d.errorf("json: decode number from empty string")
999 return
1000 } else if d.h.PreferFloat || jsonIsFloatBytesB3(bs) { // bytes.IndexByte(bs, '.') != -1 ||...
1001 // } else if d.h.PreferFloat || bytes.ContainsAny(bs, ".eE") {
1002 z.v = valueTypeFloat
1003 z.f, err = strconv.ParseFloat(stringView(bs), 64)
1004 } else if d.h.SignedInteger || bs[0] == '-' {
1005 z.v = valueTypeInt
1006 z.i, err = strconv.ParseInt(stringView(bs), 10, 64)
1007 } else {
1008 z.v = valueTypeUint
1009 z.u, err = strconv.ParseUint(stringView(bs), 10, 64)
1010 }
1011 if err != nil {
1012 if z.v == valueTypeInt || z.v == valueTypeUint {
1013 if v, ok := err.(*strconv.NumError); ok && (v.Err == strconv.ErrRange || v.Err == strconv.ErrSyntax) {
1014 z.v = valueTypeFloat
1015 z.f, err = strconv.ParseFloat(stringView(bs), 64)
1016 }
1017 }
1018 if err != nil {
1019 d.d.errorf("json: decode number from %s: %v", bs, err)
1020 return
1021 }
1022 }
1023 }
1024 // if decodeFurther {
1025 // d.s.sc.retryRead()
1026 // }
1027 return
1028 }
1029
1030 //----------------------
1031
1032 // JsonHandle is a handle for JSON encoding format.
1033 //
1034 // Json is comprehensively supported:
1035 // - decodes numbers into interface{} as int, uint or float64
1036 // - configurable way to encode/decode []byte .
1037 // by default, encodes and decodes []byte using base64 Std Encoding
1038 // - UTF-8 support for encoding and decoding
1039 //
1040 // It has better performance than the json library in the standard library,
1041 // by leveraging the performance improvements of the codec library and
1042 // minimizing allocations.
1043 //
1044 // In addition, it doesn't read more bytes than necessary during a decode, which allows
1045 // reading multiple values from a stream containing json and non-json content.
1046 // For example, a user can read a json value, then a cbor value, then a msgpack value,
1047 // all from the same stream in sequence.
1048 type JsonHandle struct {
1049 textEncodingType
1050 BasicHandle
1051
1052 // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
1053 // If not configured, raw bytes are encoded to/from base64 text.
1054 RawBytesExt InterfaceExt
1055
1056 // Indent indicates how a value is encoded.
1057 // - If positive, indent by that number of spaces.
1058 // - If negative, indent by that number of tabs.
1059 Indent int8
1060
1061 // IntegerAsString controls how integers (signed and unsigned) are encoded.
1062 //
1063 // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
1064 // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
1065 // This can be mitigated by configuring how to encode integers.
1066 //
1067 // IntegerAsString interpretes the following values:
1068 // - if 'L', then encode integers > 2^53 as a json string.
1069 // - if 'A', then encode all integers as a json string
1070 // containing the exact integer representation as a decimal.
1071 // - else encode all integers as a json number (default)
1072 IntegerAsString uint8
1073
1074 // HTMLCharsAsIs controls how to encode some special characters to html: < > &
1075 //
1076 // By default, we encode them as \uXXX
1077 // to prevent security holes when served from some browsers.
1078 HTMLCharsAsIs bool
1079
1080 // PreferFloat says that we will default to decoding a number as a float.
1081 // If not set, we will examine the characters of the number and decode as an
1082 // integer type if it doesn't have any of the characters [.eE].
1083 PreferFloat bool
1084
1085 // TermWhitespace says that we add a whitespace character
1086 // at the end of an encoding.
1087 //
1088 // The whitespace is important, especially if using numbers in a context
1089 // where multiple items are written to a stream.
1090 TermWhitespace bool
1091 }
1092
1093 func (h *JsonHandle) hasElemSeparators() bool { return true }
1094
1095 func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
1096 return h.SetExt(rt, tag, &setExtWrapper{i: ext})
1097 }
1098
1099 func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
1100 hd := jsonEncDriver{e: e, h: h}
1101 hd.bs = hd.b[:0]
1102
1103 hd.reset()
1104
1105 return &hd
1106 }
1107
1108 func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
1109 // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
1110 hd := jsonDecDriver{d: d, h: h}
1111 hd.bs = hd.b[:0]
1112 hd.reset()
1113 return &hd
1114 }
1115
1116 func (e *jsonEncDriver) reset() {
1117 e.w = e.e.w
1118 e.se.i = e.h.RawBytesExt
1119 if e.bs != nil {
1120 e.bs = e.bs[:0]
1121 }
1122 e.d, e.dt, e.dl, e.ds = false, false, 0, ""
1123 e.c = 0
1124 if e.h.Indent > 0 {
1125 e.d = true
1126 e.ds = jsonSpaces[:e.h.Indent]
1127 } else if e.h.Indent < 0 {
1128 e.d = true
1129 e.dt = true
1130 e.ds = jsonTabs[:-(e.h.Indent)]
1131 }
1132 }
1133
1134 func (d *jsonDecDriver) reset() {
1135 d.r = d.d.r
1136 d.se.i = d.h.RawBytesExt
1137 if d.bs != nil {
1138 d.bs = d.bs[:0]
1139 }
1140 d.c, d.tok = 0, 0
1141 // d.n.reset()
1142 }
1143
1144 // func jsonIsFloatBytes(bs []byte) bool {
1145 // for _, v := range bs {
1146 // // if v == '.' || v == 'e' || v == 'E' {
1147 // if jsonIsFloatSet.isset(v) {
1148 // return true
1149 // }
1150 // }
1151 // return false
1152 // }
1153
1154 func jsonIsFloatBytesB2(bs []byte) bool {
1155 return bytes.IndexByte(bs, '.') != -1 ||
1156 bytes.IndexByte(bs, 'E') != -1
1157 }
1158
1159 func jsonIsFloatBytesB3(bs []byte) bool {
1160 return bytes.IndexByte(bs, '.') != -1 ||
1161 bytes.IndexByte(bs, 'E') != -1 ||
1162 bytes.IndexByte(bs, 'e') != -1
1163 }
1164
1165 // var jsonEncodeTerminate = []byte{' '}
1166
1167 // func (h *JsonHandle) rpcEncodeTerminate() []byte {
1168 // return jsonEncodeTerminate
1169 // }
1170
1171 var _ decDriver = (*jsonDecDriver)(nil)
1172 var _ encDriver = (*jsonEncDriver)(nil)