Debian Codegraph @

codec/decode.go

raw symbols SCIP
1 // Copyright (c) 2012-2020 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 "io"
10 "math"
11 "reflect"
12 "strconv"
13 "time"
14 )
15
16 const msgBadDesc = "unrecognized descriptor byte"
17
18 const (
19 decDefMaxDepth = 1024 // maximum depth
20 decDefChanCap = 64 // should be large, as cap cannot be expanded
21 decScratchByteArrayLen = (8 + 2 + 2) * 8 // around cacheLineSize ie ~64, depending on Decoder size
22
23 // MARKER: massage decScratchByteArrayLen to ensure xxxDecDriver structs fit within cacheLine*N
24
25 // decFailNonEmptyIntf configures whether we error
26 // when decoding naked into a non-empty interface.
27 //
28 // Typically, we cannot decode non-nil stream value into
29 // nil interface with methods (e.g. io.Reader).
30 // However, in some scenarios, this should be allowed:
31 // - MapType
32 // - SliceType
33 // - Extensions
34 //
35 // Consequently, we should relax this. Put it behind a const flag for now.
36 decFailNonEmptyIntf = false
37
38 // decUseTransient says that we should not use the transient optimization.
39 //
40 // There's potential for GC corruption or memory overwrites if transient isn't
41 // used carefully, so this flag helps turn it off quickly if needed.
42 //
43 // Use it everywhere needed so we can completely remove unused code blocks.
44 decUseTransient = true
45 )
46
47 var (
48 errNeedMapOrArrayDecodeToStruct = errors.New("only encoded map or array can decode into struct")
49 errCannotDecodeIntoNil = errors.New("cannot decode into nil")
50
51 errExpandSliceCannotChange = errors.New("expand slice: cannot change")
52
53 errDecoderNotInitialized = errors.New("Decoder not initialized")
54
55 errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read")
56 errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read")
57 errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown")
58 errMaxDepthExceeded = errors.New("maximum decoding depth exceeded")
59 )
60
61 // decByteState tracks where the []byte returned by the last call
62 // to DecodeBytes or DecodeStringAsByte came from
63 type decByteState uint8
64
65 const (
66 decByteStateNone decByteState = iota
67 decByteStateZerocopy // view into []byte that we are decoding from
68 decByteStateReuseBuf // view into transient buffer used internally by decDriver
69 // decByteStateNewAlloc
70 )
71
72 type decNotDecodeableReason uint8
73
74 const (
75 decNotDecodeableReasonUnknown decNotDecodeableReason = iota
76 decNotDecodeableReasonBadKind
77 decNotDecodeableReasonNonAddrValue
78 decNotDecodeableReasonNilReference
79 )
80
81 type decDriver interface {
82 // this will check if the next token is a break.
83 CheckBreak() bool
84
85 // TryNil tries to decode as nil.
86 // If a nil is in the stream, it consumes it and returns true.
87 //
88 // Note: if TryNil returns true, that must be handled.
89 TryNil() bool
90
91 // ContainerType returns one of: Bytes, String, Nil, Slice or Map.
92 //
93 // Return unSet if not known.
94 //
95 // Note: Implementations MUST fully consume sentinel container types, specifically Nil.
96 ContainerType() (vt valueType)
97
98 // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt.
99 // For maps and arrays, it will not do the decoding in-band, but will signal
100 // the decoder, so that is done later, by setting the fauxUnion.valueType field.
101 //
102 // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
103 // for extensions, DecodeNaked must read the tag and the []byte if it exists.
104 // if the []byte is not read, then kInterfaceNaked will treat it as a Handle
105 // that stores the subsequent value in-band, and complete reading the RawExt.
106 //
107 // extensions should also use readx to decode them, for efficiency.
108 // kInterface will extract the detached byte slice if it has to pass it outside its realm.
109 DecodeNaked()
110
111 DecodeInt64() (i int64)
112 DecodeUint64() (ui uint64)
113
114 DecodeFloat64() (f float64)
115 DecodeBool() (b bool)
116
117 // DecodeStringAsBytes returns the bytes representing a string.
118 // It will return a view into scratch buffer or input []byte (if applicable).
119 //
120 // Note: This can also decode symbols, if supported.
121 //
122 // Users should consume it right away and not store it for later use.
123 DecodeStringAsBytes() (v []byte)
124
125 // DecodeBytes returns the bytes representing a binary value.
126 // It will return a view into scratch buffer or input []byte (if applicable).
127 //
128 // All implementations must honor the contract below:
129 // if ZeroCopy and applicable, return a view into input []byte we are decoding from
130 // else if in == nil, return a view into scratch buffer
131 // else append decoded value to in[:0] and return that
132 // (this can be simulated by passing []byte{} as in parameter)
133 //
134 // Implementations must also update Decoder.decByteState on each call to
135 // DecodeBytes or DecodeStringAsBytes. Some callers may check that and work appropriately.
136 //
137 // Note: DecodeBytes may decode past the length of the passed byte slice, up to the cap.
138 // Consequently, it is ok to pass a zero-len slice to DecodeBytes, as the returned
139 // byte slice will have the appropriate length.
140 DecodeBytes(in []byte) (out []byte)
141 // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
142
143 // DecodeExt will decode into a *RawExt or into an extension.
144 DecodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext)
145 // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
146
147 DecodeTime() (t time.Time)
148
149 // ReadArrayStart will return the length of the array.
150 // If the format doesn't prefix the length, it returns containerLenUnknown.
151 // If the expected array was a nil in the stream, it returns containerLenNil.
152 ReadArrayStart() int
153 ReadArrayEnd()
154
155 // ReadMapStart will return the length of the array.
156 // If the format doesn't prefix the length, it returns containerLenUnknown.
157 // If the expected array was a nil in the stream, it returns containerLenNil.
158 ReadMapStart() int
159 ReadMapEnd()
160
161 reset()
162
163 // atEndOfDecode()
164
165 // nextValueBytes will return the bytes representing the next value in the stream.
166 //
167 // if start is nil, then treat it as a request to discard the next set of bytes,
168 // and the return response does not matter.
169 // Typically, this means that the returned []byte is nil/empty/undefined.
170 //
171 // Optimize for decoding from a []byte, where the nextValueBytes will just be a sub-slice
172 // of the input slice. Callers that need to use this to not be a view into the input bytes
173 // should handle it appropriately.
174 nextValueBytes(start []byte) []byte
175
176 // descBd will describe the token descriptor that signifies what type was decoded
177 descBd() string
178
179 decoder() *Decoder
180
181 driverStateManager
182 decNegintPosintFloatNumber
183 }
184
185 type decDriverContainerTracker interface {
186 ReadArrayElem()
187 ReadMapElemKey()
188 ReadMapElemValue()
189 }
190
191 type decNegintPosintFloatNumber interface {
192 decInteger() (ui uint64, neg, ok bool)
193 decFloat() (f float64, ok bool)
194 }
195
196 type decDriverNoopNumberHelper struct{}
197
198 func (x decDriverNoopNumberHelper) decInteger() (ui uint64, neg, ok bool) {
199 panic("decInteger unsupported")
200 }
201 func (x decDriverNoopNumberHelper) decFloat() (f float64, ok bool) { panic("decFloat unsupported") }
202
203 type decDriverNoopContainerReader struct{}
204
205 func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { panic("ReadArrayStart unsupported") }
206 func (x decDriverNoopContainerReader) ReadArrayEnd() {}
207 func (x decDriverNoopContainerReader) ReadMapStart() (v int) { panic("ReadMapStart unsupported") }
208 func (x decDriverNoopContainerReader) ReadMapEnd() {}
209 func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return }
210
211 // DecodeOptions captures configuration options during decode.
212 type DecodeOptions struct {
213 // MapType specifies type to use during schema-less decoding of a map in the stream.
214 // If nil (unset), we default to map[string]interface{} iff json handle and MapKeyAsString=true,
215 // else map[interface{}]interface{}.
216 MapType reflect.Type
217
218 // SliceType specifies type to use during schema-less decoding of an array in the stream.
219 // If nil (unset), we default to []interface{} for all formats.
220 SliceType reflect.Type
221
222 // MaxInitLen defines the maxinum initial length that we "make" a collection
223 // (string, slice, map, chan). If 0 or negative, we default to a sensible value
224 // based on the size of an element in the collection.
225 //
226 // For example, when decoding, a stream may say that it has 2^64 elements.
227 // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash.
228 // Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
229 MaxInitLen int
230
231 // ReaderBufferSize is the size of the buffer used when reading.
232 //
233 // if > 0, we use a smart buffer internally for performance purposes.
234 ReaderBufferSize int
235
236 // MaxDepth defines the maximum depth when decoding nested
237 // maps and slices. If 0 or negative, we default to a suitably large number (currently 1024).
238 MaxDepth int16
239
240 // If ErrorIfNoField, return an error when decoding a map
241 // from a codec stream into a struct, and no matching struct field is found.
242 ErrorIfNoField bool
243
244 // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
245 // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
246 // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
247 ErrorIfNoArrayExpand bool
248
249 // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
250 SignedInteger bool
251
252 // MapValueReset controls how we decode into a map value.
253 //
254 // By default, we MAY retrieve the mapping for a key, and then decode into that.
255 // However, especially with big maps, that retrieval may be expensive and unnecessary
256 // if the stream already contains all that is necessary to recreate the value.
257 //
258 // If true, we will never retrieve the previous mapping,
259 // but rather decode into a new value and set that in the map.
260 //
261 // If false, we will retrieve the previous mapping if necessary e.g.
262 // the previous mapping is a pointer, or is a struct or array with pre-set state,
263 // or is an interface.
264 MapValueReset bool
265
266 // SliceElementReset: on decoding a slice, reset the element to a zero value first.
267 //
268 // concern: if the slice already contained some garbage, we will decode into that garbage.
269 SliceElementReset bool
270
271 // InterfaceReset controls how we decode into an interface.
272 //
273 // By default, when we see a field that is an interface{...},
274 // or a map with interface{...} value, we will attempt decoding into the
275 // "contained" value.
276 //
277 // However, this prevents us from reading a string into an interface{}
278 // that formerly contained a number.
279 //
280 // If true, we will decode into a new "blank" value, and set that in the interface.
281 // If false, we will decode into whatever is contained in the interface.
282 InterfaceReset bool
283
284 // InternString controls interning of strings during decoding.
285 //
286 // Some handles, e.g. json, typically will read map keys as strings.
287 // If the set of keys are finite, it may help reduce allocation to
288 // look them up from a map (than to allocate them afresh).
289 //
290 // Note: Handles will be smart when using the intern functionality.
291 // Every string should not be interned.
292 // An excellent use-case for interning is struct field names,
293 // or map keys where key type is string.
294 InternString bool
295
296 // PreferArrayOverSlice controls whether to decode to an array or a slice.
297 //
298 // This only impacts decoding into a nil interface{}.
299 //
300 // Consequently, it has no effect on codecgen.
301 //
302 // *Note*: This only applies if using go1.5 and above,
303 // as it requires reflect.ArrayOf support which was absent before go1.5.
304 PreferArrayOverSlice bool
305
306 // DeleteOnNilMapValue controls how to decode a nil value in the stream.
307 //
308 // If true, we will delete the mapping of the key.
309 // Else, just set the mapping to the zero value of the type.
310 //
311 // Deprecated: This does NOTHING and is left behind for compiling compatibility.
312 // This change is necessitated because 'nil' in a stream now consistently
313 // means the zero value (ie reset the value to its zero state).
314 DeleteOnNilMapValue bool
315
316 // RawToString controls how raw bytes in a stream are decoded into a nil interface{}.
317 // By default, they are decoded as []byte, but can be decoded as string (if configured).
318 RawToString bool
319
320 // ZeroCopy controls whether decoded values of []byte or string type
321 // point into the input []byte parameter passed to a NewDecoderBytes/ResetBytes(...) call.
322 //
323 // To illustrate, if ZeroCopy and decoding from a []byte (not io.Writer),
324 // then a []byte or string in the output result may just be a slice of (point into)
325 // the input bytes.
326 //
327 // This optimization prevents unnecessary copying.
328 //
329 // However, it is made optional, as the caller MUST ensure that the input parameter []byte is
330 // not modified after the Decode() happens, as any changes are mirrored in the decoded result.
331 ZeroCopy bool
332
333 // PreferPointerForStructOrArray controls whether a struct or array
334 // is stored in a nil interface{}, or a pointer to it.
335 //
336 // This mostly impacts when we decode registered extensions.
337 PreferPointerForStructOrArray bool
338
339 // ValidateUnicode controls will cause decoding to fail if an expected unicode
340 // string is well-formed but include invalid codepoints.
341 //
342 // This could have a performance impact.
343 ValidateUnicode bool
344 }
345
346 // ----------------------------------------
347
348 func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) {
349 d.d.DecodeExt(rv2i(rv), f.ti.rt, 0, nil)
350 }
351
352 func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) {
353 d.d.DecodeExt(rv2i(rv), f.ti.rt, f.xfTag, f.xfFn)
354 }
355
356 func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) {
357 rv2i(rv).(Selfer).CodecDecodeSelf(d)
358 }
359
360 func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) {
361 bm := rv2i(rv).(encoding.BinaryUnmarshaler)
362 xbs := d.d.DecodeBytes(nil)
363 fnerr := bm.UnmarshalBinary(xbs)
364 d.onerror(fnerr)
365 }
366
367 func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) {
368 tm := rv2i(rv).(encoding.TextUnmarshaler)
369 fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes())
370 d.onerror(fnerr)
371 }
372
373 func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) {
374 d.jsonUnmarshalV(rv2i(rv).(jsonUnmarshaler))
375 }
376
377 func (d *Decoder) jsonUnmarshalV(tm jsonUnmarshaler) {
378 // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
379 var bs0 = []byte{}
380 if !d.bytes {
381 bs0 = d.blist.get(256)
382 }
383 bs := d.d.nextValueBytes(bs0)
384 fnerr := tm.UnmarshalJSON(bs)
385 if !d.bytes {
386 d.blist.put(bs)
387 if !byteSliceSameData(bs0, bs) {
388 d.blist.put(bs0)
389 }
390 }
391 d.onerror(fnerr)
392 }
393
394 func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) {
395 d.errorf("no decoding function defined for kind %v", rv.Kind())
396 }
397
398 func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) {
399 rvSetBytes(rv, d.rawBytes())
400 }
401
402 func (d *Decoder) kString(f *codecFnInfo, rv reflect.Value) {
403 rvSetString(rv, d.stringZC(d.d.DecodeStringAsBytes()))
404 }
405
406 func (d *Decoder) kBool(f *codecFnInfo, rv reflect.Value) {
407 rvSetBool(rv, d.d.DecodeBool())
408 }
409
410 func (d *Decoder) kTime(f *codecFnInfo, rv reflect.Value) {
411 rvSetTime(rv, d.d.DecodeTime())
412 }
413
414 func (d *Decoder) kFloat32(f *codecFnInfo, rv reflect.Value) {
415 rvSetFloat32(rv, d.decodeFloat32())
416 }
417
418 func (d *Decoder) kFloat64(f *codecFnInfo, rv reflect.Value) {
419 rvSetFloat64(rv, d.d.DecodeFloat64())
420 }
421
422 func (d *Decoder) kComplex64(f *codecFnInfo, rv reflect.Value) {
423 rvSetComplex64(rv, complex(d.decodeFloat32(), 0))
424 }
425
426 func (d *Decoder) kComplex128(f *codecFnInfo, rv reflect.Value) {
427 rvSetComplex128(rv, complex(d.d.DecodeFloat64(), 0))
428 }
429
430 func (d *Decoder) kInt(f *codecFnInfo, rv reflect.Value) {
431 rvSetInt(rv, int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)))
432 }
433
434 func (d *Decoder) kInt8(f *codecFnInfo, rv reflect.Value) {
435 rvSetInt8(rv, int8(chkOvf.IntV(d.d.DecodeInt64(), 8)))
436 }
437
438 func (d *Decoder) kInt16(f *codecFnInfo, rv reflect.Value) {
439 rvSetInt16(rv, int16(chkOvf.IntV(d.d.DecodeInt64(), 16)))
440 }
441
442 func (d *Decoder) kInt32(f *codecFnInfo, rv reflect.Value) {
443 rvSetInt32(rv, int32(chkOvf.IntV(d.d.DecodeInt64(), 32)))
444 }
445
446 func (d *Decoder) kInt64(f *codecFnInfo, rv reflect.Value) {
447 rvSetInt64(rv, d.d.DecodeInt64())
448 }
449
450 func (d *Decoder) kUint(f *codecFnInfo, rv reflect.Value) {
451 rvSetUint(rv, uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)))
452 }
453
454 func (d *Decoder) kUintptr(f *codecFnInfo, rv reflect.Value) {
455 rvSetUintptr(rv, uintptr(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)))
456 }
457
458 func (d *Decoder) kUint8(f *codecFnInfo, rv reflect.Value) {
459 rvSetUint8(rv, uint8(chkOvf.UintV(d.d.DecodeUint64(), 8)))
460 }
461
462 func (d *Decoder) kUint16(f *codecFnInfo, rv reflect.Value) {
463 rvSetUint16(rv, uint16(chkOvf.UintV(d.d.DecodeUint64(), 16)))
464 }
465
466 func (d *Decoder) kUint32(f *codecFnInfo, rv reflect.Value) {
467 rvSetUint32(rv, uint32(chkOvf.UintV(d.d.DecodeUint64(), 32)))
468 }
469
470 func (d *Decoder) kUint64(f *codecFnInfo, rv reflect.Value) {
471 rvSetUint64(rv, d.d.DecodeUint64())
472 }
473
474 func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) {
475 // nil interface:
476 // use some hieristics to decode it appropriately
477 // based on the detected next value in the stream.
478 n := d.naked()
479 d.d.DecodeNaked()
480
481 // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader).
482 // Howver, it is possible that the user has ways to pass in a type for a given interface
483 // - MapType
484 // - SliceType
485 // - Extensions
486 //
487 // Consequently, we should relax this. Put it behind a const flag for now.
488 if decFailNonEmptyIntf && f.ti.numMeth > 0 {
489 d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth)
490 }
491 switch n.v {
492 case valueTypeMap:
493 mtid := d.mtid
494 if mtid == 0 {
495 if d.jsms { // if json, default to a map type with string keys
496 mtid = mapStrIntfTypId // for json performance
497 } else {
498 mtid = mapIntfIntfTypId
499 }
500 }
501 if mtid == mapStrIntfTypId {
502 var v2 map[string]interface{}
503 d.decode(&v2)
504 rvn = rv4iptr(&v2).Elem()
505 } else if mtid == mapIntfIntfTypId {
506 var v2 map[interface{}]interface{}
507 d.decode(&v2)
508 rvn = rv4iptr(&v2).Elem()
509 } else if d.mtr {
510 rvn = reflect.New(d.h.MapType)
511 d.decode(rv2i(rvn))
512 rvn = rvn.Elem()
513 } else {
514 rvn = rvZeroAddrK(d.h.MapType, reflect.Map)
515 d.decodeValue(rvn, nil)
516 }
517 case valueTypeArray:
518 if d.stid == 0 || d.stid == intfSliceTypId {
519 var v2 []interface{}
520 d.decode(&v2)
521 rvn = rv4iptr(&v2).Elem()
522 } else if d.str {
523 rvn = reflect.New(d.h.SliceType)
524 d.decode(rv2i(rvn))
525 rvn = rvn.Elem()
526 } else {
527 rvn = rvZeroAddrK(d.h.SliceType, reflect.Slice)
528 d.decodeValue(rvn, nil)
529 }
530 if reflectArrayOfSupported && d.h.PreferArrayOverSlice {
531 rvn = rvGetArray4Slice(rvn)
532 }
533 case valueTypeExt:
534 tag, bytes := n.u, n.l // calling decode below might taint the values
535 bfn := d.h.getExtForTag(tag)
536 var re = RawExt{Tag: tag}
537 if bytes == nil {
538 // it is one of the InterfaceExt ones: json and cbor.
539 // most likely cbor, as json decoding never reveals valueTypeExt (no tagging support)
540 if bfn == nil {
541 d.decode(&re.Value)
542 rvn = rv4iptr(&re).Elem()
543 } else {
544 if bfn.ext == SelfExt {
545 rvn = rvZeroAddrK(bfn.rt, bfn.rt.Kind())
546 d.decodeValue(rvn, d.h.fnNoExt(bfn.rt))
547 } else {
548 rvn = reflect.New(bfn.rt)
549 d.interfaceExtConvertAndDecode(rv2i(rvn), bfn.ext)
550 rvn = rvn.Elem()
551 }
552 }
553 } else {
554 // one of the BytesExt ones: binc, msgpack, simple
555 if bfn == nil {
556 re.setData(bytes, false)
557 rvn = rv4iptr(&re).Elem()
558 } else {
559 rvn = reflect.New(bfn.rt)
560 if bfn.ext == SelfExt {
561 d.sideDecode(rv2i(rvn), bfn.rt, bytes)
562 } else {
563 bfn.ext.ReadExt(rv2i(rvn), bytes)
564 }
565 rvn = rvn.Elem()
566 }
567 }
568 // if struct/array, directly store pointer into the interface
569 if d.h.PreferPointerForStructOrArray && rvn.CanAddr() {
570 if rk := rvn.Kind(); rk == reflect.Array || rk == reflect.Struct {
571 rvn = rvn.Addr()
572 }
573 }
574 case valueTypeNil:
575 // rvn = reflect.Zero(f.ti.rt)
576 // no-op
577 case valueTypeInt:
578 rvn = n.ri()
579 case valueTypeUint:
580 rvn = n.ru()
581 case valueTypeFloat:
582 rvn = n.rf()
583 case valueTypeBool:
584 rvn = n.rb()
585 case valueTypeString, valueTypeSymbol:
586 rvn = n.rs()
587 case valueTypeBytes:
588 rvn = n.rl()
589 case valueTypeTime:
590 rvn = n.rt()
591 default:
592 halt.errorf("kInterfaceNaked: unexpected valueType: %d", n.v)
593 }
594 return
595 }
596
597 func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
598 // Note: A consequence of how kInterface works, is that
599 // if an interface already contains something, we try
600 // to decode into what was there before.
601 // We do not replace with a generic value (as got from decodeNaked).
602 //
603 // every interface passed here MUST be settable.
604 //
605 // ensure you call rvSetIntf(...) before returning.
606
607 isnilrv := rvIsNil(rv)
608
609 var rvn reflect.Value
610
611 if d.h.InterfaceReset {
612 // check if mapping to a type: if so, initialize it and move on
613 rvn = d.h.intf2impl(f.ti.rtid)
614 if !rvn.IsValid() {
615 rvn = d.kInterfaceNaked(f)
616 if rvn.IsValid() {
617 rvSetIntf(rv, rvn)
618 } else if !isnilrv {
619 decSetNonNilRV2Zero4Intf(rv)
620 }
621 return
622 }
623 } else if isnilrv {
624 // check if mapping to a type: if so, initialize it and move on
625 rvn = d.h.intf2impl(f.ti.rtid)
626 if !rvn.IsValid() {
627 rvn = d.kInterfaceNaked(f)
628 if rvn.IsValid() {
629 rvSetIntf(rv, rvn)
630 }
631 return
632 }
633 } else {
634 // now we have a non-nil interface value, meaning it contains a type
635 rvn = rv.Elem()
636 }
637
638 // rvn is now a non-interface type
639
640 canDecode, _ := isDecodeable(rvn)
641
642 // Note: interface{} is settable, but underlying type may not be.
643 // Consequently, we MAY have to allocate a value (containing the underlying value),
644 // decode into it, and reset the interface to that new value.
645
646 if !canDecode {
647 rvn2 := d.oneShotAddrRV(rvType(rvn), rvn.Kind())
648 rvSetDirect(rvn2, rvn)
649 rvn = rvn2
650 }
651
652 d.decodeValue(rvn, nil)
653 rvSetIntf(rv, rvn)
654 }
655
656 func decStructFieldKeyNotString(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) {
657 if keyType == valueTypeInt {
658 rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10)
659 } else if keyType == valueTypeUint {
660 rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10)
661 } else if keyType == valueTypeFloat {
662 rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64)
663 } else {
664 halt.errorf("invalid struct key type: %v", keyType)
665 }
666 return
667 }
668
669 func (d *Decoder) kStructField(si *structFieldInfo, rv reflect.Value) {
670 if d.d.TryNil() {
671 if rv = si.path.field(rv); rv.IsValid() {
672 decSetNonNilRV2Zero(rv)
673 }
674 return
675 }
676 d.decodeValueNoCheckNil(si.path.fieldAlloc(rv), nil)
677 }
678
679 func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
680 ctyp := d.d.ContainerType()
681 ti := f.ti
682 var mf MissingFielder
683 if ti.flagMissingFielder {
684 mf = rv2i(rv).(MissingFielder)
685 } else if ti.flagMissingFielderPtr {
686 mf = rv2i(rvAddr(rv, ti.ptr)).(MissingFielder)
687 }
688 if ctyp == valueTypeMap {
689 containerLen := d.mapStart(d.d.ReadMapStart())
690 if containerLen == 0 {
691 d.mapEnd()
692 return
693 }
694 hasLen := containerLen >= 0
695 var name2 []byte
696 if mf != nil {
697 var namearr2 [16]byte
698 name2 = namearr2[:0]
699 }
700 var rvkencname []byte
701 for j := 0; d.containerNext(j, containerLen, hasLen); j++ {
702 d.mapElemKey()
703 if ti.keyType == valueTypeString {
704 rvkencname = d.d.DecodeStringAsBytes()
705 } else {
706 rvkencname = decStructFieldKeyNotString(d.d, ti.keyType, &d.b)
707 }
708 d.mapElemValue()
709 if si := ti.siForEncName(rvkencname); si != nil {
710 d.kStructField(si, rv)
711 } else if mf != nil {
712 // store rvkencname in new []byte, as it previously shares Decoder.b, which is used in decode
713 name2 = append(name2[:0], rvkencname...)
714 var f interface{}
715 d.decode(&f)
716 if !mf.CodecMissingField(name2, f) && d.h.ErrorIfNoField {
717 d.errorf("no matching struct field when decoding stream map with key: %s ", stringView(name2))
718 }
719 } else {
720 d.structFieldNotFound(-1, stringView(rvkencname))
721 }
722 }
723 d.mapEnd()
724 } else if ctyp == valueTypeArray {
725 containerLen := d.arrayStart(d.d.ReadArrayStart())
726 if containerLen == 0 {
727 d.arrayEnd()
728 return
729 }
730 // Not much gain from doing it two ways for array.
731 // Arrays are not used as much for structs.
732 hasLen := containerLen >= 0
733 var checkbreak bool
734 tisfi := ti.sfi.source()
735 for j, si := range tisfi {
736 if hasLen {
737 if j == containerLen {
738 break
739 }
740 } else if d.checkBreak() {
741 checkbreak = true
742 break
743 }
744 d.arrayElem()
745 d.kStructField(si, rv)
746 }
747 var proceed bool
748 if hasLen {
749 proceed = containerLen > len(tisfi)
750 } else {
751 proceed = !checkbreak
752 }
753 // if (hasLen && containerLen > len(tisfi)) || (!hasLen && !checkbreak) {
754 if proceed {
755 // read remaining values and throw away
756 for j := len(tisfi); ; j++ {
757 if !d.containerNext(j, containerLen, hasLen) {
758 break
759 }
760 d.arrayElem()
761 d.structFieldNotFound(j, "")
762 }
763 }
764 d.arrayEnd()
765 } else {
766 d.onerror(errNeedMapOrArrayDecodeToStruct)
767 }
768 }
769
770 func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
771 // A slice can be set from a map or array in stream.
772 // This way, the order can be kept (as order is lost with map).
773
774 // Note: rv is a slice type here - guaranteed
775
776 ti := f.ti
777 rvCanset := rv.CanSet()
778
779 ctyp := d.d.ContainerType()
780 if ctyp == valueTypeBytes || ctyp == valueTypeString {
781 // you can only decode bytes or string in the stream into a slice or array of bytes
782 if !(ti.rtid == uint8SliceTypId || ti.elemkind == uint8(reflect.Uint8)) {
783 d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
784 }
785 rvbs := rvGetBytes(rv)
786 if !rvCanset {
787 // not addressable byte slice, so do not decode into it past the length
788 rvbs = rvbs[:len(rvbs):len(rvbs)]
789 }
790 bs2 := d.decodeBytesInto(rvbs)
791 // if !(len(bs2) == len(rvbs) && byteSliceSameData(rvbs, bs2)) {
792 if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
793 if rvCanset {
794 rvSetBytes(rv, bs2)
795 } else if len(rvbs) > 0 && len(bs2) > 0 {
796 copy(rvbs, bs2)
797 }
798 }
799 return
800 }
801
802 slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - never Nil
803
804 // an array can never return a nil slice. so no need to check f.array here.
805 if containerLenS == 0 {
806 if rvCanset {
807 if rvIsNil(rv) {
808 rvSetDirect(rv, rvSliceZeroCap(ti.rt))
809 } else {
810 rvSetSliceLen(rv, 0)
811 }
812 }
813 slh.End()
814 return
815 }
816
817 rtelem0Mut := !scalarBitset.isset(ti.elemkind)
818 rtelem := ti.elem
819
820 for k := reflect.Kind(ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
821 rtelem = rtelem.Elem()
822 }
823
824 var fn *codecFn
825
826 var rvChanged bool
827
828 var rv0 = rv
829 var rv9 reflect.Value
830
831 rvlen := rvLenSlice(rv)
832 rvcap := rvCapSlice(rv)
833 hasLen := containerLenS > 0
834 if hasLen {
835 if containerLenS > rvcap {
836 oldRvlenGtZero := rvlen > 0
837 rvlen1 := decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
838 if rvlen1 == rvlen {
839 } else if rvlen1 <= rvcap {
840 if rvCanset {
841 rvlen = rvlen1
842 rvSetSliceLen(rv, rvlen)
843 }
844 } else if rvCanset { // rvlen1 > rvcap
845 rvlen = rvlen1
846 rv, rvCanset = rvMakeSlice(rv, f.ti, rvlen, rvlen)
847 rvcap = rvlen
848 rvChanged = !rvCanset
849 } else { // rvlen1 > rvcap && !canSet
850 d.errorf("cannot decode into non-settable slice")
851 }
852 if rvChanged && oldRvlenGtZero && rtelem0Mut {
853 rvCopySlice(rv, rv0, rtelem) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
854 }
855 } else if containerLenS != rvlen {
856 if rvCanset {
857 rvlen = containerLenS
858 rvSetSliceLen(rv, rvlen)
859 }
860 }
861 }
862
863 // consider creating new element once, and just decoding into it.
864 var elemReset = d.h.SliceElementReset
865
866 var j int
867
868 for ; d.containerNext(j, containerLenS, hasLen); j++ {
869 if j == 0 {
870 if rvIsNil(rv) { // means hasLen = false
871 if rvCanset {
872 rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
873 rv, rvCanset = rvMakeSlice(rv, f.ti, rvlen, rvlen)
874 rvcap = rvlen
875 rvChanged = !rvCanset
876 } else {
877 d.errorf("cannot decode into non-settable slice")
878 }
879 }
880 if fn == nil {
881 fn = d.h.fn(rtelem)
882 }
883 }
884 // if indefinite, etc, then expand the slice if necessary
885 if j >= rvlen {
886 slh.ElemContainerState(j)
887
888 // expand the slice up to the cap.
889 // Note that we did, so we have to reset it later.
890
891 if rvlen < rvcap {
892 rvlen = rvcap
893 if rvCanset {
894 rvSetSliceLen(rv, rvlen)
895 } else if rvChanged {
896 rv = rvSlice(rv, rvlen)
897 } else {
898 d.onerror(errExpandSliceCannotChange)
899 }
900 } else {
901 if !(rvCanset || rvChanged) {
902 d.onerror(errExpandSliceCannotChange)
903 }
904 rv, rvcap, rvCanset = rvGrowSlice(rv, f.ti, rvcap, 1)
905 rvlen = rvcap
906 rvChanged = !rvCanset
907 }
908 } else {
909 slh.ElemContainerState(j)
910 }
911 rv9 = rvSliceIndex(rv, j, f.ti)
912 if elemReset {
913 rvSetZero(rv9)
914 }
915 d.decodeValue(rv9, fn)
916 }
917 if j < rvlen {
918 if rvCanset {
919 rvSetSliceLen(rv, j)
920 } else if rvChanged {
921 rv = rvSlice(rv, j)
922 }
923 // rvlen = j
924 } else if j == 0 && rvIsNil(rv) {
925 if rvCanset {
926 rv = rvSliceZeroCap(ti.rt)
927 rvCanset = false
928 rvChanged = true
929 }
930 }
931 slh.End()
932
933 if rvChanged { // infers rvCanset=true, so it can be reset
934 rvSetDirect(rv0, rv)
935 }
936 }
937
938 func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
939 // An array can be set from a map or array in stream.
940
941 ctyp := d.d.ContainerType()
942 if handleBytesWithinKArray && (ctyp == valueTypeBytes || ctyp == valueTypeString) {
943 // you can only decode bytes or string in the stream into a slice or array of bytes
944 if f.ti.elemkind != uint8(reflect.Uint8) {
945 d.errorf("bytes/string in stream can decode into array of bytes, but not %v", f.ti.rt)
946 }
947 rvbs := rvGetArrayBytes(rv, nil)
948 bs2 := d.decodeBytesInto(rvbs)
949 if !byteSliceSameData(rvbs, bs2) && len(rvbs) > 0 && len(bs2) > 0 {
950 copy(rvbs, bs2)
951 }
952 return
953 }
954
955 slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - never Nil
956
957 // an array can never return a nil slice. so no need to check f.array here.
958 if containerLenS == 0 {
959 slh.End()
960 return
961 }
962
963 rtelem := f.ti.elem
964 for k := reflect.Kind(f.ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
965 rtelem = rtelem.Elem()
966 }
967
968 var fn *codecFn
969
970 var rv9 reflect.Value
971
972 rvlen := rv.Len() // same as cap
973 hasLen := containerLenS > 0
974 if hasLen && containerLenS > rvlen {
975 d.errorf("cannot decode into array with length: %v, less than container length: %v", rvlen, containerLenS)
976 }
977
978 // consider creating new element once, and just decoding into it.
979 var elemReset = d.h.SliceElementReset
980
981 for j := 0; d.containerNext(j, containerLenS, hasLen); j++ {
982 // note that you cannot expand the array if indefinite and we go past array length
983 if j >= rvlen {
984 slh.arrayCannotExpand(hasLen, rvlen, j, containerLenS)
985 return
986 }
987
988 slh.ElemContainerState(j)
989 rv9 = rvArrayIndex(rv, j, f.ti)
990 if elemReset {
991 rvSetZero(rv9)
992 }
993
994 if fn == nil {
995 fn = d.h.fn(rtelem)
996 }
997 d.decodeValue(rv9, fn)
998 }
999 slh.End()
1000 }
1001
1002 func (d *Decoder) kChan(f *codecFnInfo, rv reflect.Value) {
1003 // A slice can be set from a map or array in stream.
1004 // This way, the order can be kept (as order is lost with map).
1005
1006 ti := f.ti
1007 if ti.chandir&uint8(reflect.SendDir) == 0 {
1008 d.errorf("receive-only channel cannot be decoded")
1009 }
1010 ctyp := d.d.ContainerType()
1011 if ctyp == valueTypeBytes || ctyp == valueTypeString {
1012 // you can only decode bytes or string in the stream into a slice or array of bytes
1013 if !(ti.rtid == uint8SliceTypId || ti.elemkind == uint8(reflect.Uint8)) {
1014 d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
1015 }
1016 bs2 := d.d.DecodeBytes(nil)
1017 irv := rv2i(rv)
1018 ch, ok := irv.(chan<- byte)
1019 if !ok {
1020 ch = irv.(chan byte)
1021 }
1022 for _, b := range bs2 {
1023 ch <- b
1024 }
1025 return
1026 }
1027
1028 var rvCanset = rv.CanSet()
1029
1030 // only expects valueType(Array|Map - nil handled above)
1031 slh, containerLenS := d.decSliceHelperStart()
1032
1033 // an array can never return a nil slice. so no need to check f.array here.
1034 if containerLenS == 0 {
1035 if rvCanset && rvIsNil(rv) {
1036 rvSetDirect(rv, reflect.MakeChan(ti.rt, 0))
1037 }
1038 slh.End()
1039 return
1040 }
1041
1042 rtelem := ti.elem
1043 useTransient := decUseTransient && ti.elemkind != byte(reflect.Ptr) && ti.tielem.flagCanTransient
1044
1045 for k := reflect.Kind(ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
1046 rtelem = rtelem.Elem()
1047 }
1048
1049 var fn *codecFn
1050
1051 var rvChanged bool
1052 var rv0 = rv
1053 var rv9 reflect.Value
1054
1055 var rvlen int // = rv.Len()
1056 hasLen := containerLenS > 0
1057
1058 for j := 0; d.containerNext(j, containerLenS, hasLen); j++ {
1059 if j == 0 {
1060 if rvIsNil(rv) {
1061 if hasLen {
1062 rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
1063 } else {
1064 rvlen = decDefChanCap
1065 }
1066 if rvCanset {
1067 rv = reflect.MakeChan(ti.rt, rvlen)
1068 rvChanged = true
1069 } else {
1070 d.errorf("cannot decode into non-settable chan")
1071 }
1072 }
1073 if fn == nil {
1074 fn = d.h.fn(rtelem)
1075 }
1076 }
1077 slh.ElemContainerState(j)
1078 if rv9.IsValid() {
1079 rvSetZero(rv9)
1080 } else if decUseTransient && useTransient {
1081 rv9 = d.perType.TransientAddrK(ti.elem, reflect.Kind(ti.elemkind))
1082 } else {
1083 rv9 = rvZeroAddrK(ti.elem, reflect.Kind(ti.elemkind))
1084 }
1085 if !d.d.TryNil() {
1086 d.decodeValueNoCheckNil(rv9, fn)
1087 }
1088 rv.Send(rv9)
1089 }
1090 slh.End()
1091
1092 if rvChanged { // infers rvCanset=true, so it can be reset
1093 rvSetDirect(rv0, rv)
1094 }
1095
1096 }
1097
1098 func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
1099 containerLen := d.mapStart(d.d.ReadMapStart())
1100 ti := f.ti
1101 if rvIsNil(rv) {
1102 rvlen := decInferLen(containerLen, d.h.MaxInitLen, int(ti.keysize+ti.elemsize))
1103 rvSetDirect(rv, makeMapReflect(ti.rt, rvlen))
1104 }
1105
1106 if containerLen == 0 {
1107 d.mapEnd()
1108 return
1109 }
1110
1111 ktype, vtype := ti.key, ti.elem
1112 ktypeId := rt2id(ktype)
1113 vtypeKind := reflect.Kind(ti.elemkind)
1114 ktypeKind := reflect.Kind(ti.keykind)
1115 kfast := mapKeyFastKindFor(ktypeKind)
1116 visindirect := mapStoresElemIndirect(uintptr(ti.elemsize))
1117 visref := refBitset.isset(ti.elemkind)
1118
1119 vtypePtr := vtypeKind == reflect.Ptr
1120 ktypePtr := ktypeKind == reflect.Ptr
1121
1122 vTransient := decUseTransient && !vtypePtr && ti.tielem.flagCanTransient
1123 kTransient := decUseTransient && !ktypePtr && ti.tikey.flagCanTransient
1124
1125 var vtypeElem reflect.Type
1126
1127 var keyFn, valFn *codecFn
1128 var ktypeLo, vtypeLo = ktype, vtype
1129
1130 if ktypeKind == reflect.Ptr {
1131 for ktypeLo = ktype.Elem(); ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
1132 }
1133 }
1134
1135 if vtypePtr {
1136 vtypeElem = vtype.Elem()
1137 for vtypeLo = vtypeElem; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
1138 }
1139 }
1140
1141 rvkMut := !scalarBitset.isset(ti.keykind) // if ktype is immutable, then re-use the same rvk.
1142 rvvMut := !scalarBitset.isset(ti.elemkind)
1143 rvvCanNil := isnilBitset.isset(ti.elemkind)
1144
1145 // rvk: key
1146 // rvkn: if non-mutable, on each iteration of loop, set rvk to this
1147 // rvv: value
1148 // rvvn: if non-mutable, on each iteration of loop, set rvv to this
1149 // if mutable, may be used as a temporary value for local-scoped operations
1150 // rvva: if mutable, used as transient value for use for key lookup
1151 // rvvz: zero value of map value type, used to do a map set when nil is found in stream
1152 var rvk, rvkn, rvv, rvvn, rvva, rvvz reflect.Value
1153
1154 // we do a doMapGet if kind is mutable, and InterfaceReset=true if interface
1155 var doMapGet, doMapSet bool
1156
1157 if !d.h.MapValueReset {
1158 if rvvMut && (vtypeKind != reflect.Interface || !d.h.InterfaceReset) {
1159 doMapGet = true
1160 rvva = mapAddrLoopvarRV(vtype, vtypeKind)
1161 }
1162 }
1163
1164 ktypeIsString := ktypeId == stringTypId
1165 ktypeIsIntf := ktypeId == intfTypId
1166
1167 hasLen := containerLen > 0
1168
1169 // kstrbs is used locally for the key bytes, so we can reduce allocation.
1170 // When we read keys, we copy to this local bytes array, and use a stringView for lookup.
1171 // We only convert it into a true string if we have to do a set on the map.
1172
1173 // Since kstr2bs will usually escape to the heap, declaring a [64]byte array may be wasteful.
1174 // It is only valuable if we are sure that it is declared on the stack.
1175 // var kstrarr [64]byte // most keys are less than 32 bytes, and even more less than 64
1176 // var kstrbs = kstrarr[:0]
1177 var kstrbs []byte
1178 var kstr2bs []byte
1179 var s string
1180
1181 var callFnRvk bool
1182
1183 fnRvk2 := func() (s string) {
1184 callFnRvk = false
1185 if len(kstr2bs) < 2 {
1186 return string(kstr2bs)
1187 }
1188 return d.mapKeyString(&callFnRvk, &kstrbs, &kstr2bs)
1189 }
1190
1191 // Use a possibly transient (map) value (and key), to reduce allocation
1192
1193 for j := 0; d.containerNext(j, containerLen, hasLen); j++ {
1194 callFnRvk = false
1195 if j == 0 {
1196 // if vtypekind is a scalar and thus value will be decoded using TransientAddrK,
1197 // then it is ok to use TransientAddr2K for the map key.
1198 if decUseTransient && vTransient && kTransient {
1199 rvk = d.perType.TransientAddr2K(ktype, ktypeKind)
1200 } else {
1201 rvk = rvZeroAddrK(ktype, ktypeKind)
1202 }
1203 if !rvkMut {
1204 rvkn = rvk
1205 }
1206 if !rvvMut {
1207 if decUseTransient && vTransient {
1208 rvvn = d.perType.TransientAddrK(vtype, vtypeKind)
1209 } else {
1210 rvvn = rvZeroAddrK(vtype, vtypeKind)
1211 }
1212 }
1213 if !ktypeIsString && keyFn == nil {
1214 keyFn = d.h.fn(ktypeLo)
1215 }
1216 if valFn == nil {
1217 valFn = d.h.fn(vtypeLo)
1218 }
1219 } else if rvkMut {
1220 rvSetZero(rvk)
1221 } else {
1222 rvk = rvkn
1223 }
1224
1225 d.mapElemKey()
1226 if ktypeIsString {
1227 kstr2bs = d.d.DecodeStringAsBytes()
1228 rvSetString(rvk, fnRvk2())
1229 } else {
1230 d.decByteState = decByteStateNone
1231 d.decodeValue(rvk, keyFn)
1232 // special case if interface wrapping a byte slice
1233 if ktypeIsIntf {
1234 if rvk2 := rvk.Elem(); rvk2.IsValid() && rvType(rvk2) == uint8SliceTyp {
1235 kstr2bs = rvGetBytes(rvk2)
1236 rvSetIntf(rvk, rv4istr(fnRvk2()))
1237 }
1238 // NOTE: consider failing early if map/slice/func
1239 }
1240 }
1241
1242 d.mapElemValue()
1243
1244 if d.d.TryNil() {
1245 // since a map, we have to set zero value if needed
1246 if !rvvz.IsValid() {
1247 rvvz = rvZeroK(vtype, vtypeKind)
1248 }
1249 if callFnRvk {
1250 s = d.string(kstr2bs)
1251 if ktypeIsString {
1252 rvSetString(rvk, s)
1253 } else { // ktypeIsIntf
1254 rvSetIntf(rvk, rv4istr(s))
1255 }
1256 }
1257 mapSet(rv, rvk, rvvz, kfast, visindirect, visref)
1258 continue
1259 }
1260
1261 // there is non-nil content in the stream to decode ...
1262 // consequently, it's ok to just directly create new value to the pointer (if vtypePtr)
1263
1264 // set doMapSet to false iff u do a get, and the return value is a non-nil pointer
1265 doMapSet = true
1266
1267 if !rvvMut {
1268 rvv = rvvn
1269 } else if !doMapGet {
1270 goto NEW_RVV
1271 } else {
1272 rvv = mapGet(rv, rvk, rvva, kfast, visindirect, visref)
1273 if !rvv.IsValid() || (rvvCanNil && rvIsNil(rvv)) {
1274 goto NEW_RVV
1275 }
1276 switch vtypeKind {
1277 case reflect.Ptr, reflect.Map: // ok to decode directly into map
1278 doMapSet = false
1279 case reflect.Interface:
1280 // if an interface{}, just decode into it iff a non-nil ptr/map, else allocate afresh
1281 rvvn = rvv.Elem()
1282 if k := rvvn.Kind(); (k == reflect.Ptr || k == reflect.Map) && !rvIsNil(rvvn) {
1283 d.decodeValueNoCheckNil(rvvn, nil) // valFn is incorrect here
1284 continue
1285 }
1286 // make addressable (so we can set the interface)
1287 rvvn = rvZeroAddrK(vtype, vtypeKind)
1288 rvSetIntf(rvvn, rvv)
1289 rvv = rvvn
1290 default:
1291 // make addressable (so you can set the slice/array elements, etc)
1292 if decUseTransient && vTransient {
1293 rvvn = d.perType.TransientAddrK(vtype, vtypeKind)
1294 } else {
1295 rvvn = rvZeroAddrK(vtype, vtypeKind)
1296 }
1297 rvSetDirect(rvvn, rvv)
1298 rvv = rvvn
1299 }
1300 }
1301 goto DECODE_VALUE_NO_CHECK_NIL
1302
1303 NEW_RVV:
1304 if vtypePtr {
1305 rvv = reflect.New(vtypeElem) // non-nil in stream, so allocate value
1306 } else if decUseTransient && vTransient {
1307 rvv = d.perType.TransientAddrK(vtype, vtypeKind)
1308 } else {
1309 rvv = rvZeroAddrK(vtype, vtypeKind)
1310 }
1311
1312 DECODE_VALUE_NO_CHECK_NIL:
1313 d.decodeValueNoCheckNil(rvv, valFn)
1314
1315 if doMapSet {
1316 if callFnRvk {
1317 s = d.string(kstr2bs)
1318 if ktypeIsString {
1319 rvSetString(rvk, s)
1320 } else { // ktypeIsIntf
1321 rvSetIntf(rvk, rv4istr(s))
1322 }
1323 }
1324 mapSet(rv, rvk, rvv, kfast, visindirect, visref)
1325 }
1326 }
1327
1328 d.mapEnd()
1329 }
1330
1331 // Decoder reads and decodes an object from an input stream in a supported format.
1332 //
1333 // Decoder is NOT safe for concurrent use i.e. a Decoder cannot be used
1334 // concurrently in multiple goroutines.
1335 //
1336 // However, as Decoder could be allocation heavy to initialize, a Reset method is provided
1337 // so its state can be reused to decode new input streams repeatedly.
1338 // This is the idiomatic way to use.
1339 type Decoder struct {
1340 panicHdl
1341
1342 d decDriver
1343
1344 // cache the mapTypeId and sliceTypeId for faster comparisons
1345 mtid uintptr
1346 stid uintptr
1347
1348 h *BasicHandle
1349
1350 blist bytesFreelist
1351
1352 // ---- cpu cache line boundary?
1353 decRd
1354
1355 // ---- cpu cache line boundary?
1356 n fauxUnion
1357
1358 hh Handle
1359 err error
1360
1361 perType decPerType
1362
1363 // used for interning strings
1364 is internerMap
1365
1366 // ---- cpu cache line boundary?
1367 // ---- writable fields during execution --- *try* to keep in sep cache line
1368 maxdepth int16
1369 depth int16
1370
1371 // Extensions can call Decode() within a current Decode() call.
1372 // We need to know when the top level Decode() call returns,
1373 // so we can decide whether to Release() or not.
1374 calls uint16 // what depth in mustDecode are we in now.
1375
1376 c containerState
1377
1378 decByteState
1379
1380 // b is an always-available scratch buffer used by Decoder and decDrivers.
1381 // By being always-available, it can be used for one-off things without
1382 // having to get from freelist, use, and return back to freelist.
1383 b [decScratchByteArrayLen]byte
1384 }
1385
1386 // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
1387 //
1388 // For efficiency, Users are encouraged to configure ReaderBufferSize on the handle
1389 // OR pass in a memory buffered reader (eg bufio.Reader, bytes.Buffer).
1390 func NewDecoder(r io.Reader, h Handle) *Decoder {
1391 d := h.newDecDriver().decoder()
1392 if r != nil {
1393 d.Reset(r)
1394 }
1395 return d
1396 }
1397
1398 // NewDecoderBytes returns a Decoder which efficiently decodes directly
1399 // from a byte slice with zero copying.
1400 func NewDecoderBytes(in []byte, h Handle) *Decoder {
1401 d := h.newDecDriver().decoder()
1402 if in != nil {
1403 d.ResetBytes(in)
1404 }
1405 return d
1406 }
1407
1408 // NewDecoderString returns a Decoder which efficiently decodes directly
1409 // from a string with zero copying.
1410 //
1411 // It is a convenience function that calls NewDecoderBytes with a
1412 // []byte view into the string.
1413 //
1414 // This can be an efficient zero-copy if using default mode i.e. without codec.safe tag.
1415 func NewDecoderString(s string, h Handle) *Decoder {
1416 return NewDecoderBytes(bytesView(s), h)
1417 }
1418
1419 func (d *Decoder) r() *decRd {
1420 return &d.decRd
1421 }
1422
1423 func (d *Decoder) init(h Handle) {
1424 initHandle(h)
1425 d.bytes = true
1426 d.err = errDecoderNotInitialized
1427 d.h = h.getBasicHandle()
1428 d.hh = h
1429 d.be = h.isBinary()
1430 if d.h.InternString && d.is == nil {
1431 d.is.init()
1432 }
1433 // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
1434 }
1435
1436 func (d *Decoder) resetCommon() {
1437 d.d.reset()
1438 d.err = nil
1439 d.c = 0
1440 d.decByteState = decByteStateNone
1441 d.depth = 0
1442 d.calls = 0
1443 // reset all things which were cached from the Handle, but could change
1444 d.maxdepth = decDefMaxDepth
1445 if d.h.MaxDepth > 0 {
1446 d.maxdepth = d.h.MaxDepth
1447 }
1448 d.mtid = 0
1449 d.stid = 0
1450 d.mtr = false
1451 d.str = false
1452 if d.h.MapType != nil {
1453 d.mtid = rt2id(d.h.MapType)
1454 d.mtr = fastpathAvIndex(d.mtid) != -1
1455 }
1456 if d.h.SliceType != nil {
1457 d.stid = rt2id(d.h.SliceType)
1458 d.str = fastpathAvIndex(d.stid) != -1
1459 }
1460 }
1461
1462 // Reset the Decoder with a new Reader to decode from,
1463 // clearing all state from last run(s).
1464 func (d *Decoder) Reset(r io.Reader) {
1465 if r == nil {
1466 r = &eofReader
1467 }
1468 d.bytes = false
1469 if d.h.ReaderBufferSize > 0 {
1470 if d.bi == nil {
1471 d.bi = new(bufioDecReader)
1472 }
1473 d.bi.reset(r, d.h.ReaderBufferSize, &d.blist)
1474 d.bufio = true
1475 d.decReader = d.bi
1476 } else {
1477 if d.ri == nil {
1478 d.ri = new(ioDecReader)
1479 }
1480 d.ri.reset(r, &d.blist)
1481 d.bufio = false
1482 d.decReader = d.ri
1483 }
1484 d.resetCommon()
1485 }
1486
1487 // ResetBytes resets the Decoder with a new []byte to decode from,
1488 // clearing all state from last run(s).
1489 func (d *Decoder) ResetBytes(in []byte) {
1490 if in == nil {
1491 in = []byte{}
1492 }
1493 d.bufio = false
1494 d.bytes = true
1495 d.decReader = &d.rb
1496 d.rb.reset(in)
1497 d.resetCommon()
1498 }
1499
1500 // ResetString resets the Decoder with a new string to decode from,
1501 // clearing all state from last run(s).
1502 //
1503 // It is a convenience function that calls ResetBytes with a
1504 // []byte view into the string.
1505 //
1506 // This can be an efficient zero-copy if using default mode i.e. without codec.safe tag.
1507 func (d *Decoder) ResetString(s string) {
1508 d.ResetBytes(bytesView(s))
1509 }
1510
1511 func (d *Decoder) naked() *fauxUnion {
1512 return &d.n
1513 }
1514
1515 // Decode decodes the stream from reader and stores the result in the
1516 // value pointed to by v. v cannot be a nil pointer. v can also be
1517 // a reflect.Value of a pointer.
1518 //
1519 // Note that a pointer to a nil interface is not a nil pointer.
1520 // If you do not know what type of stream it is, pass in a pointer to a nil interface.
1521 // We will decode and store a value in that nil interface.
1522 //
1523 // Sample usages:
1524 //
1525 // // Decoding into a non-nil typed value
1526 // var f float32
1527 // err = codec.NewDecoder(r, handle).Decode(&f)
1528 //
1529 // // Decoding into nil interface
1530 // var v interface{}
1531 // dec := codec.NewDecoder(r, handle)
1532 // err = dec.Decode(&v)
1533 //
1534 // When decoding into a nil interface{}, we will decode into an appropriate value based
1535 // on the contents of the stream:
1536 // - Numbers are decoded as float64, int64 or uint64.
1537 // - Other values are decoded appropriately depending on the type:
1538 // bool, string, []byte, time.Time, etc
1539 // - Extensions are decoded as RawExt (if no ext function registered for the tag)
1540 //
1541 // Configurations exist on the Handle to override defaults
1542 // (e.g. for MapType, SliceType and how to decode raw bytes).
1543 //
1544 // When decoding into a non-nil interface{} value, the mode of encoding is based on the
1545 // type of the value. When a value is seen:
1546 // - If an extension is registered for it, call that extension function
1547 // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
1548 // - Else decode it based on its reflect.Kind
1549 //
1550 // There are some special rules when decoding into containers (slice/array/map/struct).
1551 // Decode will typically use the stream contents to UPDATE the container i.e. the values
1552 // in these containers will not be zero'ed before decoding.
1553 // - A map can be decoded from a stream map, by updating matching keys.
1554 // - A slice can be decoded from a stream array,
1555 // by updating the first n elements, where n is length of the stream.
1556 // - A slice can be decoded from a stream map, by decoding as if
1557 // it contains a sequence of key-value pairs.
1558 // - A struct can be decoded from a stream map, by updating matching fields.
1559 // - A struct can be decoded from a stream array,
1560 // by updating fields as they occur in the struct (by index).
1561 //
1562 // This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update
1563 // in place by default). However, the consequence of this is that values in slices or maps
1564 // which are not zero'ed before hand, will have part of the prior values in place after decode
1565 // if the stream doesn't contain an update for those parts.
1566 //
1567 // This in-place update can be disabled by configuring the MapValueReset and SliceElementReset
1568 // decode options available on every handle.
1569 //
1570 // Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice,
1571 // we reset the destination map or slice to a zero-length value.
1572 //
1573 // However, when decoding a stream nil, we reset the destination container
1574 // to its "zero" value (e.g. nil for slice/map, etc).
1575 //
1576 // Note: we allow nil values in the stream anywhere except for map keys.
1577 // A nil value in the encoded stream where a map key is expected is treated as an error.
1578 func (d *Decoder) Decode(v interface{}) (err error) {
1579 // tried to use closure, as runtime optimizes defer with no params.
1580 // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
1581 // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
1582 if !debugging {
1583 defer func() {
1584 if x := recover(); x != nil {
1585 panicValToErr(d, x, &d.err)
1586 err = d.err
1587 }
1588 }()
1589 }
1590
1591 d.MustDecode(v)
1592 return
1593 }
1594
1595 // MustDecode is like Decode, but panics if unable to Decode.
1596 //
1597 // Note: This provides insight to the code location that triggered the error.
1598 func (d *Decoder) MustDecode(v interface{}) {
1599 halt.onerror(d.err)
1600 if d.hh == nil {
1601 halt.onerror(errNoFormatHandle)
1602 }
1603
1604 // Top-level: v is a pointer and not nil.
1605 d.calls++
1606 d.decode(v)
1607 d.calls--
1608 }
1609
1610 // Release releases shared (pooled) resources.
1611 //
1612 // It is important to call Release() when done with a Decoder, so those resources
1613 // are released instantly for use by subsequently created Decoders.
1614 //
1615 // By default, Release() is automatically called unless the option ExplicitRelease is set.
1616 //
1617 // Deprecated: Release is a no-op as pooled resources are not used with an Decoder.
1618 // This method is kept for compatibility reasons only.
1619 func (d *Decoder) Release() {
1620 }
1621
1622 func (d *Decoder) swallow() {
1623 d.d.nextValueBytes(nil)
1624 }
1625
1626 func (d *Decoder) swallowErr() (err error) {
1627 if !debugging {
1628 defer func() {
1629 if x := recover(); x != nil {
1630 panicValToErr(d, x, &err)
1631 }
1632 }()
1633 }
1634 d.swallow()
1635 return
1636 }
1637
1638 func setZero(iv interface{}) {
1639 if iv == nil {
1640 return
1641 }
1642 rv, ok := isNil(iv)
1643 if ok {
1644 return
1645 }
1646 // var canDecode bool
1647 switch v := iv.(type) {
1648 case *string:
1649 *v = ""
1650 case *bool:
1651 *v = false
1652 case *int:
1653 *v = 0
1654 case *int8:
1655 *v = 0
1656 case *int16:
1657 *v = 0
1658 case *int32:
1659 *v = 0
1660 case *int64:
1661 *v = 0
1662 case *uint:
1663 *v = 0
1664 case *uint8:
1665 *v = 0
1666 case *uint16:
1667 *v = 0
1668 case *uint32:
1669 *v = 0
1670 case *uint64:
1671 *v = 0
1672 case *float32:
1673 *v = 0
1674 case *float64:
1675 *v = 0
1676 case *complex64:
1677 *v = 0
1678 case *complex128:
1679 *v = 0
1680 case *[]byte:
1681 *v = nil
1682 case *Raw:
1683 *v = nil
1684 case *time.Time:
1685 *v = time.Time{}
1686 case reflect.Value:
1687 decSetNonNilRV2Zero(v)
1688 default:
1689 if !fastpathDecodeSetZeroTypeSwitch(iv) {
1690 decSetNonNilRV2Zero(rv)
1691 }
1692 }
1693 }
1694
1695 // decSetNonNilRV2Zero will set the non-nil value to its zero value.
1696 func decSetNonNilRV2Zero(v reflect.Value) {
1697 // If not decodeable (settable), we do not touch it.
1698 // We considered empty'ing it if not decodeable e.g.
1699 // - if chan, drain it
1700 // - if map, clear it
1701 // - if slice or array, zero all elements up to len
1702 //
1703 // However, we decided instead that we either will set the
1704 // whole value to the zero value, or leave AS IS.
1705
1706 k := v.Kind()
1707 if k == reflect.Interface {
1708 decSetNonNilRV2Zero4Intf(v)
1709 } else if k == reflect.Ptr {
1710 decSetNonNilRV2Zero4Ptr(v)
1711 } else if v.CanSet() {
1712 rvSetDirectZero(v)
1713 }
1714 }
1715
1716 func decSetNonNilRV2Zero4Ptr(v reflect.Value) {
1717 ve := v.Elem()
1718 if ve.CanSet() {
1719 rvSetZero(ve) // we can have a pointer to an interface
1720 } else if v.CanSet() {
1721 rvSetZero(v)
1722 }
1723 }
1724
1725 func decSetNonNilRV2Zero4Intf(v reflect.Value) {
1726 ve := v.Elem()
1727 if ve.CanSet() {
1728 rvSetDirectZero(ve) // interfaces always have element as a non-interface
1729 } else if v.CanSet() {
1730 rvSetZero(v)
1731 }
1732 }
1733
1734 func (d *Decoder) decode(iv interface{}) {
1735 // a switch with only concrete types can be optimized.
1736 // consequently, we deal with nil and interfaces outside the switch.
1737
1738 if iv == nil {
1739 d.onerror(errCannotDecodeIntoNil)
1740 }
1741
1742 switch v := iv.(type) {
1743 // case nil:
1744 // case Selfer:
1745 case reflect.Value:
1746 if x, _ := isDecodeable(v); !x {
1747 d.haltAsNotDecodeable(v)
1748 }
1749 d.decodeValue(v, nil)
1750 case *string:
1751 *v = d.stringZC(d.d.DecodeStringAsBytes())
1752 case *bool:
1753 *v = d.d.DecodeBool()
1754 case *int:
1755 *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))
1756 case *int8:
1757 *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8))
1758 case *int16:
1759 *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16))
1760 case *int32:
1761 *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32))
1762 case *int64:
1763 *v = d.d.DecodeInt64()
1764 case *uint:
1765 *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))
1766 case *uint8:
1767 *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))
1768 case *uint16:
1769 *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))
1770 case *uint32:
1771 *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))
1772 case *uint64:
1773 *v = d.d.DecodeUint64()
1774 case *float32:
1775 *v = d.decodeFloat32()
1776 case *float64:
1777 *v = d.d.DecodeFloat64()
1778 case *complex64:
1779 *v = complex(d.decodeFloat32(), 0)
1780 case *complex128:
1781 *v = complex(d.d.DecodeFloat64(), 0)
1782 case *[]byte:
1783 *v = d.decodeBytesInto(*v)
1784 case []byte:
1785 // not addressable byte slice, so do not decode into it past the length
1786 b := d.decodeBytesInto(v[:len(v):len(v)])
1787 if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) { // not same slice
1788 copy(v, b)
1789 }
1790 case *time.Time:
1791 *v = d.d.DecodeTime()
1792 case *Raw:
1793 *v = d.rawBytes()
1794
1795 case *interface{}:
1796 d.decodeValue(rv4iptr(v), nil)
1797
1798 default:
1799 // we can't check non-predefined types, as they might be a Selfer or extension.
1800 if skipFastpathTypeSwitchInDirectCall || !fastpathDecodeTypeSwitch(iv, d) {
1801 v := reflect.ValueOf(iv)
1802 if x, _ := isDecodeable(v); !x {
1803 d.haltAsNotDecodeable(v)
1804 }
1805 d.decodeValue(v, nil)
1806 }
1807 }
1808 }
1809
1810 // decodeValue MUST be called by the actual value we want to decode into,
1811 // not its addr or a reference to it.
1812 //
1813 // This way, we know if it is itself a pointer, and can handle nil in
1814 // the stream effectively.
1815 //
1816 // Note that decodeValue will handle nil in the stream early, so that the
1817 // subsequent calls i.e. kXXX methods, etc do not have to handle it themselves.
1818 func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn) {
1819 if d.d.TryNil() {
1820 decSetNonNilRV2Zero(rv)
1821 return
1822 }
1823 d.decodeValueNoCheckNil(rv, fn)
1824 }
1825
1826 func (d *Decoder) decodeValueNoCheckNil(rv reflect.Value, fn *codecFn) {
1827 // If stream is not containing a nil value, then we can deref to the base
1828 // non-pointer value, and decode into that.
1829 var rvp reflect.Value
1830 var rvpValid bool
1831 PTR:
1832 if rv.Kind() == reflect.Ptr {
1833 rvpValid = true
1834 if rvIsNil(rv) {
1835 rvSetDirect(rv, reflect.New(rvType(rv).Elem()))
1836 }
1837 rvp = rv
1838 rv = rv.Elem()
1839 goto PTR
1840 }
1841
1842 if fn == nil {
1843 fn = d.h.fn(rvType(rv))
1844 }
1845 if fn.i.addrD {
1846 if rvpValid {
1847 rv = rvp
1848 } else if rv.CanAddr() {
1849 rv = rvAddr(rv, fn.i.ti.ptr)
1850 } else if fn.i.addrDf {
1851 d.errorf("cannot decode into a non-pointer value")
1852 }
1853 }
1854 fn.fd(d, &fn.i, rv)
1855 }
1856
1857 func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
1858 // Note: rvkencname is used only if there is an error, to pass into d.errorf.
1859 // Consequently, it is ok to pass in a stringView
1860 // Since rvkencname may be a stringView, do NOT pass it to another function.
1861 if d.h.ErrorIfNoField {
1862 if index >= 0 {
1863 d.errorf("no matching struct field found when decoding stream array at index %v", index)
1864 } else if rvkencname != "" {
1865 d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
1866 }
1867 }
1868 d.swallow()
1869 }
1870
1871 func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
1872 if d.h.ErrorIfNoArrayExpand {
1873 d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
1874 }
1875 }
1876
1877 func (d *Decoder) haltAsNotDecodeable(rv reflect.Value) {
1878 if !rv.IsValid() {
1879 d.onerror(errCannotDecodeIntoNil)
1880 }
1881 // check if an interface can be retrieved, before grabbing an interface
1882 if !rv.CanInterface() {
1883 d.errorf("cannot decode into a value without an interface: %v", rv)
1884 }
1885 d.errorf("cannot decode into value of kind: %v, %#v", rv.Kind(), rv2i(rv))
1886 }
1887
1888 func (d *Decoder) depthIncr() {
1889 d.depth++
1890 if d.depth >= d.maxdepth {
1891 d.onerror(errMaxDepthExceeded)
1892 }
1893 }
1894
1895 func (d *Decoder) depthDecr() {
1896 d.depth--
1897 }
1898
1899 // Possibly get an interned version of a string, iff InternString=true and decoding a map key.
1900 //
1901 // This should mostly be used for map keys, where the key type is string.
1902 // This is because keys of a map/struct are typically reused across many objects.
1903 func (d *Decoder) string(v []byte) (s string) {
1904 if d.is == nil || d.c != containerMapKey || len(v) < 2 || len(v) > internMaxStrLen {
1905 return string(v)
1906 }
1907 return d.is.string(v)
1908 }
1909
1910 func (d *Decoder) zerocopy() bool {
1911 return d.bytes && d.h.ZeroCopy
1912 }
1913
1914 // decodeBytesInto is a convenience delegate function to decDriver.DecodeBytes.
1915 // It ensures that `in` is not a nil byte, before calling decDriver.DecodeBytes,
1916 // as decDriver.DecodeBytes treats a nil as a hint to use its internal scratch buffer.
1917 func (d *Decoder) decodeBytesInto(in []byte) (v []byte) {
1918 if in == nil {
1919 in = []byte{}
1920 }
1921 return d.d.DecodeBytes(in)
1922 }
1923
1924 func (d *Decoder) rawBytes() (v []byte) {
1925 // ensure that this is not a view into the bytes
1926 // i.e. if necessary, make new copy always.
1927 v = d.d.nextValueBytes([]byte{})
1928 if d.bytes && !d.h.ZeroCopy {
1929 v0 := v
1930 v = make([]byte, len(v))
1931 copy(v, v0)
1932 }
1933 return
1934 }
1935
1936 func (d *Decoder) wrapErr(v error, err *error) {
1937 *err = wrapCodecErr(v, d.hh.Name(), d.NumBytesRead(), false)
1938 }
1939
1940 // NumBytesRead returns the number of bytes read
1941 func (d *Decoder) NumBytesRead() int {
1942 return int(d.r().numread())
1943 }
1944
1945 // decodeFloat32 will delegate to an appropriate DecodeFloat32 implementation (if exists),
1946 // else if will call DecodeFloat64 and ensure the value doesn't overflow.
1947 //
1948 // Note that we return float64 to reduce unnecessary conversions
1949 func (d *Decoder) decodeFloat32() float32 {
1950 if d.js {
1951 return d.jsondriver().DecodeFloat32() // custom implementation for 32-bit
1952 }
1953 return float32(chkOvf.Float32V(d.d.DecodeFloat64()))
1954 }
1955
1956 // ---- container tracking
1957 // Note: We update the .c after calling the callback.
1958 // This way, the callback can know what the last status was.
1959
1960 // MARKER: do not call mapEnd if mapStart returns containerLenNil.
1961
1962 func (d *Decoder) containerNext(j, containerLen int, hasLen bool) bool {
1963 // return (hasLen && j < containerLen) || !(hasLen || slh.d.checkBreak())
1964 if hasLen {
1965 return j < containerLen
1966 }
1967 return !d.checkBreak()
1968 }
1969
1970 func (d *Decoder) mapStart(v int) int {
1971 if v != containerLenNil {
1972 d.depthIncr()
1973 d.c = containerMapStart
1974 }
1975 return v
1976 }
1977
1978 func (d *Decoder) mapElemKey() {
1979 if d.js {
1980 d.jsondriver().ReadMapElemKey()
1981 }
1982 d.c = containerMapKey
1983 }
1984
1985 func (d *Decoder) mapElemValue() {
1986 if d.js {
1987 d.jsondriver().ReadMapElemValue()
1988 }
1989 d.c = containerMapValue
1990 }
1991
1992 func (d *Decoder) mapEnd() {
1993 d.d.ReadMapEnd()
1994 d.depthDecr()
1995 d.c = 0
1996 }
1997
1998 func (d *Decoder) arrayStart(v int) int {
1999 if v != containerLenNil {
2000 d.depthIncr()
2001 d.c = containerArrayStart
2002 }
2003 return v
2004 }
2005
2006 func (d *Decoder) arrayElem() {
2007 if d.js {
2008 d.jsondriver().ReadArrayElem()
2009 }
2010 d.c = containerArrayElem
2011 }
2012
2013 func (d *Decoder) arrayEnd() {
2014 d.d.ReadArrayEnd()
2015 d.depthDecr()
2016 d.c = 0
2017 }
2018
2019 func (d *Decoder) interfaceExtConvertAndDecode(v interface{}, ext InterfaceExt) {
2020 // var v interface{} = ext.ConvertExt(rv)
2021 // d.d.decode(&v)
2022 // ext.UpdateExt(rv, v)
2023
2024 // assume v is a pointer:
2025 // - if struct|array, pass as is to ConvertExt
2026 // - else make it non-addressable and pass to ConvertExt
2027 // - make return value from ConvertExt addressable
2028 // - decode into it
2029 // - return the interface for passing into UpdateExt.
2030 // - interface should be a pointer if struct|array, else a value
2031
2032 var s interface{}
2033 rv := reflect.ValueOf(v)
2034 rv2 := rv.Elem()
2035 rvk := rv2.Kind()
2036 if rvk == reflect.Struct || rvk == reflect.Array {
2037 s = ext.ConvertExt(v)
2038 } else {
2039 s = ext.ConvertExt(rv2i(rv2))
2040 }
2041 rv = reflect.ValueOf(s)
2042
2043 // We cannot use isDecodeable here, as the value converted may be nil,
2044 // or it may not be nil but is not addressable and thus we cannot extend it, etc.
2045 // Instead, we just ensure that the value is addressable.
2046
2047 if !rv.CanAddr() {
2048 rvk = rv.Kind()
2049 rv2 = d.oneShotAddrRV(rvType(rv), rvk)
2050 if rvk == reflect.Interface {
2051 rvSetIntf(rv2, rv)
2052 } else {
2053 rvSetDirect(rv2, rv)
2054 }
2055 rv = rv2
2056 }
2057
2058 d.decodeValue(rv, nil)
2059 ext.UpdateExt(v, rv2i(rv))
2060 }
2061
2062 func (d *Decoder) sideDecode(v interface{}, basetype reflect.Type, bs []byte) {
2063 // NewDecoderBytes(bs, d.hh).decodeValue(baseRV(v), d.h.fnNoExt(basetype))
2064
2065 defer func(rb bytesDecReader, bytes bool,
2066 c containerState, dbs decByteState, depth int16, r decReader, state interface{}) {
2067 d.rb = rb
2068 d.bytes = bytes
2069 d.c = c
2070 d.decByteState = dbs
2071 d.depth = depth
2072 d.decReader = r
2073 d.d.restoreState(state)
2074 }(d.rb, d.bytes, d.c, d.decByteState, d.depth, d.decReader, d.d.captureState())
2075
2076 // d.rb.reset(in)
2077 d.rb = bytesDecReader{bs[:len(bs):len(bs)], 0}
2078 d.bytes = true
2079 d.decReader = &d.rb
2080 d.d.resetState()
2081 d.c = 0
2082 d.decByteState = decByteStateNone
2083 d.depth = 0
2084
2085 // must call using fnNoExt
2086 d.decodeValue(baseRV(v), d.h.fnNoExt(basetype))
2087 }
2088
2089 func (d *Decoder) fauxUnionReadRawBytes(asString bool) {
2090 if asString || d.h.RawToString {
2091 d.n.v = valueTypeString
2092 // fauxUnion is only used within DecodeNaked calls; consequently, we should try to intern.
2093 d.n.s = d.stringZC(d.d.DecodeBytes(nil))
2094 } else {
2095 d.n.v = valueTypeBytes
2096 d.n.l = d.d.DecodeBytes([]byte{})
2097 }
2098 }
2099
2100 func (d *Decoder) oneShotAddrRV(rvt reflect.Type, rvk reflect.Kind) reflect.Value {
2101 if decUseTransient &&
2102 (numBoolStrSliceBitset.isset(byte(rvk)) ||
2103 ((rvk == reflect.Struct || rvk == reflect.Array) &&
2104 d.h.getTypeInfo(rt2id(rvt), rvt).flagCanTransient)) {
2105 return d.perType.TransientAddrK(rvt, rvk)
2106 }
2107 return rvZeroAddrK(rvt, rvk)
2108 }
2109
2110 // --------------------------------------------------
2111
2112 // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
2113 // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
2114 //
2115 // Note: if IsNil, do not call ElemContainerState.
2116 type decSliceHelper struct {
2117 d *Decoder
2118 ct valueType
2119 Array bool
2120 IsNil bool
2121 }
2122
2123 func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
2124 x.ct = d.d.ContainerType()
2125 x.d = d
2126 switch x.ct {
2127 case valueTypeNil:
2128 x.IsNil = true
2129 case valueTypeArray:
2130 x.Array = true
2131 clen = d.arrayStart(d.d.ReadArrayStart())
2132 case valueTypeMap:
2133 clen = d.mapStart(d.d.ReadMapStart())
2134 clen += clen
2135 default:
2136 d.errorf("only encoded map or array can be decoded into a slice (%d)", x.ct)
2137 }
2138 return
2139 }
2140
2141 func (x decSliceHelper) End() {
2142 if x.IsNil {
2143 } else if x.Array {
2144 x.d.arrayEnd()
2145 } else {
2146 x.d.mapEnd()
2147 }
2148 }
2149
2150 func (x decSliceHelper) ElemContainerState(index int) {
2151 // Note: if isnil, clen=0, so we never call into ElemContainerState
2152
2153 if x.Array {
2154 x.d.arrayElem()
2155 } else if index&1 == 0 { // index%2 == 0 {
2156 x.d.mapElemKey()
2157 } else {
2158 x.d.mapElemValue()
2159 }
2160 }
2161
2162 func (x decSliceHelper) arrayCannotExpand(hasLen bool, lenv, j, containerLenS int) {
2163 x.d.arrayCannotExpand(lenv, j+1)
2164 // drain completely and return
2165 x.ElemContainerState(j)
2166 x.d.swallow()
2167 j++
2168 for ; x.d.containerNext(j, containerLenS, hasLen); j++ {
2169 x.ElemContainerState(j)
2170 x.d.swallow()
2171 }
2172 x.End()
2173 }
2174
2175 // decNextValueBytesHelper helps with NextValueBytes calls.
2176 //
2177 // Typical usage:
2178 // - each Handle's decDriver will implement a high level nextValueBytes,
2179 // which will track the current cursor, delegate to a nextValueBytesR
2180 // method, and then potentially call bytesRdV at the end.
2181 //
2182 // See simple.go for typical usage model.
2183 type decNextValueBytesHelper struct {
2184 d *Decoder
2185 }
2186
2187 func (x decNextValueBytesHelper) append1(v *[]byte, b byte) {
2188 if *v != nil && !x.d.bytes {
2189 *v = append(*v, b)
2190 }
2191 }
2192
2193 func (x decNextValueBytesHelper) appendN(v *[]byte, b ...byte) {
2194 if *v != nil && !x.d.bytes {
2195 *v = append(*v, b...)
2196 }
2197 }
2198
2199 func (x decNextValueBytesHelper) bytesRdV(v *[]byte, startpos uint) {
2200 if x.d.bytes {
2201 *v = x.d.rb.b[startpos:x.d.rb.c]
2202 }
2203 }
2204
2205 // decNegintPosintFloatNumberHelper is used for formats that are binary
2206 // and have distinct ways of storing positive integers vs negative integers
2207 // vs floats, which are uniquely identified by the byte descriptor.
2208 //
2209 // Currently, these formats are binc, cbor and simple.
2210 type decNegintPosintFloatNumberHelper struct {
2211 d *Decoder
2212 }
2213
2214 func (x decNegintPosintFloatNumberHelper) uint64(ui uint64, neg, ok bool) uint64 {
2215 if ok && !neg {
2216 return ui
2217 }
2218 return x.uint64TryFloat(ok)
2219 }
2220
2221 func (x decNegintPosintFloatNumberHelper) uint64TryFloat(ok bool) (ui uint64) {
2222 if ok { // neg = true
2223 x.d.errorf("assigning negative signed value to unsigned type")
2224 }
2225 f, ok := x.d.d.decFloat()
2226 if ok && f >= 0 && noFrac64(math.Float64bits(f)) {
2227 ui = uint64(f)
2228 } else {
2229 x.d.errorf("invalid number loading uint64, with descriptor: %v", x.d.d.descBd())
2230 }
2231 return ui
2232 }
2233
2234 func decNegintPosintFloatNumberHelperInt64v(ui uint64, neg, incrIfNeg bool) (i int64) {
2235 if neg && incrIfNeg {
2236 ui++
2237 }
2238 i = chkOvf.SignedIntV(ui)
2239 if neg {
2240 i = -i
2241 }
2242 return
2243 }
2244
2245 func (x decNegintPosintFloatNumberHelper) int64(ui uint64, neg, ok bool) (i int64) {
2246 if ok {
2247 return decNegintPosintFloatNumberHelperInt64v(ui, neg, x.d.cbor)
2248 }
2249 // return x.int64TryFloat()
2250 // }
2251 // func (x decNegintPosintFloatNumberHelper) int64TryFloat() (i int64) {
2252 f, ok := x.d.d.decFloat()
2253 if ok && noFrac64(math.Float64bits(f)) {
2254 i = int64(f)
2255 } else {
2256 x.d.errorf("invalid number loading uint64, with descriptor: %v", x.d.d.descBd())
2257 }
2258 return
2259 }
2260
2261 func (x decNegintPosintFloatNumberHelper) float64(f float64, ok bool) float64 {
2262 if ok {
2263 return f
2264 }
2265 return x.float64TryInteger()
2266 }
2267
2268 func (x decNegintPosintFloatNumberHelper) float64TryInteger() float64 {
2269 ui, neg, ok := x.d.d.decInteger()
2270 if !ok {
2271 x.d.errorf("invalid descriptor for float: %v", x.d.d.descBd())
2272 }
2273 return float64(decNegintPosintFloatNumberHelperInt64v(ui, neg, x.d.cbor))
2274 }
2275
2276 // isDecodeable checks if value can be decoded into
2277 //
2278 // decode can take any reflect.Value that is a inherently addressable i.e.
2279 // - non-nil chan (we will SEND to it)
2280 // - non-nil slice (we will set its elements)
2281 // - non-nil map (we will put into it)
2282 // - non-nil pointer (we can "update" it)
2283 // - func: no
2284 // - interface: no
2285 // - array: if canAddr=true
2286 // - any other value pointer: if canAddr=true
2287 func isDecodeable(rv reflect.Value) (canDecode bool, reason decNotDecodeableReason) {
2288 switch rv.Kind() {
2289 case reflect.Ptr, reflect.Slice, reflect.Chan, reflect.Map:
2290 canDecode = !rvIsNil(rv)
2291 reason = decNotDecodeableReasonNilReference
2292 case reflect.Func, reflect.Interface, reflect.Invalid, reflect.UnsafePointer:
2293 reason = decNotDecodeableReasonBadKind
2294 default:
2295 canDecode = rv.CanAddr()
2296 reason = decNotDecodeableReasonNonAddrValue
2297 }
2298 return
2299 }
2300
2301 func decByteSlice(r *decRd, clen, maxInitLen int, bs []byte) (bsOut []byte) {
2302 if clen == 0 {
2303 return zeroByteSlice
2304 }
2305 if len(bs) == clen {
2306 bsOut = bs
2307 r.readb(bsOut)
2308 } else if cap(bs) >= clen {
2309 bsOut = bs[:clen]
2310 r.readb(bsOut)
2311 } else {
2312 var len2 int
2313 for len2 < clen {
2314 len3 := decInferLen(clen-len2, maxInitLen, 1)
2315 bs3 := bsOut
2316 bsOut = make([]byte, len2+len3)
2317 copy(bsOut, bs3)
2318 r.readb(bsOut[len2:])
2319 len2 += len3
2320 }
2321 }
2322 return
2323 }
2324
2325 // decInferLen will infer a sensible length, given the following:
2326 // - clen: length wanted.
2327 // - maxlen: max length to be returned.
2328 // if <= 0, it is unset, and we infer it based on the unit size
2329 // - unit: number of bytes for each element of the collection
2330 func decInferLen(clen, maxlen, unit int) int {
2331 // anecdotal testing showed increase in allocation with map length of 16.
2332 // We saw same typical alloc from 0-8, then a 20% increase at 16.
2333 // Thus, we set it to 8.
2334 const (
2335 minLenIfUnset = 8
2336 maxMem = 256 * 1024 // 256Kb Memory
2337 )
2338
2339 // handle when maxlen is not set i.e. <= 0
2340
2341 // clen==0: use 0
2342 // maxlen<=0, clen<0: use default
2343 // maxlen> 0, clen<0: use default
2344 // maxlen<=0, clen>0: infer maxlen, and cap on it
2345 // maxlen> 0, clen>0: cap at maxlen
2346
2347 if clen == 0 || clen == containerLenNil {
2348 return 0
2349 }
2350 if clen < 0 {
2351 // if unspecified, return 64 for bytes, ... 8 for uint64, ... and everything else
2352 clen = 64 / unit
2353 if clen > minLenIfUnset {
2354 return clen
2355 }
2356 return minLenIfUnset
2357 }
2358 if unit <= 0 {
2359 return clen
2360 }
2361 if maxlen <= 0 {
2362 maxlen = maxMem / unit
2363 }
2364 if clen < maxlen {
2365 return clen
2366 }
2367 return maxlen
2368 }