Debian Codegraph @

vendor/github.com/ugorji/go/codec/decode.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 import (
7 "encoding"
8 "errors"
9 "fmt"
10 "io"
11 "reflect"
12 "sync"
13 "time"
14 )
15
16 // Some tagging information for error messages.
17 const (
18 msgBadDesc = "Unrecognized descriptor byte"
19 msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v"
20 )
21
22 var (
23 onlyMapOrArrayCanDecodeIntoStructErr = errors.New("only encoded map or array can be decoded into a struct")
24 cannotDecodeIntoNilErr = errors.New("cannot decode into nil")
25
26 decUnreadByteNothingToReadErr = errors.New("cannot unread - nothing has been read")
27 decUnreadByteLastByteNotReadErr = errors.New("cannot unread - last byte has not been read")
28 decUnreadByteUnknownErr = errors.New("cannot unread - reason unknown")
29 )
30
31 // decReader abstracts the reading source, allowing implementations that can
32 // read from an io.Reader or directly off a byte slice with zero-copying.
33 type decReader interface {
34 unreadn1()
35
36 // readx will use the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR
37 // just return a view of the []byte being decoded from.
38 // Ensure you call detachZeroCopyBytes later if this needs to be sent outside codec control.
39 readx(n int) []byte
40 readb([]byte)
41 readn1() uint8
42 readn3() (uint8, uint8, uint8)
43 readn4() (uint8, uint8, uint8, uint8)
44 // readn1eof() (v uint8, eof bool)
45 numread() int // number of bytes read
46 track()
47 stopTrack() []byte
48
49 // skip will skip any byte that matches, and return the first non-matching byte
50 skip(accept *bitset256) (token byte)
51 // readTo will read any byte that matches, stopping once no-longer matching.
52 readTo(in []byte, accept *bitset256) (out []byte)
53 // readUntil will read, only stopping once it matches the 'stop' byte.
54 readUntil(in []byte, stop byte) (out []byte)
55 }
56
57 // type decReaderByteScanner interface {
58 // io.Reader
59 // io.ByteScanner
60 // }
61
62 type decDriver interface {
63 // this will check if the next token is a break.
64 CheckBreak() bool
65 // Note: TryDecodeAsNil should be careful not to share any temporary []byte with
66 // the rest of the decDriver. This is because sometimes, we optimize by holding onto
67 // a transient []byte, and ensuring the only other call we make to the decDriver
68 // during that time is maybe a TryDecodeAsNil() call.
69 TryDecodeAsNil() bool
70 // vt is one of: Bytes, String, Nil, Slice or Map. Return unSet if not known.
71 ContainerType() (vt valueType)
72 // IsBuiltinType(rt uintptr) bool
73 DecodeBuiltin(rt uintptr, v interface{})
74
75 // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt.
76 // For maps and arrays, it will not do the decoding in-band, but will signal
77 // the decoder, so that is done later, by setting the decNaked.valueType field.
78 //
79 // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
80 // for extensions, DecodeNaked must read the tag and the []byte if it exists.
81 // if the []byte is not read, then kInterfaceNaked will treat it as a Handle
82 // that stores the subsequent value in-band, and complete reading the RawExt.
83 //
84 // extensions should also use readx to decode them, for efficiency.
85 // kInterface will extract the detached byte slice if it has to pass it outside its realm.
86 DecodeNaked()
87 DecodeInt(bitsize uint8) (i int64)
88 DecodeUint(bitsize uint8) (ui uint64)
89 DecodeFloat(chkOverflow32 bool) (f float64)
90 DecodeBool() (b bool)
91 // DecodeString can also decode symbols.
92 // It looks redundant as DecodeBytes is available.
93 // However, some codecs (e.g. binc) support symbols and can
94 // return a pre-stored string value, meaning that it can bypass
95 // the cost of []byte->string conversion.
96 DecodeString() (s string)
97 DecodeStringAsBytes() (v []byte)
98
99 // DecodeBytes may be called directly, without going through reflection.
100 // Consequently, it must be designed to handle possible nil.
101 DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte)
102 // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
103
104 // decodeExt will decode into a *RawExt or into an extension.
105 DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64)
106 // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
107 ReadArrayStart() int
108 ReadArrayElem()
109 ReadArrayEnd()
110 ReadMapStart() int
111 ReadMapElemKey()
112 ReadMapElemValue()
113 ReadMapEnd()
114
115 reset()
116 uncacheRead()
117 }
118
119 // type decNoSeparator struct {}
120 // func (_ decNoSeparator) ReadEnd() {}
121
122 type decDriverNoopContainerReader struct{}
123
124 func (_ decDriverNoopContainerReader) ReadArrayStart() (v int) { return }
125 func (_ decDriverNoopContainerReader) ReadArrayElem() {}
126 func (_ decDriverNoopContainerReader) ReadArrayEnd() {}
127 func (_ decDriverNoopContainerReader) ReadMapStart() (v int) { return }
128 func (_ decDriverNoopContainerReader) ReadMapElemKey() {}
129 func (_ decDriverNoopContainerReader) ReadMapElemValue() {}
130 func (_ decDriverNoopContainerReader) ReadMapEnd() {}
131 func (_ decDriverNoopContainerReader) CheckBreak() (v bool) { return }
132
133 // func (_ decNoSeparator) uncacheRead() {}
134
135 type DecodeOptions struct {
136 // MapType specifies type to use during schema-less decoding of a map in the stream.
137 // If nil, we use map[interface{}]interface{}
138 MapType reflect.Type
139
140 // SliceType specifies type to use during schema-less decoding of an array in the stream.
141 // If nil, we use []interface{}
142 SliceType reflect.Type
143
144 // MaxInitLen defines the maxinum initial length that we "make" a collection (string, slice, map, chan).
145 // If 0 or negative, we default to a sensible value based on the size of an element in the collection.
146 //
147 // For example, when decoding, a stream may say that it has 2^64 elements.
148 // We should not auto-matically provision a slice of that length, to prevent Out-Of-Memory crash.
149 // Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
150 MaxInitLen int
151
152 // If ErrorIfNoField, return an error when decoding a map
153 // from a codec stream into a struct, and no matching struct field is found.
154 ErrorIfNoField bool
155
156 // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
157 // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
158 // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
159 ErrorIfNoArrayExpand bool
160
161 // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
162 SignedInteger bool
163
164 // MapValueReset controls how we decode into a map value.
165 //
166 // By default, we MAY retrieve the mapping for a key, and then decode into that.
167 // However, especially with big maps, that retrieval may be expensive and unnecessary
168 // if the stream already contains all that is necessary to recreate the value.
169 //
170 // If true, we will never retrieve the previous mapping,
171 // but rather decode into a new value and set that in the map.
172 //
173 // If false, we will retrieve the previous mapping if necessary e.g.
174 // the previous mapping is a pointer, or is a struct or array with pre-set state,
175 // or is an interface.
176 MapValueReset bool
177
178 // SliceElementReset: on decoding a slice, reset the element to a zero value first.
179 //
180 // concern: if the slice already contained some garbage, we will decode into that garbage.
181 SliceElementReset bool
182
183 // InterfaceReset controls how we decode into an interface.
184 //
185 // By default, when we see a field that is an interface{...},
186 // or a map with interface{...} value, we will attempt decoding into the
187 // "contained" value.
188 //
189 // However, this prevents us from reading a string into an interface{}
190 // that formerly contained a number.
191 //
192 // If true, we will decode into a new "blank" value, and set that in the interface.
193 // If false, we will decode into whatever is contained in the interface.
194 InterfaceReset bool
195
196 // InternString controls interning of strings during decoding.
197 //
198 // Some handles, e.g. json, typically will read map keys as strings.
199 // If the set of keys are finite, it may help reduce allocation to
200 // look them up from a map (than to allocate them afresh).
201 //
202 // Note: Handles will be smart when using the intern functionality.
203 // Every string should not be interned.
204 // An excellent use-case for interning is struct field names,
205 // or map keys where key type is string.
206 InternString bool
207
208 // PreferArrayOverSlice controls whether to decode to an array or a slice.
209 //
210 // This only impacts decoding into a nil interface{}.
211 // Consequently, it has no effect on codecgen.
212 //
213 // *Note*: This only applies if using go1.5 and above,
214 // as it requires reflect.ArrayOf support which was absent before go1.5.
215 PreferArrayOverSlice bool
216
217 // DeleteOnNilMapValue controls how to decode a nil value in the stream.
218 //
219 // If true, we will delete the mapping of the key.
220 // Else, just set the mapping to the zero value of the type.
221 DeleteOnNilMapValue bool
222
223 // ReaderBufferSize is the size of the buffer used when reading.
224 //
225 // if > 0, we use a smart buffer internally for performance purposes.
226 ReaderBufferSize int
227 }
228
229 // ------------------------------------
230
231 type bufioDecReader struct {
232 buf []byte
233 r io.Reader
234
235 c int // cursor
236 n int // num read
237 err error
238
239 trb bool
240 tr []byte
241
242 b [8]byte
243 }
244
245 func (z *bufioDecReader) reset(r io.Reader) {
246 z.r, z.c, z.n, z.err, z.trb = r, 0, 0, nil, false
247 if z.tr != nil {
248 z.tr = z.tr[:0]
249 }
250 }
251
252 func (z *bufioDecReader) Read(p []byte) (n int, err error) {
253 if z.err != nil {
254 return 0, z.err
255 }
256 p0 := p
257 n = copy(p, z.buf[z.c:])
258 z.c += n
259 if z.c == len(z.buf) {
260 z.c = 0
261 }
262 z.n += n
263 if len(p) == n {
264 if z.c == 0 {
265 z.buf = z.buf[:1]
266 z.buf[0] = p[len(p)-1]
267 z.c = 1
268 }
269 if z.trb {
270 z.tr = append(z.tr, p0[:n]...)
271 }
272 return
273 }
274 p = p[n:]
275 var n2 int
276 // if we are here, then z.buf is all read
277 if len(p) > len(z.buf) {
278 n2, err = decReadFull(z.r, p)
279 n += n2
280 z.n += n2
281 z.err = err
282 // don't return EOF if some bytes were read. keep for next time.
283 if n > 0 && err == io.EOF {
284 err = nil
285 }
286 // always keep last byte in z.buf
287 z.buf = z.buf[:1]
288 z.buf[0] = p[len(p)-1]
289 z.c = 1
290 if z.trb {
291 z.tr = append(z.tr, p0[:n]...)
292 }
293 return
294 }
295 // z.c is now 0, and len(p) <= len(z.buf)
296 for len(p) > 0 && z.err == nil {
297 // println("len(p) loop starting ... ")
298 z.c = 0
299 z.buf = z.buf[0:cap(z.buf)]
300 n2, err = z.r.Read(z.buf)
301 if n2 > 0 {
302 if err == io.EOF {
303 err = nil
304 }
305 z.buf = z.buf[:n2]
306 n2 = copy(p, z.buf)
307 z.c = n2
308 n += n2
309 z.n += n2
310 p = p[n2:]
311 }
312 z.err = err
313 // println("... len(p) loop done")
314 }
315 if z.c == 0 {
316 z.buf = z.buf[:1]
317 z.buf[0] = p[len(p)-1]
318 z.c = 1
319 }
320 if z.trb {
321 z.tr = append(z.tr, p0[:n]...)
322 }
323 return
324 }
325
326 func (z *bufioDecReader) ReadByte() (b byte, err error) {
327 z.b[0] = 0
328 _, err = z.Read(z.b[:1])
329 b = z.b[0]
330 return
331 }
332
333 func (z *bufioDecReader) UnreadByte() (err error) {
334 if z.err != nil {
335 return z.err
336 }
337 if z.c > 0 {
338 z.c--
339 z.n--
340 if z.trb {
341 z.tr = z.tr[:len(z.tr)-1]
342 }
343 return
344 }
345 return decUnreadByteNothingToReadErr
346 }
347
348 func (z *bufioDecReader) numread() int {
349 return z.n
350 }
351
352 func (z *bufioDecReader) readx(n int) (bs []byte) {
353 if n <= 0 || z.err != nil {
354 return
355 }
356 if z.c+n <= len(z.buf) {
357 bs = z.buf[z.c : z.c+n]
358 z.n += n
359 z.c += n
360 if z.trb {
361 z.tr = append(z.tr, bs...)
362 }
363 return
364 }
365 bs = make([]byte, n)
366 _, err := z.Read(bs)
367 if err != nil {
368 panic(err)
369 }
370 return
371 }
372
373 func (z *bufioDecReader) readb(bs []byte) {
374 _, err := z.Read(bs)
375 if err != nil {
376 panic(err)
377 }
378 }
379
380 // func (z *bufioDecReader) readn1eof() (b uint8, eof bool) {
381 // b, err := z.ReadByte()
382 // if err != nil {
383 // if err == io.EOF {
384 // eof = true
385 // } else {
386 // panic(err)
387 // }
388 // }
389 // return
390 // }
391
392 func (z *bufioDecReader) readn1() (b uint8) {
393 b, err := z.ReadByte()
394 if err != nil {
395 panic(err)
396 }
397 return
398 }
399
400 func (z *bufioDecReader) readn3() (b1, b2, b3 uint8) {
401 z.readb(z.b[:3])
402 return z.b[0], z.b[1], z.b[2]
403 }
404
405 func (z *bufioDecReader) readn4() (b1, b2, b3, b4 uint8) {
406 z.readb(z.b[:4])
407 return z.b[0], z.b[1], z.b[2], z.b[3]
408 }
409
410 func (z *bufioDecReader) search(in []byte, accept *bitset256, stop, flag uint8) (token byte, out []byte) {
411 // flag: 1 (skip), 2 (readTo), 4 (readUntil)
412 if flag == 4 {
413 for i := z.c; i < len(z.buf); i++ {
414 if z.buf[i] == stop {
415 token = z.buf[i]
416 z.n = z.n + (i - z.c) - 1
417 i++
418 out = z.buf[z.c:i]
419 if z.trb {
420 z.tr = append(z.tr, z.buf[z.c:i]...)
421 }
422 z.c = i
423 return
424 }
425 }
426 } else {
427 for i := z.c; i < len(z.buf); i++ {
428 if !accept.isset(z.buf[i]) {
429 token = z.buf[i]
430 z.n = z.n + (i - z.c) - 1
431 if flag == 1 {
432 i++
433 } else {
434 out = z.buf[z.c:i]
435 }
436 if z.trb {
437 z.tr = append(z.tr, z.buf[z.c:i]...)
438 }
439 z.c = i
440 return
441 }
442 }
443 }
444 z.n += len(z.buf) - z.c
445 if flag != 1 {
446 out = append(in, z.buf[z.c:]...)
447 }
448 if z.trb {
449 z.tr = append(z.tr, z.buf[z.c:]...)
450 }
451 var n2 int
452 if z.err != nil {
453 return
454 }
455 for {
456 z.c = 0
457 z.buf = z.buf[0:cap(z.buf)]
458 n2, z.err = z.r.Read(z.buf)
459 if n2 > 0 && z.err != nil {
460 z.err = nil
461 }
462 z.buf = z.buf[:n2]
463 if flag == 4 {
464 for i := 0; i < n2; i++ {
465 if z.buf[i] == stop {
466 token = z.buf[i]
467 z.n += i - 1
468 i++
469 out = append(out, z.buf[z.c:i]...)
470 if z.trb {
471 z.tr = append(z.tr, z.buf[z.c:i]...)
472 }
473 z.c = i
474 return
475 }
476 }
477 } else {
478 for i := 0; i < n2; i++ {
479 if !accept.isset(z.buf[i]) {
480 token = z.buf[i]
481 z.n += i - 1
482 if flag == 1 {
483 i++
484 }
485 if flag != 1 {
486 out = append(out, z.buf[z.c:i]...)
487 }
488 if z.trb {
489 z.tr = append(z.tr, z.buf[z.c:i]...)
490 }
491 z.c = i
492 return
493 }
494 }
495 }
496 if flag != 1 {
497 out = append(out, z.buf[:n2]...)
498 }
499 z.n += n2
500 if z.err != nil {
501 return
502 }
503 if z.trb {
504 z.tr = append(z.tr, z.buf[:n2]...)
505 }
506 }
507 }
508
509 func (z *bufioDecReader) skip(accept *bitset256) (token byte) {
510 token, _ = z.search(nil, accept, 0, 1)
511 return
512 }
513
514 func (z *bufioDecReader) readTo(in []byte, accept *bitset256) (out []byte) {
515 _, out = z.search(in, accept, 0, 2)
516 return
517 }
518
519 func (z *bufioDecReader) readUntil(in []byte, stop byte) (out []byte) {
520 _, out = z.search(in, nil, stop, 4)
521 return
522 }
523
524 func (z *bufioDecReader) unreadn1() {
525 err := z.UnreadByte()
526 if err != nil {
527 panic(err)
528 }
529 }
530
531 func (z *bufioDecReader) track() {
532 if z.tr != nil {
533 z.tr = z.tr[:0]
534 }
535 z.trb = true
536 }
537
538 func (z *bufioDecReader) stopTrack() (bs []byte) {
539 z.trb = false
540 return z.tr
541 }
542
543 // ioDecReader is a decReader that reads off an io.Reader.
544 //
545 // It also has a fallback implementation of ByteScanner if needed.
546 type ioDecReader struct {
547 r io.Reader // the reader passed in
548
549 rr io.Reader
550 br io.ByteScanner
551
552 l byte // last byte
553 ls byte // last byte status. 0: init-canDoNothing, 1: canRead, 2: canUnread
554 b [4]byte // tiny buffer for reading single bytes
555 trb bool // tracking bytes turned on
556
557 // temp byte array re-used internally for efficiency during read.
558 // shares buffer with Decoder, so we keep size of struct within 8 words.
559 x *[scratchByteArrayLen]byte
560 n int // num read
561 tr []byte // tracking bytes read
562 }
563
564 func (z *ioDecReader) reset(r io.Reader) {
565 z.r = r
566 z.rr = r
567 z.l, z.ls, z.n, z.trb = 0, 0, 0, false
568 if z.tr != nil {
569 z.tr = z.tr[:0]
570 }
571 var ok bool
572 if z.br, ok = r.(io.ByteScanner); !ok {
573 z.br = z
574 z.rr = z
575 }
576 }
577
578 func (z *ioDecReader) Read(p []byte) (n int, err error) {
579 if len(p) == 0 {
580 return
581 }
582 var firstByte bool
583 if z.ls == 1 {
584 z.ls = 2
585 p[0] = z.l
586 if len(p) == 1 {
587 n = 1
588 return
589 }
590 firstByte = true
591 p = p[1:]
592 }
593 n, err = z.r.Read(p)
594 if n > 0 {
595 if err == io.EOF && n == len(p) {
596 err = nil // read was successful, so postpone EOF (till next time)
597 }
598 z.l = p[n-1]
599 z.ls = 2
600 }
601 if firstByte {
602 n++
603 }
604 return
605 }
606
607 func (z *ioDecReader) ReadByte() (c byte, err error) {
608 n, err := z.Read(z.b[:1])
609 if n == 1 {
610 c = z.b[0]
611 if err == io.EOF {
612 err = nil // read was successful, so postpone EOF (till next time)
613 }
614 }
615 return
616 }
617
618 func (z *ioDecReader) UnreadByte() (err error) {
619 switch z.ls {
620 case 2:
621 z.ls = 1
622 case 0:
623 err = decUnreadByteNothingToReadErr
624 case 1:
625 err = decUnreadByteLastByteNotReadErr
626 default:
627 err = decUnreadByteUnknownErr
628 }
629 return
630 }
631
632 func (z *ioDecReader) numread() int {
633 return z.n
634 }
635
636 func (z *ioDecReader) readx(n int) (bs []byte) {
637 if n <= 0 {
638 return
639 }
640 if n < len(z.x) {
641 bs = z.x[:n]
642 } else {
643 bs = make([]byte, n)
644 }
645 if _, err := decReadFull(z.rr, bs); err != nil {
646 panic(err)
647 }
648 z.n += len(bs)
649 if z.trb {
650 z.tr = append(z.tr, bs...)
651 }
652 return
653 }
654
655 func (z *ioDecReader) readb(bs []byte) {
656 // if len(bs) == 0 {
657 // return
658 // }
659 if _, err := decReadFull(z.rr, bs); err != nil {
660 panic(err)
661 }
662 z.n += len(bs)
663 if z.trb {
664 z.tr = append(z.tr, bs...)
665 }
666 }
667
668 func (z *ioDecReader) readn1eof() (b uint8, eof bool) {
669 b, err := z.br.ReadByte()
670 if err == nil {
671 z.n++
672 if z.trb {
673 z.tr = append(z.tr, b)
674 }
675 } else if err == io.EOF {
676 eof = true
677 } else {
678 panic(err)
679 }
680 return
681 }
682
683 func (z *ioDecReader) readn1() (b uint8) {
684 var err error
685 if b, err = z.br.ReadByte(); err == nil {
686 z.n++
687 if z.trb {
688 z.tr = append(z.tr, b)
689 }
690 return
691 }
692 panic(err)
693 }
694
695 func (z *ioDecReader) readn3() (b1, b2, b3 uint8) {
696 z.readb(z.b[:3])
697 return z.b[0], z.b[1], z.b[2]
698 }
699
700 func (z *ioDecReader) readn4() (b1, b2, b3, b4 uint8) {
701 z.readb(z.b[:4])
702 return z.b[0], z.b[1], z.b[2], z.b[3]
703 }
704
705 func (z *ioDecReader) skip(accept *bitset256) (token byte) {
706 for {
707 var eof bool
708 token, eof = z.readn1eof()
709 if eof {
710 return
711 }
712 if accept.isset(token) {
713 continue
714 }
715 return
716 }
717 }
718
719 func (z *ioDecReader) readTo(in []byte, accept *bitset256) (out []byte) {
720 out = in
721 for {
722 token, eof := z.readn1eof()
723 if eof {
724 return
725 }
726 if accept.isset(token) {
727 out = append(out, token)
728 } else {
729 z.unreadn1()
730 return
731 }
732 }
733 }
734
735 func (z *ioDecReader) readUntil(in []byte, stop byte) (out []byte) {
736 out = in
737 for {
738 token, eof := z.readn1eof()
739 if eof {
740 panic(io.EOF)
741 }
742 out = append(out, token)
743 if token == stop {
744 return
745 }
746 }
747 }
748
749 func (z *ioDecReader) unreadn1() {
750 err := z.br.UnreadByte()
751 if err != nil {
752 panic(err)
753 }
754 z.n--
755 if z.trb {
756 if l := len(z.tr) - 1; l >= 0 {
757 z.tr = z.tr[:l]
758 }
759 }
760 }
761
762 func (z *ioDecReader) track() {
763 if z.tr != nil {
764 z.tr = z.tr[:0]
765 }
766 z.trb = true
767 }
768
769 func (z *ioDecReader) stopTrack() (bs []byte) {
770 z.trb = false
771 return z.tr
772 }
773
774 // ------------------------------------
775
776 var bytesDecReaderCannotUnreadErr = errors.New("cannot unread last byte read")
777
778 // bytesDecReader is a decReader that reads off a byte slice with zero copying
779 type bytesDecReader struct {
780 b []byte // data
781 c int // cursor
782 a int // available
783 t int // track start
784 }
785
786 func (z *bytesDecReader) reset(in []byte) {
787 z.b = in
788 z.a = len(in)
789 z.c = 0
790 z.t = 0
791 }
792
793 func (z *bytesDecReader) numread() int {
794 return z.c
795 }
796
797 func (z *bytesDecReader) unreadn1() {
798 if z.c == 0 || len(z.b) == 0 {
799 panic(bytesDecReaderCannotUnreadErr)
800 }
801 z.c--
802 z.a++
803 return
804 }
805
806 func (z *bytesDecReader) readx(n int) (bs []byte) {
807 // slicing from a non-constant start position is more expensive,
808 // as more computation is required to decipher the pointer start position.
809 // However, we do it only once, and it's better than reslicing both z.b and return value.
810
811 if n <= 0 {
812 } else if z.a == 0 {
813 panic(io.EOF)
814 } else if n > z.a {
815 panic(io.ErrUnexpectedEOF)
816 } else {
817 c0 := z.c
818 z.c = c0 + n
819 z.a = z.a - n
820 bs = z.b[c0:z.c]
821 }
822 return
823 }
824
825 func (z *bytesDecReader) readb(bs []byte) {
826 copy(bs, z.readx(len(bs)))
827 }
828
829 func (z *bytesDecReader) readn1() (v uint8) {
830 if z.a == 0 {
831 panic(io.EOF)
832 }
833 v = z.b[z.c]
834 z.c++
835 z.a--
836 return
837 }
838
839 func (z *bytesDecReader) readn3() (b1, b2, b3 uint8) {
840 if 3 > z.a {
841 panic(io.ErrUnexpectedEOF)
842 }
843 b3 = z.b[z.c+2]
844 b2 = z.b[z.c+1]
845 b1 = z.b[z.c]
846 z.c += 3
847 z.a -= 3
848 return
849 }
850
851 func (z *bytesDecReader) readn4() (b1, b2, b3, b4 uint8) {
852 if 4 > z.a {
853 panic(io.ErrUnexpectedEOF)
854 }
855 b4 = z.b[z.c+3]
856 b3 = z.b[z.c+2]
857 b2 = z.b[z.c+1]
858 b1 = z.b[z.c]
859 z.c += 4
860 z.a -= 4
861 return
862 }
863
864 // func (z *bytesDecReader) readn1eof() (v uint8, eof bool) {
865 // if z.a == 0 {
866 // eof = true
867 // return
868 // }
869 // v = z.b[z.c]
870 // z.c++
871 // z.a--
872 // return
873 // }
874
875 func (z *bytesDecReader) skip(accept *bitset256) (token byte) {
876 if z.a == 0 {
877 return
878 }
879 blen := len(z.b)
880 for i := z.c; i < blen; i++ {
881 if !accept.isset(z.b[i]) {
882 token = z.b[i]
883 i++
884 z.a -= (i - z.c)
885 z.c = i
886 return
887 }
888 }
889 z.a, z.c = 0, blen
890 return
891 }
892
893 func (z *bytesDecReader) readTo(_ []byte, accept *bitset256) (out []byte) {
894 if z.a == 0 {
895 return
896 }
897 blen := len(z.b)
898 for i := z.c; i < blen; i++ {
899 if !accept.isset(z.b[i]) {
900 out = z.b[z.c:i]
901 z.a -= (i - z.c)
902 z.c = i
903 return
904 }
905 }
906 out = z.b[z.c:]
907 z.a, z.c = 0, blen
908 return
909 }
910
911 func (z *bytesDecReader) readUntil(_ []byte, stop byte) (out []byte) {
912 if z.a == 0 {
913 panic(io.EOF)
914 }
915 blen := len(z.b)
916 for i := z.c; i < blen; i++ {
917 if z.b[i] == stop {
918 i++
919 out = z.b[z.c:i]
920 z.a -= (i - z.c)
921 z.c = i
922 return
923 }
924 }
925 z.a, z.c = 0, blen
926 panic(io.EOF)
927 }
928
929 func (z *bytesDecReader) track() {
930 z.t = z.c
931 }
932
933 func (z *bytesDecReader) stopTrack() (bs []byte) {
934 return z.b[z.t:z.c]
935 }
936
937 // ----------------------------------------
938
939 func (d *Decoder) builtin(f *codecFnInfo, rv reflect.Value) {
940 d.d.DecodeBuiltin(f.ti.rtid, rv2i(rv))
941 }
942
943 func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) {
944 d.d.DecodeExt(rv2i(rv), 0, nil)
945 }
946
947 func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) {
948 d.d.DecodeExt(rv2i(rv), f.xfTag, f.xfFn)
949 }
950
951 func (d *Decoder) getValueForUnmarshalInterface(rv reflect.Value, indir int8) (v interface{}) {
952 if indir == -1 {
953 v = rv2i(rv.Addr())
954 } else if indir == 0 {
955 v = rv2i(rv)
956 } else {
957 for j := int8(0); j < indir; j++ {
958 if rv.IsNil() {
959 rv.Set(reflect.New(rv.Type().Elem()))
960 }
961 rv = rv.Elem()
962 }
963 v = rv2i(rv)
964 }
965 return
966 }
967
968 func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) {
969 d.getValueForUnmarshalInterface(rv, f.ti.csIndir).(Selfer).CodecDecodeSelf(d)
970 }
971
972 func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) {
973 bm := d.getValueForUnmarshalInterface(rv, f.ti.bunmIndir).(encoding.BinaryUnmarshaler)
974 xbs := d.d.DecodeBytes(nil, true)
975 if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil {
976 panic(fnerr)
977 }
978 }
979
980 func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) {
981 tm := d.getValueForUnmarshalInterface(rv, f.ti.tunmIndir).(encoding.TextUnmarshaler)
982 fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes())
983 if fnerr != nil {
984 panic(fnerr)
985 }
986 }
987
988 func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) {
989 tm := d.getValueForUnmarshalInterface(rv, f.ti.junmIndir).(jsonUnmarshaler)
990 // bs := d.d.DecodeBytes(d.b[:], true, true)
991 // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
992 fnerr := tm.UnmarshalJSON(d.nextValueBytes())
993 if fnerr != nil {
994 panic(fnerr)
995 }
996 }
997
998 func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) {
999 d.errorf("no decoding function defined for kind %v", rv.Kind())
1000 }
1001
1002 // var kIntfCtr uint64
1003
1004 func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) {
1005 // nil interface:
1006 // use some hieristics to decode it appropriately
1007 // based on the detected next value in the stream.
1008 n := d.naked()
1009 d.d.DecodeNaked()
1010 if n.v == valueTypeNil {
1011 return
1012 }
1013 // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader).
1014 // if num := f.ti.rt.NumMethod(); num > 0 {
1015 if f.ti.numMeth > 0 {
1016 d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth)
1017 return
1018 }
1019 // var useRvn bool
1020 switch n.v {
1021 case valueTypeMap:
1022 if d.mtid == 0 || d.mtid == mapIntfIntfTypId {
1023 if n.lm < arrayCacheLen {
1024 n.ma[n.lm] = nil
1025 rvn = n.rr[decNakedMapIntfIntfIdx*arrayCacheLen+n.lm]
1026 n.lm++
1027 d.decode(&n.ma[n.lm-1])
1028 n.lm--
1029 } else {
1030 var v2 map[interface{}]interface{}
1031 d.decode(&v2)
1032 rvn = reflect.ValueOf(&v2).Elem()
1033 }
1034 } else if d.mtid == mapStrIntfTypId { // for json performance
1035 if n.ln < arrayCacheLen {
1036 n.na[n.ln] = nil
1037 rvn = n.rr[decNakedMapStrIntfIdx*arrayCacheLen+n.ln]
1038 n.ln++
1039 d.decode(&n.na[n.ln-1])
1040 n.ln--
1041 } else {
1042 var v2 map[string]interface{}
1043 d.decode(&v2)
1044 rvn = reflect.ValueOf(&v2).Elem()
1045 }
1046 } else {
1047 rvn = reflect.New(d.h.MapType)
1048 if useLookupRecognizedTypes && d.mtr { // isRecognizedRtid(d.mtid) {
1049 d.decode(rv2i(rvn))
1050 rvn = rvn.Elem()
1051 } else {
1052 rvn = rvn.Elem()
1053 d.decodeValue(rvn, nil, false, true)
1054 }
1055 }
1056 case valueTypeArray:
1057 if d.stid == 0 || d.stid == intfSliceTypId {
1058 if n.ls < arrayCacheLen {
1059 n.sa[n.ls] = nil
1060 rvn = n.rr[decNakedSliceIntfIdx*arrayCacheLen+n.ls]
1061 n.ls++
1062 d.decode(&n.sa[n.ls-1])
1063 n.ls--
1064 } else {
1065 var v2 []interface{}
1066 d.decode(&v2)
1067 rvn = reflect.ValueOf(&v2).Elem()
1068 }
1069 if reflectArrayOfSupported && d.stid == 0 && d.h.PreferArrayOverSlice {
1070 rvn2 := reflect.New(reflectArrayOf(rvn.Len(), intfTyp)).Elem()
1071 reflect.Copy(rvn2, rvn)
1072 rvn = rvn2
1073 }
1074 } else {
1075 rvn = reflect.New(d.h.SliceType)
1076 if useLookupRecognizedTypes && d.str { // isRecognizedRtid(d.stid) {
1077 d.decode(rv2i(rvn))
1078 rvn = rvn.Elem()
1079 } else {
1080 rvn = rvn.Elem()
1081 d.decodeValue(rvn, nil, false, true)
1082 }
1083 }
1084 case valueTypeExt:
1085 var v interface{}
1086 tag, bytes := n.u, n.l // calling decode below might taint the values
1087 if bytes == nil {
1088 if n.li < arrayCacheLen {
1089 n.ia[n.li] = nil
1090 n.li++
1091 d.decode(&n.ia[n.li-1])
1092 // v = *(&n.ia[l])
1093 n.li--
1094 v = n.ia[n.li]
1095 n.ia[n.li] = nil
1096 } else {
1097 d.decode(&v)
1098 }
1099 }
1100 bfn := d.h.getExtForTag(tag)
1101 if bfn == nil {
1102 var re RawExt
1103 re.Tag = tag
1104 re.Data = detachZeroCopyBytes(d.bytes, nil, bytes)
1105 re.Value = v
1106 rvn = reflect.ValueOf(&re).Elem()
1107 } else {
1108 rvnA := reflect.New(bfn.rt)
1109 if bytes != nil {
1110 bfn.ext.ReadExt(rv2i(rvnA), bytes)
1111 } else {
1112 bfn.ext.UpdateExt(rv2i(rvnA), v)
1113 }
1114 rvn = rvnA.Elem()
1115 }
1116 case valueTypeNil:
1117 // no-op
1118 case valueTypeInt:
1119 rvn = n.rr[decNakedIntIdx] // d.np.get(&n.i)
1120 case valueTypeUint:
1121 rvn = n.rr[decNakedUintIdx] // d.np.get(&n.u)
1122 case valueTypeFloat:
1123 rvn = n.rr[decNakedFloatIdx] // d.np.get(&n.f)
1124 case valueTypeBool:
1125 rvn = n.rr[decNakedBoolIdx] // d.np.get(&n.b)
1126 case valueTypeString, valueTypeSymbol:
1127 rvn = n.rr[decNakedStringIdx] // d.np.get(&n.s)
1128 case valueTypeBytes:
1129 rvn = n.rr[decNakedBytesIdx] // d.np.get(&n.l)
1130 case valueTypeTimestamp:
1131 rvn = n.rr[decNakedTimeIdx] // d.np.get(&n.t)
1132 default:
1133 panic(fmt.Errorf("kInterfaceNaked: unexpected valueType: %d", n.v))
1134 }
1135 return
1136 }
1137
1138 func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
1139 // Note:
1140 // A consequence of how kInterface works, is that
1141 // if an interface already contains something, we try
1142 // to decode into what was there before.
1143 // We do not replace with a generic value (as got from decodeNaked).
1144
1145 // every interface passed here MUST be settable.
1146 var rvn reflect.Value
1147 if rv.IsNil() {
1148 if rvn = d.kInterfaceNaked(f); rvn.IsValid() {
1149 rv.Set(rvn)
1150 }
1151 return
1152 }
1153 if d.h.InterfaceReset {
1154 if rvn = d.kInterfaceNaked(f); rvn.IsValid() {
1155 rv.Set(rvn)
1156 } else {
1157 // reset to zero value based on current type in there.
1158 rv.Set(reflect.Zero(rv.Elem().Type()))
1159 }
1160 return
1161 }
1162
1163 // now we have a non-nil interface value, meaning it contains a type
1164 rvn = rv.Elem()
1165 if d.d.TryDecodeAsNil() {
1166 rv.Set(reflect.Zero(rvn.Type()))
1167 return
1168 }
1169
1170 // Note: interface{} is settable, but underlying type may not be.
1171 // Consequently, we MAY have to create a decodable value out of the underlying value,
1172 // decode into it, and reset the interface itself.
1173 // fmt.Printf(">>>> kInterface: rvn type: %v, rv type: %v\n", rvn.Type(), rv.Type())
1174
1175 rvn2, canDecode := isDecodeable(rvn)
1176 if canDecode {
1177 d.decodeValue(rvn2, nil, true, true)
1178 return
1179 }
1180
1181 rvn2 = reflect.New(rvn.Type()).Elem()
1182 rvn2.Set(rvn)
1183 d.decodeValue(rvn2, nil, true, true)
1184 rv.Set(rvn2)
1185 }
1186
1187 func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
1188 // checking if recognized within kstruct is too expensive.
1189 // only check where you can determine if valid outside the loop
1190 // ie on homogenous collections: slices, arrays and maps.
1191 //
1192 // if true, we don't create too many decFn's.
1193 // It's a delicate balance.
1194 const checkRecognized bool = false // false: TODO
1195
1196 fti := f.ti
1197 dd := d.d
1198 elemsep := d.hh.hasElemSeparators()
1199 sfn := structFieldNode{v: rv, update: true}
1200 ctyp := dd.ContainerType()
1201 if ctyp == valueTypeMap {
1202 containerLen := dd.ReadMapStart()
1203 if containerLen == 0 {
1204 dd.ReadMapEnd()
1205 return
1206 }
1207 tisfi := fti.sfi
1208 hasLen := containerLen >= 0
1209
1210 for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
1211 // rvkencname := dd.DecodeString()
1212 if elemsep {
1213 dd.ReadMapElemKey()
1214 }
1215 rvkencnameB := dd.DecodeStringAsBytes()
1216 rvkencname := stringView(rvkencnameB)
1217 // rvksi := ti.getForEncName(rvkencname)
1218 if elemsep {
1219 dd.ReadMapElemValue()
1220 }
1221 if k := fti.indexForEncName(rvkencname); k > -1 {
1222 si := tisfi[k]
1223 if dd.TryDecodeAsNil() {
1224 si.setToZeroValue(rv)
1225 } else {
1226 d.decodeValue(sfn.field(si), nil, checkRecognized, true)
1227 }
1228 } else {
1229 d.structFieldNotFound(-1, rvkencname)
1230 }
1231 // keepAlive4StringView(rvkencnameB) // maintain ref 4 stringView // not needed, as reference is outside loop
1232 }
1233 dd.ReadMapEnd()
1234 } else if ctyp == valueTypeArray {
1235 containerLen := dd.ReadArrayStart()
1236 if containerLen == 0 {
1237 dd.ReadArrayEnd()
1238 return
1239 }
1240 // Not much gain from doing it two ways for array.
1241 // Arrays are not used as much for structs.
1242 hasLen := containerLen >= 0
1243 for j, si := range fti.sfip {
1244 if (hasLen && j == containerLen) || (!hasLen && dd.CheckBreak()) {
1245 break
1246 }
1247 if elemsep {
1248 dd.ReadArrayElem()
1249 }
1250 if dd.TryDecodeAsNil() {
1251 si.setToZeroValue(rv)
1252 } else {
1253 d.decodeValue(sfn.field(si), nil, checkRecognized, true)
1254 }
1255 }
1256 if containerLen > len(fti.sfip) {
1257 // read remaining values and throw away
1258 for j := len(fti.sfip); j < containerLen; j++ {
1259 if elemsep {
1260 dd.ReadArrayElem()
1261 }
1262 d.structFieldNotFound(j, "")
1263 }
1264 }
1265 dd.ReadArrayEnd()
1266 } else {
1267 d.error(onlyMapOrArrayCanDecodeIntoStructErr)
1268 return
1269 }
1270 }
1271
1272 func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
1273 // A slice can be set from a map or array in stream.
1274 // This way, the order can be kept (as order is lost with map).
1275 ti := f.ti
1276 dd := d.d
1277 rtelem0 := ti.rt.Elem()
1278 ctyp := dd.ContainerType()
1279 if ctyp == valueTypeBytes || ctyp == valueTypeString {
1280 // you can only decode bytes or string in the stream into a slice or array of bytes
1281 if !(ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) {
1282 d.errorf("bytes or string in the stream must be decoded into a slice or array of bytes, not %v", ti.rt)
1283 }
1284 if f.seq == seqTypeChan {
1285 bs2 := dd.DecodeBytes(nil, true)
1286 ch := rv2i(rv).(chan<- byte)
1287 for _, b := range bs2 {
1288 ch <- b
1289 }
1290 } else {
1291 rvbs := rv.Bytes()
1292 bs2 := dd.DecodeBytes(rvbs, false)
1293 if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) {
1294 if rv.CanSet() {
1295 rv.SetBytes(bs2)
1296 } else {
1297 copy(rvbs, bs2)
1298 }
1299 }
1300 }
1301 return
1302 }
1303
1304 // array := f.seq == seqTypeChan
1305
1306 slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map)
1307
1308 // an array can never return a nil slice. so no need to check f.array here.
1309 if containerLenS == 0 {
1310 if rv.CanSet() {
1311 if f.seq == seqTypeSlice {
1312 if rv.IsNil() {
1313 rv.Set(reflect.MakeSlice(ti.rt, 0, 0))
1314 } else {
1315 rv.SetLen(0)
1316 }
1317 } else if f.seq == seqTypeChan {
1318 if rv.IsNil() {
1319 rv.Set(reflect.MakeChan(ti.rt, 0))
1320 }
1321 }
1322 }
1323 slh.End()
1324 return
1325 }
1326
1327 rtelem0Size := int(rtelem0.Size())
1328 rtElem0Kind := rtelem0.Kind()
1329 rtElem0Id := rt2id(rtelem0)
1330 rtelem0Mut := !isImmutableKind(rtElem0Kind)
1331 rtelem := rtelem0
1332 rtelemkind := rtelem.Kind()
1333 for rtelemkind == reflect.Ptr {
1334 rtelem = rtelem.Elem()
1335 rtelemkind = rtelem.Kind()
1336 }
1337
1338 var fn *codecFn
1339
1340 var rv0, rv9 reflect.Value
1341 rv0 = rv
1342 rvChanged := false
1343
1344 rvlen := rv.Len()
1345 rvcap := rv.Cap()
1346 hasLen := containerLenS > 0
1347 if hasLen && f.seq == seqTypeSlice {
1348 if containerLenS > rvcap {
1349 oldRvlenGtZero := rvlen > 0
1350 rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size()))
1351 if rvlen <= rvcap {
1352 if rv.CanSet() {
1353 rv.SetLen(rvlen)
1354 } else {
1355 rv = rv.Slice(0, rvlen)
1356 rvChanged = true
1357 }
1358 } else {
1359 rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
1360 rvcap = rvlen
1361 rvChanged = true
1362 }
1363 if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) {
1364 reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
1365 }
1366 } else if containerLenS != rvlen {
1367 rvlen = containerLenS
1368 if rv.CanSet() {
1369 rv.SetLen(rvlen)
1370 } else {
1371 rv = rv.Slice(0, rvlen)
1372 rvChanged = true
1373 }
1374 }
1375 }
1376
1377 var recognizedRtid, recognizedRtidPtr bool
1378 if useLookupRecognizedTypes {
1379 recognizedRtid = isRecognizedRtid(rtElem0Id)
1380 recognizedRtidPtr = isRecognizedRtidPtr(rtElem0Id)
1381 }
1382
1383 // consider creating new element once, and just decoding into it.
1384 var rtelem0Zero reflect.Value
1385 var rtelem0ZeroValid bool
1386 var decodeAsNil bool
1387 var j int
1388 for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ {
1389 if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rv.IsNil() {
1390 if hasLen {
1391 rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size)
1392 } else {
1393 rvlen = 8
1394 }
1395 if f.seq == seqTypeSlice {
1396 rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
1397 rvChanged = true
1398 } else if f.seq == seqTypeChan {
1399 rv.Set(reflect.MakeChan(ti.rt, rvlen))
1400 }
1401 }
1402 slh.ElemContainerState(j)
1403 decodeAsNil = dd.TryDecodeAsNil()
1404 if f.seq == seqTypeChan {
1405 if decodeAsNil {
1406 rv.Send(reflect.Zero(rtelem0))
1407 continue
1408 }
1409 if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rv9.IsNil()) {
1410 rv9 = reflect.New(rtelem0).Elem()
1411 }
1412 if useLookupRecognizedTypes && (recognizedRtid || recognizedRtidPtr) {
1413 d.decode(rv2i(rv9.Addr()))
1414 } else {
1415 if fn == nil {
1416 fn = d.cf.get(rtelem, true, true)
1417 }
1418 d.decodeValue(rv9, fn, false, true)
1419 }
1420 rv.Send(rv9)
1421 } else {
1422 // if indefinite, etc, then expand the slice if necessary
1423 var decodeIntoBlank bool
1424 if j >= rvlen {
1425 if f.seq == seqTypeArray {
1426 d.arrayCannotExpand(rvlen, j+1)
1427 decodeIntoBlank = true
1428 } else { // if f.seq == seqTypeSlice
1429 // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // uses append logic, plus varargs
1430 var rvcap2 int
1431 rv9, rvcap2, rvChanged = decExpandSliceRV(rv, ti.rt, rtelem0Size, 1, rvlen, rvcap)
1432 rvlen++
1433 if rvChanged {
1434 rv = rv9
1435 rvcap = rvcap2
1436 }
1437 }
1438 }
1439 if decodeIntoBlank {
1440 if !decodeAsNil {
1441 d.swallow()
1442 }
1443 } else {
1444 rv9 = rv.Index(j)
1445 if d.h.SliceElementReset || decodeAsNil {
1446 if !rtelem0ZeroValid {
1447 rtelem0ZeroValid = true
1448 rtelem0Zero = reflect.Zero(rtelem0)
1449 }
1450 rv9.Set(rtelem0Zero)
1451 }
1452 if decodeAsNil {
1453 continue
1454 }
1455
1456 if useLookupRecognizedTypes && recognizedRtid {
1457 d.decode(rv2i(rv9.Addr()))
1458 } else if useLookupRecognizedTypes && recognizedRtidPtr { // && !rv9.IsNil() {
1459 if rv9.IsNil() {
1460 rv9.Set(reflect.New(rtelem))
1461 }
1462 d.decode(rv2i(rv9))
1463 } else {
1464 if fn == nil {
1465 fn = d.cf.get(rtelem, true, true)
1466 }
1467 d.decodeValue(rv9, fn, false, true)
1468 }
1469 }
1470 }
1471 }
1472 if f.seq == seqTypeSlice {
1473 if j < rvlen {
1474 if rv.CanSet() {
1475 rv.SetLen(j)
1476 } else {
1477 rv = rv.Slice(0, j)
1478 rvChanged = true
1479 }
1480 rvlen = j
1481 } else if j == 0 && rv.IsNil() {
1482 rv = reflect.MakeSlice(ti.rt, 0, 0)
1483 rvChanged = true
1484 }
1485 }
1486 slh.End()
1487
1488 if rvChanged {
1489 rv0.Set(rv)
1490 }
1491 }
1492
1493 // func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
1494 // // d.decodeValueFn(rv.Slice(0, rv.Len()))
1495 // f.kSlice(rv.Slice(0, rv.Len()))
1496 // }
1497
1498 func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
1499 dd := d.d
1500 containerLen := dd.ReadMapStart()
1501 elemsep := d.hh.hasElemSeparators()
1502 ti := f.ti
1503 if rv.IsNil() {
1504 rv.Set(makeMapReflect(ti.rt, containerLen))
1505 }
1506
1507 if containerLen == 0 {
1508 dd.ReadMapEnd()
1509 return
1510 }
1511
1512 ktype, vtype := ti.rt.Key(), ti.rt.Elem()
1513 ktypeId := rt2id(ktype)
1514 vtypeId := rt2id(vtype)
1515 vtypeKind := vtype.Kind()
1516 var recognizedKtyp, recognizedVtyp, recognizedPtrKtyp, recognizedPtrVtyp bool
1517 if useLookupRecognizedTypes {
1518 recognizedKtyp = isRecognizedRtid(ktypeId)
1519 recognizedVtyp = isRecognizedRtid(vtypeId)
1520 recognizedPtrKtyp = isRecognizedRtidPtr(ktypeId)
1521 recognizedPtrVtyp = isRecognizedRtidPtr(vtypeId)
1522 }
1523
1524 var keyFn, valFn *codecFn
1525 var ktypeLo, vtypeLo reflect.Type
1526 for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
1527 }
1528
1529 for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
1530 }
1531
1532 var mapGet, mapSet bool
1533 rvvImmut := isImmutableKind(vtypeKind)
1534 if !d.h.MapValueReset {
1535 // if pointer, mapGet = true
1536 // if interface, mapGet = true if !DecodeNakedAlways (else false)
1537 // if builtin, mapGet = false
1538 // else mapGet = true
1539 if vtypeKind == reflect.Ptr {
1540 mapGet = true
1541 } else if vtypeKind == reflect.Interface {
1542 if !d.h.InterfaceReset {
1543 mapGet = true
1544 }
1545 } else if !rvvImmut {
1546 mapGet = true
1547 }
1548 }
1549
1550 var rvk, rvkp, rvv, rvz reflect.Value
1551 rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk.
1552 ktypeIsString := ktypeId == stringTypId
1553 ktypeIsIntf := ktypeId == intfTypId
1554 hasLen := containerLen > 0
1555 var kstrbs []byte
1556 for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
1557 if elemsep {
1558 dd.ReadMapElemKey()
1559 }
1560 // if a nil key, just ignore the mapped value and continue
1561 if dd.TryDecodeAsNil() {
1562 if elemsep {
1563 dd.ReadMapElemValue()
1564 }
1565 d.swallow()
1566 continue
1567 }
1568 if rvkMut || !rvkp.IsValid() {
1569 rvkp = reflect.New(ktype)
1570 rvk = rvkp.Elem()
1571 }
1572 if ktypeIsString {
1573 kstrbs = dd.DecodeStringAsBytes()
1574 rvk.SetString(stringView(kstrbs))
1575 // NOTE: if doing an insert, you MUST use a real string (not stringview)
1576 } else if useLookupRecognizedTypes && recognizedKtyp {
1577 d.decode(rv2i(rvkp))
1578 // rvk = rvkp.Elem() //TODO: remove, unnecessary
1579 } else if useLookupRecognizedTypes && recognizedPtrKtyp {
1580 if rvk.IsNil() {
1581 rvk = reflect.New(ktypeLo)
1582 }
1583 d.decode(rv2i(rvk))
1584 } else {
1585 if keyFn == nil {
1586 keyFn = d.cf.get(ktypeLo, true, true)
1587 }
1588 d.decodeValue(rvk, keyFn, false, true)
1589 }
1590 // special case if a byte array.
1591 if ktypeIsIntf {
1592 rvk = rvk.Elem()
1593 if rvk.Type() == uint8SliceTyp {
1594 rvk = reflect.ValueOf(d.string(rvk.Bytes()))
1595 }
1596 }
1597
1598 if elemsep {
1599 dd.ReadMapElemValue()
1600 }
1601
1602 // Brittle, but OK per TryDecodeAsNil() contract.
1603 // i.e. TryDecodeAsNil never shares slices with other decDriver procedures
1604 if dd.TryDecodeAsNil() {
1605 if ktypeIsString {
1606 rvk.SetString(d.string(kstrbs))
1607 }
1608 if d.h.DeleteOnNilMapValue {
1609 rv.SetMapIndex(rvk, reflect.Value{})
1610 } else {
1611 rv.SetMapIndex(rvk, reflect.Zero(vtype))
1612 }
1613 continue
1614 }
1615
1616 mapSet = true // set to false if u do a get, and its a non-nil pointer
1617 if mapGet {
1618 // mapGet true only in case where kind=Ptr|Interface or kind is otherwise mutable.
1619 rvv = rv.MapIndex(rvk)
1620 if !rvv.IsValid() {
1621 rvv = reflect.New(vtype).Elem()
1622 } else if vtypeKind == reflect.Ptr {
1623 if rvv.IsNil() {
1624 rvv = reflect.New(vtype).Elem()
1625 } else {
1626 mapSet = false
1627 }
1628 } else if vtypeKind == reflect.Interface {
1629 // not addressable, and thus not settable.
1630 // e MUST create a settable/addressable variant
1631 rvv2 := reflect.New(rvv.Type()).Elem()
1632 if !rvv.IsNil() {
1633 rvv2.Set(rvv)
1634 }
1635 rvv = rvv2
1636 }
1637 // else it is ~mutable, and we can just decode into it directly
1638 } else if rvvImmut {
1639 if !rvz.IsValid() {
1640 rvz = reflect.New(vtype).Elem()
1641 }
1642 rvv = rvz
1643 } else {
1644 rvv = reflect.New(vtype).Elem()
1645 }
1646
1647 // We MUST be done with the stringview of the key, before decoding the value
1648 // so that we don't bastardize the reused byte array.
1649 if mapSet && ktypeIsString {
1650 rvk.SetString(d.string(kstrbs))
1651 }
1652 if useLookupRecognizedTypes && recognizedVtyp && rvv.CanAddr() {
1653 d.decode(rv2i(rvv.Addr()))
1654 } else if useLookupRecognizedTypes && recognizedPtrVtyp {
1655 if rvv.IsNil() {
1656 rvv = reflect.New(vtypeLo)
1657 mapSet = true
1658 }
1659 d.decode(rv2i(rvv))
1660 } else {
1661 if valFn == nil {
1662 valFn = d.cf.get(vtypeLo, true, true)
1663 }
1664 d.decodeValue(rvv, valFn, false, true)
1665 // d.decodeValueFn(rvv, valFn)
1666 }
1667 if mapSet {
1668 rv.SetMapIndex(rvk, rvv)
1669 }
1670 // if ktypeIsString {
1671 // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop
1672 // }
1673 }
1674
1675 dd.ReadMapEnd()
1676 }
1677
1678 // decNaked is used to keep track of the primitives decoded.
1679 // Without it, we would have to decode each primitive and wrap it
1680 // in an interface{}, causing an allocation.
1681 // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
1682 // so we can rest assured that no other decoding happens while these
1683 // primitives are being decoded.
1684 //
1685 // maps and arrays are not handled by this mechanism.
1686 // However, RawExt is, and we accommodate for extensions that decode
1687 // RawExt from DecodeNaked, but need to decode the value subsequently.
1688 // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
1689 //
1690 // However, decNaked also keeps some arrays of default maps and slices
1691 // used in DecodeNaked. This way, we can get a pointer to it
1692 // without causing a new heap allocation.
1693 //
1694 // kInterfaceNaked will ensure that there is no allocation for the common
1695 // uses.
1696 type decNaked struct {
1697 // r RawExt // used for RawExt, uint, []byte.
1698 u uint64
1699 i int64
1700 f float64
1701 l []byte
1702 s string
1703 t time.Time
1704
1705 b bool
1706
1707 inited bool
1708
1709 v valueType
1710
1711 li, lm, ln, ls int8
1712
1713 // array/stacks for reducing allocation
1714 // keep arrays at the bottom? Chance is that they are not used much.
1715 ia [arrayCacheLen]interface{}
1716 ma [arrayCacheLen]map[interface{}]interface{}
1717 na [arrayCacheLen]map[string]interface{}
1718 sa [arrayCacheLen][]interface{}
1719 // ra [2]RawExt
1720
1721 rr [5 * arrayCacheLen]reflect.Value
1722 }
1723
1724 const (
1725 decNakedUintIdx = iota
1726 decNakedIntIdx
1727 decNakedFloatIdx
1728 decNakedBytesIdx
1729 decNakedStringIdx
1730 decNakedTimeIdx
1731 decNakedBoolIdx
1732 )
1733 const (
1734 _ = iota // maps to the scalars above
1735 decNakedIntfIdx
1736 decNakedMapIntfIntfIdx
1737 decNakedMapStrIntfIdx
1738 decNakedSliceIntfIdx
1739 )
1740
1741 func (n *decNaked) init() {
1742 if n.inited {
1743 return
1744 }
1745 // n.ms = n.ma[:0]
1746 // n.is = n.ia[:0]
1747 // n.ns = n.na[:0]
1748 // n.ss = n.sa[:0]
1749
1750 n.rr[decNakedUintIdx] = reflect.ValueOf(&n.u).Elem()
1751 n.rr[decNakedIntIdx] = reflect.ValueOf(&n.i).Elem()
1752 n.rr[decNakedFloatIdx] = reflect.ValueOf(&n.f).Elem()
1753 n.rr[decNakedBytesIdx] = reflect.ValueOf(&n.l).Elem()
1754 n.rr[decNakedStringIdx] = reflect.ValueOf(&n.s).Elem()
1755 n.rr[decNakedTimeIdx] = reflect.ValueOf(&n.t).Elem()
1756 n.rr[decNakedBoolIdx] = reflect.ValueOf(&n.b).Elem()
1757
1758 for i := range [arrayCacheLen]struct{}{} {
1759 n.rr[decNakedIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.ia[i])).Elem()
1760 n.rr[decNakedMapIntfIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.ma[i])).Elem()
1761 n.rr[decNakedMapStrIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.na[i])).Elem()
1762 n.rr[decNakedSliceIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.sa[i])).Elem()
1763 }
1764 n.inited = true
1765 // n.rr[] = reflect.ValueOf(&n.)
1766 }
1767
1768 func (n *decNaked) reset() {
1769 if n == nil {
1770 return
1771 }
1772 n.li, n.lm, n.ln, n.ls = 0, 0, 0, 0
1773 }
1774
1775 type rtid2rv struct {
1776 rtid uintptr
1777 rv reflect.Value
1778 }
1779
1780 // A Decoder reads and decodes an object from an input stream in the codec format.
1781 type Decoder struct {
1782 // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
1783 // Try to put things that go together to fit within a cache line (8 words).
1784
1785 d decDriver
1786 // NOTE: Decoder shouldn't call it's read methods,
1787 // as the handler MAY need to do some coordination.
1788 r decReader
1789 hh Handle
1790 h *BasicHandle
1791
1792 mtr, mtrp, str, strp bool //
1793
1794 be bool // is binary encoding
1795 bytes bool // is bytes reader
1796 js bool // is json handle
1797
1798 // ---- cpu cache line boundary?
1799
1800 rb bytesDecReader
1801 ri ioDecReader
1802 bi bufioDecReader
1803
1804 // cr containerStateRecv
1805
1806 n *decNaked
1807 nsp *sync.Pool
1808
1809 // ---- cpu cache line boundary?
1810
1811 is map[string]string // used for interning strings
1812
1813 // cache the mapTypeId and sliceTypeId for faster comparisons
1814 mtid uintptr
1815 stid uintptr
1816
1817 b [scratchByteArrayLen]byte
1818 // _ uintptr // for alignment purposes, so next one starts from a cache line
1819
1820 err error
1821 // ---- cpu cache line boundary?
1822
1823 cf codecFner
1824 // _ [64]byte // force alignment???
1825 }
1826
1827 // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
1828 //
1829 // For efficiency, Users are encouraged to pass in a memory buffered reader
1830 // (eg bufio.Reader, bytes.Buffer).
1831 func NewDecoder(r io.Reader, h Handle) *Decoder {
1832 d := newDecoder(h)
1833 d.Reset(r)
1834 return d
1835 }
1836
1837 // NewDecoderBytes returns a Decoder which efficiently decodes directly
1838 // from a byte slice with zero copying.
1839 func NewDecoderBytes(in []byte, h Handle) *Decoder {
1840 d := newDecoder(h)
1841 d.ResetBytes(in)
1842 return d
1843 }
1844
1845 var defaultDecNaked decNaked
1846
1847 func newDecoder(h Handle) *Decoder {
1848 d := &Decoder{hh: h, h: h.getBasicHandle(), be: h.isBinary()}
1849
1850 // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
1851
1852 _, d.js = h.(*JsonHandle)
1853 if d.h.InternString {
1854 d.is = make(map[string]string, 32)
1855 }
1856 d.d = h.newDecDriver(d)
1857 // d.cr, _ = d.d.(containerStateRecv)
1858 return d
1859 }
1860
1861 // naked must be called before each call to .DecodeNaked,
1862 // as they will use it.
1863 func (d *Decoder) naked() *decNaked {
1864 if d.n == nil {
1865 // consider one of:
1866 // - get from sync.Pool (if GC is frequent, there's no value here)
1867 // - new alloc (safest. only init'ed if it a naked decode will be done)
1868 // - field in Decoder (makes the Decoder struct very big)
1869 // To support using a decoder where a DecodeNaked is not needed,
1870 // we prefer #1 or #2.
1871 // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool
1872 // d.n.init()
1873 var v interface{}
1874 d.nsp, v = pool.decNaked()
1875 d.n = v.(*decNaked)
1876 }
1877 return d.n
1878 }
1879
1880 func (d *Decoder) resetCommon() {
1881 d.n.reset()
1882 d.d.reset()
1883 d.cf.reset(d.hh)
1884 d.err = nil
1885 // reset all things which were cached from the Handle,
1886 // but could be changed.
1887 d.mtid, d.stid = 0, 0
1888 d.mtr, d.mtrp, d.str, d.strp = false, false, false, false
1889 if d.h.MapType != nil {
1890 d.mtid = rt2id(d.h.MapType)
1891 if useLookupRecognizedTypes {
1892 d.mtr = isRecognizedRtid(d.mtid)
1893 d.mtrp = isRecognizedRtidPtr(d.mtid)
1894 }
1895 }
1896 if d.h.SliceType != nil {
1897 d.stid = rt2id(d.h.SliceType)
1898 if useLookupRecognizedTypes {
1899 d.str = isRecognizedRtid(d.stid)
1900 d.strp = isRecognizedRtidPtr(d.stid)
1901 }
1902 }
1903 }
1904
1905 func (d *Decoder) Reset(r io.Reader) {
1906 if d.h.ReaderBufferSize > 0 {
1907 d.bi.buf = make([]byte, 0, d.h.ReaderBufferSize)
1908 d.bi.reset(r)
1909 d.r = &d.bi
1910 } else {
1911 d.ri.x = &d.b
1912 // d.s = d.sa[:0]
1913 d.ri.reset(r)
1914 d.r = &d.ri
1915 }
1916 d.resetCommon()
1917 }
1918
1919 func (d *Decoder) ResetBytes(in []byte) {
1920 d.bytes = true
1921 d.rb.reset(in)
1922 d.r = &d.rb
1923 d.resetCommon()
1924 }
1925
1926 // Decode decodes the stream from reader and stores the result in the
1927 // value pointed to by v. v cannot be a nil pointer. v can also be
1928 // a reflect.Value of a pointer.
1929 //
1930 // Note that a pointer to a nil interface is not a nil pointer.
1931 // If you do not know what type of stream it is, pass in a pointer to a nil interface.
1932 // We will decode and store a value in that nil interface.
1933 //
1934 // Sample usages:
1935 // // Decoding into a non-nil typed value
1936 // var f float32
1937 // err = codec.NewDecoder(r, handle).Decode(&f)
1938 //
1939 // // Decoding into nil interface
1940 // var v interface{}
1941 // dec := codec.NewDecoder(r, handle)
1942 // err = dec.Decode(&v)
1943 //
1944 // When decoding into a nil interface{}, we will decode into an appropriate value based
1945 // on the contents of the stream:
1946 // - Numbers are decoded as float64, int64 or uint64.
1947 // - Other values are decoded appropriately depending on the type:
1948 // bool, string, []byte, time.Time, etc
1949 // - Extensions are decoded as RawExt (if no ext function registered for the tag)
1950 // Configurations exist on the Handle to override defaults
1951 // (e.g. for MapType, SliceType and how to decode raw bytes).
1952 //
1953 // When decoding into a non-nil interface{} value, the mode of encoding is based on the
1954 // type of the value. When a value is seen:
1955 // - If an extension is registered for it, call that extension function
1956 // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
1957 // - Else decode it based on its reflect.Kind
1958 //
1959 // There are some special rules when decoding into containers (slice/array/map/struct).
1960 // Decode will typically use the stream contents to UPDATE the container.
1961 // - A map can be decoded from a stream map, by updating matching keys.
1962 // - A slice can be decoded from a stream array,
1963 // by updating the first n elements, where n is length of the stream.
1964 // - A slice can be decoded from a stream map, by decoding as if
1965 // it contains a sequence of key-value pairs.
1966 // - A struct can be decoded from a stream map, by updating matching fields.
1967 // - A struct can be decoded from a stream array,
1968 // by updating fields as they occur in the struct (by index).
1969 //
1970 // When decoding a stream map or array with length of 0 into a nil map or slice,
1971 // we reset the destination map or slice to a zero-length value.
1972 //
1973 // However, when decoding a stream nil, we reset the destination container
1974 // to its "zero" value (e.g. nil for slice/map, etc).
1975 //
1976 func (d *Decoder) Decode(v interface{}) (err error) {
1977 defer panicToErrs2(&d.err, &err)
1978 d.MustDecode(v)
1979 return
1980 }
1981
1982 // MustDecode is like Decode, but panics if unable to Decode.
1983 // This provides insight to the code location that triggered the error.
1984 func (d *Decoder) MustDecode(v interface{}) {
1985 // TODO: Top-level: ensure that v is a pointer and not nil.
1986 if d.err != nil {
1987 panic(d.err)
1988 }
1989 if d.d.TryDecodeAsNil() {
1990 d.setZero(v)
1991 } else {
1992 d.decode(v)
1993 }
1994 if d.nsp != nil {
1995 if d.n != nil {
1996 d.nsp.Put(d.n)
1997 d.n = nil
1998 }
1999 d.nsp = nil
2000 }
2001 d.n = nil
2002 // xprintf(">>>>>>>> >>>>>>>> num decFns: %v\n", d.cf.sn)
2003 }
2004
2005 // // this is not a smart swallow, as it allocates objects and does unnecessary work.
2006 // func (d *Decoder) swallowViaHammer() {
2007 // var blank interface{}
2008 // d.decodeValueNoFn(reflect.ValueOf(&blank).Elem())
2009 // }
2010
2011 func (d *Decoder) swallow() {
2012 // smarter decode that just swallows the content
2013 dd := d.d
2014 if dd.TryDecodeAsNil() {
2015 return
2016 }
2017 elemsep := d.hh.hasElemSeparators()
2018 switch dd.ContainerType() {
2019 case valueTypeMap:
2020 containerLen := dd.ReadMapStart()
2021 hasLen := containerLen >= 0
2022 for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
2023 // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break}
2024 if elemsep {
2025 dd.ReadMapElemKey()
2026 }
2027 d.swallow()
2028 if elemsep {
2029 dd.ReadMapElemValue()
2030 }
2031 d.swallow()
2032 }
2033 dd.ReadMapEnd()
2034 case valueTypeArray:
2035 containerLen := dd.ReadArrayStart()
2036 hasLen := containerLen >= 0
2037 for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
2038 if elemsep {
2039 dd.ReadArrayElem()
2040 }
2041 d.swallow()
2042 }
2043 dd.ReadArrayEnd()
2044 case valueTypeBytes:
2045 dd.DecodeBytes(d.b[:], true)
2046 case valueTypeString:
2047 dd.DecodeStringAsBytes()
2048 default:
2049 // these are all primitives, which we can get from decodeNaked
2050 // if RawExt using Value, complete the processing.
2051 n := d.naked()
2052 dd.DecodeNaked()
2053 if n.v == valueTypeExt && n.l == nil {
2054 if n.li < arrayCacheLen {
2055 n.ia[n.li] = nil
2056 n.li++
2057 d.decode(&n.ia[n.li-1])
2058 n.ia[n.li-1] = nil
2059 n.li--
2060 } else {
2061 var v2 interface{}
2062 d.decode(&v2)
2063 }
2064 }
2065 }
2066 }
2067
2068 func (d *Decoder) setZero(iv interface{}) {
2069 if iv == nil || definitelyNil(iv) {
2070 return
2071 }
2072 switch v := iv.(type) {
2073 case *string:
2074 *v = ""
2075 case *bool:
2076 *v = false
2077 case *int:
2078 *v = 0
2079 case *int8:
2080 *v = 0
2081 case *int16:
2082 *v = 0
2083 case *int32:
2084 *v = 0
2085 case *int64:
2086 *v = 0
2087 case *uint:
2088 *v = 0
2089 case *uint8:
2090 *v = 0
2091 case *uint16:
2092 *v = 0
2093 case *uint32:
2094 *v = 0
2095 case *uint64:
2096 *v = 0
2097 case *float32:
2098 *v = 0
2099 case *float64:
2100 *v = 0
2101 case *[]uint8:
2102 *v = nil
2103 case *Raw:
2104 *v = nil
2105 case reflect.Value:
2106 v = d.ensureDecodeable(v)
2107 if v.CanSet() {
2108 v.Set(reflect.Zero(v.Type()))
2109 } // TODO: else drain if chan, clear if map, set all to nil if slice???
2110 default:
2111 if !fastpathDecodeSetZeroTypeSwitch(iv, d) {
2112 v := reflect.ValueOf(iv)
2113 v = d.ensureDecodeable(v)
2114 if v.CanSet() {
2115 v.Set(reflect.Zero(v.Type()))
2116 } // TODO: else drain if chan, clear if map, set all to nil if slice???
2117 }
2118 }
2119 }
2120
2121 func (d *Decoder) decode(iv interface{}) {
2122 // check nil and interfaces explicitly,
2123 // so that type switches just have a run of constant non-interface types.
2124 if iv == nil {
2125 d.error(cannotDecodeIntoNilErr)
2126 return
2127 }
2128 if v, ok := iv.(Selfer); ok {
2129 v.CodecDecodeSelf(d)
2130 return
2131 }
2132
2133 switch v := iv.(type) {
2134 // case nil:
2135 // case Selfer:
2136
2137 case reflect.Value:
2138 v = d.ensureDecodeable(v)
2139 d.decodeValue(v, nil, false, true) // TODO: maybe ask to recognize ...
2140
2141 case *string:
2142 *v = d.d.DecodeString()
2143 case *bool:
2144 *v = d.d.DecodeBool()
2145 case *int:
2146 *v = int(d.d.DecodeInt(intBitsize))
2147 case *int8:
2148 *v = int8(d.d.DecodeInt(8))
2149 case *int16:
2150 *v = int16(d.d.DecodeInt(16))
2151 case *int32:
2152 *v = int32(d.d.DecodeInt(32))
2153 case *int64:
2154 *v = d.d.DecodeInt(64)
2155 case *uint:
2156 *v = uint(d.d.DecodeUint(uintBitsize))
2157 case *uint8:
2158 *v = uint8(d.d.DecodeUint(8))
2159 case *uint16:
2160 *v = uint16(d.d.DecodeUint(16))
2161 case *uint32:
2162 *v = uint32(d.d.DecodeUint(32))
2163 case *uint64:
2164 *v = d.d.DecodeUint(64)
2165 case *float32:
2166 *v = float32(d.d.DecodeFloat(true))
2167 case *float64:
2168 *v = d.d.DecodeFloat(false)
2169 case *[]uint8:
2170 *v = d.d.DecodeBytes(*v, false)
2171
2172 case *Raw:
2173 *v = d.rawBytes()
2174
2175 case *interface{}:
2176 d.decodeValue(reflect.ValueOf(iv).Elem(), nil, false, true) // TODO: consider recognize here
2177 // d.decodeValueNotNil(reflect.ValueOf(iv).Elem())
2178
2179 default:
2180 if !fastpathDecodeTypeSwitch(iv, d) {
2181 v := reflect.ValueOf(iv)
2182 v = d.ensureDecodeable(v)
2183 d.decodeValue(v, nil, false, false)
2184 // d.decodeValueFallback(v)
2185 }
2186 }
2187 }
2188
2189 func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn, tryRecognized, chkAll bool) {
2190 // If stream is not containing a nil value, then we can deref to the base
2191 // non-pointer value, and decode into that.
2192 var rvp reflect.Value
2193 var rvpValid bool
2194 if rv.Kind() == reflect.Ptr {
2195 rvpValid = true
2196 for {
2197 if rv.IsNil() {
2198 rv.Set(reflect.New(rv.Type().Elem()))
2199 }
2200 rvp = rv
2201 rv = rv.Elem()
2202 if rv.Kind() != reflect.Ptr {
2203 break
2204 }
2205 }
2206 }
2207
2208 if useLookupRecognizedTypes && tryRecognized && isRecognizedRtid(rv2rtid(rv)) {
2209 if rvpValid {
2210 d.decode(rv2i(rvp))
2211 return
2212 } else if rv.CanAddr() {
2213 d.decode(rv2i(rv.Addr()))
2214 return
2215 }
2216 }
2217
2218 if fn == nil {
2219 // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer
2220 fn = d.cf.get(rv.Type(), chkAll, true) // chkAll, chkAll)
2221 }
2222 if fn.i.addr {
2223 if rvpValid {
2224 fn.fd(d, &fn.i, rvp)
2225 } else if rv.CanAddr() {
2226 fn.fd(d, &fn.i, rv.Addr())
2227 } else {
2228 fn.fd(d, &fn.i, rv)
2229 }
2230 } else {
2231 fn.fd(d, &fn.i, rv)
2232 }
2233 // return rv
2234 }
2235
2236 func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
2237 // NOTE: rvkencname may be a stringView, so don't pass it to another function.
2238 if d.h.ErrorIfNoField {
2239 if index >= 0 {
2240 d.errorf("no matching struct field found when decoding stream array at index %v", index)
2241 return
2242 } else if rvkencname != "" {
2243 d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
2244 return
2245 }
2246 }
2247 d.swallow()
2248 }
2249
2250 func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
2251 if d.h.ErrorIfNoArrayExpand {
2252 d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
2253 }
2254 }
2255
2256 func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) {
2257 switch rv.Kind() {
2258 case reflect.Array:
2259 return rv, true
2260 case reflect.Ptr:
2261 if !rv.IsNil() {
2262 return rv.Elem(), true
2263 }
2264 case reflect.Slice, reflect.Chan, reflect.Map:
2265 if !rv.IsNil() {
2266 return rv, true
2267 }
2268 }
2269 return
2270 }
2271
2272 func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) {
2273 // decode can take any reflect.Value that is a inherently addressable i.e.
2274 // - array
2275 // - non-nil chan (we will SEND to it)
2276 // - non-nil slice (we will set its elements)
2277 // - non-nil map (we will put into it)
2278 // - non-nil pointer (we can "update" it)
2279 rv2, canDecode := isDecodeable(rv)
2280 if canDecode {
2281 return
2282 }
2283 if !rv.IsValid() {
2284 d.error(cannotDecodeIntoNilErr)
2285 return
2286 }
2287 if !rv.CanInterface() {
2288 d.errorf("cannot decode into a value without an interface: %v", rv)
2289 return
2290 }
2291 rvi := rv2i(rv)
2292 d.errorf("cannot decode into value of kind: %v, type: %T, %v", rv.Kind(), rvi, rvi)
2293 return
2294 }
2295
2296 // func (d *Decoder) chkPtrValue(rv reflect.Value) {
2297 // // We can only decode into a non-nil pointer
2298 // if rv.Kind() == reflect.Ptr && !rv.IsNil() {
2299 // return
2300 // }
2301 // d.errNotValidPtrValue(rv)
2302 // }
2303
2304 // func (d *Decoder) errNotValidPtrValue(rv reflect.Value) {
2305 // if !rv.IsValid() {
2306 // d.error(cannotDecodeIntoNilErr)
2307 // return
2308 // }
2309 // if !rv.CanInterface() {
2310 // d.errorf("cannot decode into a value without an interface: %v", rv)
2311 // return
2312 // }
2313 // rvi := rv2i(rv)
2314 // d.errorf("cannot decode into non-pointer or nil pointer. Got: %v, %T, %v", rv.Kind(), rvi, rvi)
2315 // }
2316
2317 func (d *Decoder) error(err error) {
2318 panic(err)
2319 }
2320
2321 func (d *Decoder) errorf(format string, params ...interface{}) {
2322 params2 := make([]interface{}, len(params)+1)
2323 params2[0] = d.r.numread()
2324 copy(params2[1:], params)
2325 err := fmt.Errorf("[pos %d]: "+format, params2...)
2326 panic(err)
2327 }
2328
2329 // Possibly get an interned version of a string
2330 //
2331 // This should mostly be used for map keys, where the key type is string.
2332 // This is because keys of a map/struct are typically reused across many objects.
2333 func (d *Decoder) string(v []byte) (s string) {
2334 if d.is == nil {
2335 return string(v) // don't return stringView, as we need a real string here.
2336 }
2337 s, ok := d.is[string(v)] // no allocation here, per go implementation
2338 if !ok {
2339 s = string(v) // new allocation here
2340 d.is[s] = s
2341 }
2342 return s
2343 }
2344
2345 // nextValueBytes returns the next value in the stream as a set of bytes.
2346 func (d *Decoder) nextValueBytes() (bs []byte) {
2347 d.d.uncacheRead()
2348 d.r.track()
2349 d.swallow()
2350 bs = d.r.stopTrack()
2351 return
2352 }
2353
2354 func (d *Decoder) rawBytes() []byte {
2355 // ensure that this is not a view into the bytes
2356 // i.e. make new copy always.
2357 bs := d.nextValueBytes()
2358 bs2 := make([]byte, len(bs))
2359 copy(bs2, bs)
2360 return bs2
2361 }
2362
2363 // --------------------------------------------------
2364
2365 // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
2366 // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
2367 type decSliceHelper struct {
2368 d *Decoder
2369 // ct valueType
2370 array bool
2371 }
2372
2373 func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
2374 dd := d.d
2375 ctyp := dd.ContainerType()
2376 if ctyp == valueTypeArray {
2377 x.array = true
2378 clen = dd.ReadArrayStart()
2379 } else if ctyp == valueTypeMap {
2380 clen = dd.ReadMapStart() * 2
2381 } else {
2382 d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp)
2383 }
2384 // x.ct = ctyp
2385 x.d = d
2386 return
2387 }
2388
2389 func (x decSliceHelper) End() {
2390 if x.array {
2391 x.d.d.ReadArrayEnd()
2392 } else {
2393 x.d.d.ReadMapEnd()
2394 }
2395 }
2396
2397 func (x decSliceHelper) ElemContainerState(index int) {
2398 if x.array {
2399 x.d.d.ReadArrayElem()
2400 } else {
2401 if index%2 == 0 {
2402 x.d.d.ReadMapElemKey()
2403 } else {
2404 x.d.d.ReadMapElemValue()
2405 }
2406 }
2407 }
2408
2409 func decByteSlice(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) {
2410 if clen == 0 {
2411 return zeroByteSlice
2412 }
2413 if len(bs) == clen {
2414 bsOut = bs
2415 r.readb(bsOut)
2416 } else if cap(bs) >= clen {
2417 bsOut = bs[:clen]
2418 r.readb(bsOut)
2419 } else {
2420 // bsOut = make([]byte, clen)
2421 len2 := decInferLen(clen, maxInitLen, 1)
2422 bsOut = make([]byte, len2)
2423 r.readb(bsOut)
2424 for len2 < clen {
2425 len3 := decInferLen(clen-len2, maxInitLen, 1)
2426 bs3 := bsOut
2427 bsOut = make([]byte, len2+len3)
2428 copy(bsOut, bs3)
2429 r.readb(bsOut[len2:])
2430 len2 += len3
2431 }
2432 }
2433 return
2434 }
2435
2436 func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
2437 if xlen := len(in); xlen > 0 {
2438 if isBytesReader || xlen <= scratchByteArrayLen {
2439 if cap(dest) >= xlen {
2440 out = dest[:xlen]
2441 } else {
2442 out = make([]byte, xlen)
2443 }
2444 copy(out, in)
2445 return
2446 }
2447 }
2448 return in
2449 }
2450
2451 // decInferLen will infer a sensible length, given the following:
2452 // - clen: length wanted.
2453 // - maxlen: max length to be returned.
2454 // if <= 0, it is unset, and we infer it based on the unit size
2455 // - unit: number of bytes for each element of the collection
2456 func decInferLen(clen, maxlen, unit int) (rvlen int) {
2457 // handle when maxlen is not set i.e. <= 0
2458 if clen <= 0 {
2459 return
2460 }
2461 if maxlen <= 0 {
2462 // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
2463 // maxlen = 256 * 1024 / unit
2464 // if maxlen < (4 * 1024) {
2465 // maxlen = 4 * 1024
2466 // }
2467 if unit < (256 / 4) {
2468 maxlen = 256 * 1024 / unit
2469 } else {
2470 maxlen = 4 * 1024
2471 }
2472 }
2473 if clen > maxlen {
2474 rvlen = maxlen
2475 } else {
2476 rvlen = clen
2477 }
2478 return
2479 }
2480
2481 func decExpandSliceRV(s reflect.Value, st reflect.Type, stElemSize, num, slen, scap int) (
2482 s2 reflect.Value, scap2 int, changed bool) {
2483 l1 := slen + num // new slice length
2484 if l1 < slen {
2485 panic("expandSlice: slice overflow")
2486 }
2487 if l1 <= scap {
2488 if s.CanSet() {
2489 s.SetLen(l1)
2490 } else {
2491 s2 = s.Slice(0, l1)
2492 scap2 = scap
2493 changed = true
2494 }
2495 return
2496 }
2497 scap2 = growCap(scap, stElemSize, num)
2498 s2 = reflect.MakeSlice(st, l1, scap2)
2499 changed = true
2500 reflect.Copy(s2, s)
2501 return
2502 }
2503
2504 func decReadFull(r io.Reader, bs []byte) (n int, err error) {
2505 var nn int
2506 for n < len(bs) && err == nil {
2507 nn, err = r.Read(bs[n:])
2508 if nn > 0 {
2509 if err == io.EOF {
2510 // leave EOF for next time
2511 err = nil
2512 }
2513 n += nn
2514 }
2515 }
2516
2517 // do not do this - it serves no purpose
2518 // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
2519 return
2520 }