decode.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. import (
  5. "encoding"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "reflect"
  10. "runtime"
  11. "strconv"
  12. "time"
  13. )
  14. // Some tagging information for error messages.
  15. const (
  16. msgBadDesc = "unrecognized descriptor byte"
  17. // msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v"
  18. )
  19. const (
  20. decDefMaxDepth = 1024 // maximum depth
  21. decDefSliceCap = 8
  22. decDefChanCap = 64 // should be large, as cap cannot be expanded
  23. decScratchByteArrayLen = cacheLineSize // - 5 // + (8 * 2) // - (8 * 1)
  24. )
  25. var (
  26. errstrOnlyMapOrArrayCanDecodeIntoStruct = "only encoded map or array can be decoded into a struct"
  27. errstrCannotDecodeIntoNil = "cannot decode into nil"
  28. errmsgExpandSliceOverflow = "expand slice: slice overflow"
  29. errmsgExpandSliceCannotChange = "expand slice: cannot change"
  30. errDecoderNotInitialized = errors.New("Decoder not initialized")
  31. errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read")
  32. errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read")
  33. errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown")
  34. errMaxDepthExceeded = errors.New("maximum decoding depth exceeded")
  35. errBytesDecReaderCannotUnread = errors.New("cannot unread last byte read")
  36. )
  37. type decDriver interface {
  38. // this will check if the next token is a break.
  39. CheckBreak() bool
  40. // TryDecodeAsNil tries to decode as nil.
  41. // Note: TryDecodeAsNil should be careful not to share any temporary []byte with
  42. // the rest of the decDriver. This is because sometimes, we optimize by holding onto
  43. // a transient []byte, and ensuring the only other call we make to the decDriver
  44. // during that time is maybe a TryDecodeAsNil() call.
  45. TryDecodeAsNil() bool
  46. // ContainerType returns one of: Bytes, String, Nil, Slice or Map. Return unSet if not known.
  47. ContainerType() (vt valueType)
  48. // IsBuiltinType(rt uintptr) bool
  49. // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt.
  50. // For maps and arrays, it will not do the decoding in-band, but will signal
  51. // the decoder, so that is done later, by setting the decNaked.valueType field.
  52. //
  53. // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
  54. // for extensions, DecodeNaked must read the tag and the []byte if it exists.
  55. // if the []byte is not read, then kInterfaceNaked will treat it as a Handle
  56. // that stores the subsequent value in-band, and complete reading the RawExt.
  57. //
  58. // extensions should also use readx to decode them, for efficiency.
  59. // kInterface will extract the detached byte slice if it has to pass it outside its realm.
  60. DecodeNaked()
  61. DecodeInt64() (i int64)
  62. DecodeUint64() (ui uint64)
  63. DecodeFloat64() (f float64)
  64. DecodeBool() (b bool)
  65. // DecodeStringAsBytes returns the bytes representing a string.
  66. // By definition, it will return a view into a scratch buffer.
  67. //
  68. // Note: This can also decode symbols, if supported.
  69. //
  70. // Users should consume it right away and not store it for later use.
  71. DecodeStringAsBytes() (v []byte)
  72. // DecodeBytes may be called directly, without going through reflection.
  73. // Consequently, it must be designed to handle possible nil.
  74. DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte)
  75. // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
  76. // DecodeExt will decode into a *RawExt or into an extension.
  77. DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64)
  78. // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
  79. DecodeTime() (t time.Time)
  80. ReadArrayStart() int
  81. ReadArrayEnd()
  82. ReadMapStart() int
  83. ReadMapEnd()
  84. reset()
  85. atEndOfDecode()
  86. uncacheRead()
  87. }
  88. type decDriverContainerTracker interface {
  89. ReadArrayElem()
  90. ReadMapElemKey()
  91. ReadMapElemValue()
  92. }
  93. type decodeError struct {
  94. codecError
  95. pos int
  96. }
  97. func (d decodeError) Error() string {
  98. return fmt.Sprintf("%s decode error [pos %d]: %v", d.name, d.pos, d.err)
  99. }
  100. type decDriverNoopContainerReader struct{}
  101. func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { return }
  102. func (x decDriverNoopContainerReader) ReadArrayEnd() {}
  103. func (x decDriverNoopContainerReader) ReadMapStart() (v int) { return }
  104. func (x decDriverNoopContainerReader) ReadMapEnd() {}
  105. func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return }
  106. func (x decDriverNoopContainerReader) atEndOfDecode() {}
  107. // func (x decDriverNoopContainerReader) ReadArrayElem() {}
  108. // func (x decDriverNoopContainerReader) ReadMapElemKey() {}
  109. // func (x decDriverNoopContainerReader) ReadMapElemValue() {}
  110. // func (x decNoSeparator) uncacheRead() {}
  111. // DecodeOptions captures configuration options during decode.
  112. type DecodeOptions struct {
  113. // MapType specifies type to use during schema-less decoding of a map in the stream.
  114. // If nil (unset), we default to map[string]interface{} iff json handle and MapStringAsKey=true,
  115. // else map[interface{}]interface{}.
  116. MapType reflect.Type
  117. // SliceType specifies type to use during schema-less decoding of an array in the stream.
  118. // If nil (unset), we default to []interface{} for all formats.
  119. SliceType reflect.Type
  120. // MaxInitLen defines the maxinum initial length that we "make" a collection
  121. // (string, slice, map, chan). If 0 or negative, we default to a sensible value
  122. // based on the size of an element in the collection.
  123. //
  124. // For example, when decoding, a stream may say that it has 2^64 elements.
  125. // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash.
  126. // Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
  127. MaxInitLen int
  128. // ReaderBufferSize is the size of the buffer used when reading.
  129. //
  130. // if > 0, we use a smart buffer internally for performance purposes.
  131. ReaderBufferSize int
  132. // MaxDepth defines the maximum depth when decoding nested
  133. // maps and slices. If 0 or negative, we default to a suitably large number (currently 1024).
  134. MaxDepth int16
  135. // If ErrorIfNoField, return an error when decoding a map
  136. // from a codec stream into a struct, and no matching struct field is found.
  137. ErrorIfNoField bool
  138. // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
  139. // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
  140. // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
  141. ErrorIfNoArrayExpand bool
  142. // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
  143. SignedInteger bool
  144. // MapValueReset controls how we decode into a map value.
  145. //
  146. // By default, we MAY retrieve the mapping for a key, and then decode into that.
  147. // However, especially with big maps, that retrieval may be expensive and unnecessary
  148. // if the stream already contains all that is necessary to recreate the value.
  149. //
  150. // If true, we will never retrieve the previous mapping,
  151. // but rather decode into a new value and set that in the map.
  152. //
  153. // If false, we will retrieve the previous mapping if necessary e.g.
  154. // the previous mapping is a pointer, or is a struct or array with pre-set state,
  155. // or is an interface.
  156. MapValueReset bool
  157. // SliceElementReset: on decoding a slice, reset the element to a zero value first.
  158. //
  159. // concern: if the slice already contained some garbage, we will decode into that garbage.
  160. SliceElementReset bool
  161. // InterfaceReset controls how we decode into an interface.
  162. //
  163. // By default, when we see a field that is an interface{...},
  164. // or a map with interface{...} value, we will attempt decoding into the
  165. // "contained" value.
  166. //
  167. // However, this prevents us from reading a string into an interface{}
  168. // that formerly contained a number.
  169. //
  170. // If true, we will decode into a new "blank" value, and set that in the interface.
  171. // If false, we will decode into whatever is contained in the interface.
  172. InterfaceReset bool
  173. // InternString controls interning of strings during decoding.
  174. //
  175. // Some handles, e.g. json, typically will read map keys as strings.
  176. // If the set of keys are finite, it may help reduce allocation to
  177. // look them up from a map (than to allocate them afresh).
  178. //
  179. // Note: Handles will be smart when using the intern functionality.
  180. // Every string should not be interned.
  181. // An excellent use-case for interning is struct field names,
  182. // or map keys where key type is string.
  183. InternString bool
  184. // PreferArrayOverSlice controls whether to decode to an array or a slice.
  185. //
  186. // This only impacts decoding into a nil interface{}.
  187. // Consequently, it has no effect on codecgen.
  188. //
  189. // *Note*: This only applies if using go1.5 and above,
  190. // as it requires reflect.ArrayOf support which was absent before go1.5.
  191. PreferArrayOverSlice bool
  192. // DeleteOnNilMapValue controls how to decode a nil value in the stream.
  193. //
  194. // If true, we will delete the mapping of the key.
  195. // Else, just set the mapping to the zero value of the type.
  196. DeleteOnNilMapValue bool
  197. // RawToString controls how raw bytes in a stream are decoded into a nil interface{}.
  198. // By default, they are decoded as []byte, but can be decoded as string (if configured).
  199. RawToString bool
  200. }
  201. // ----------------------------------------
  202. // func (d *Decoder) builtin(f *codecFnInfo, rv reflect.Value) {
  203. // d.d.DecodeBuiltin(f.ti.rtid, rv2i(rv))
  204. // }
  205. func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) {
  206. d.d.DecodeExt(rv2i(rv), 0, nil)
  207. }
  208. func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) {
  209. d.d.DecodeExt(rv2i(rv), f.xfTag, f.xfFn)
  210. }
  211. func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) {
  212. rv2i(rv).(Selfer).CodecDecodeSelf(d)
  213. }
  214. func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) {
  215. bm := rv2i(rv).(encoding.BinaryUnmarshaler)
  216. xbs := d.d.DecodeBytes(nil, true)
  217. if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil {
  218. panic(fnerr)
  219. }
  220. }
  221. func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) {
  222. tm := rv2i(rv).(encoding.TextUnmarshaler)
  223. fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes())
  224. if fnerr != nil {
  225. panic(fnerr)
  226. }
  227. }
  228. func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) {
  229. tm := rv2i(rv).(jsonUnmarshaler)
  230. // bs := d.d.DecodeBytes(d.b[:], true, true)
  231. // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
  232. fnerr := tm.UnmarshalJSON(d.nextValueBytes())
  233. if fnerr != nil {
  234. panic(fnerr)
  235. }
  236. }
  237. func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) {
  238. d.errorf("no decoding function defined for kind %v", rv.Kind())
  239. }
  240. // var kIntfCtr uint64
  241. func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) {
  242. // nil interface:
  243. // use some hieristics to decode it appropriately
  244. // based on the detected next value in the stream.
  245. n := d.naked()
  246. d.d.DecodeNaked()
  247. if n.v == valueTypeNil {
  248. return
  249. }
  250. // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader).
  251. if f.ti.numMeth > 0 {
  252. d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth)
  253. return
  254. }
  255. // var useRvn bool
  256. switch n.v {
  257. case valueTypeMap:
  258. // if json, default to a map type with string keys
  259. mtid := d.mtid
  260. if mtid == 0 {
  261. if d.jsms {
  262. mtid = mapStrIntfTypId
  263. } else {
  264. mtid = mapIntfIntfTypId
  265. }
  266. }
  267. if mtid == mapIntfIntfTypId {
  268. var v2 map[interface{}]interface{}
  269. d.decode(&v2)
  270. rvn = reflect.ValueOf(&v2).Elem()
  271. } else if mtid == mapStrIntfTypId { // for json performance
  272. var v2 map[string]interface{}
  273. d.decode(&v2)
  274. rvn = reflect.ValueOf(&v2).Elem()
  275. } else {
  276. if d.mtr {
  277. rvn = reflect.New(d.h.MapType)
  278. d.decode(rv2i(rvn))
  279. rvn = rvn.Elem()
  280. } else {
  281. rvn = reflect.New(d.h.MapType).Elem()
  282. d.decodeValue(rvn, nil)
  283. }
  284. }
  285. case valueTypeArray:
  286. if d.stid == 0 || d.stid == intfSliceTypId {
  287. var v2 []interface{}
  288. d.decode(&v2)
  289. rvn = reflect.ValueOf(&v2).Elem()
  290. if reflectArrayOfSupported && d.stid == 0 && d.h.PreferArrayOverSlice {
  291. rvn2 := reflect.New(reflectArrayOf(rvn.Len(), intfTyp)).Elem()
  292. reflect.Copy(rvn2, rvn)
  293. rvn = rvn2
  294. }
  295. } else {
  296. if d.str {
  297. rvn = reflect.New(d.h.SliceType)
  298. d.decode(rv2i(rvn))
  299. rvn = rvn.Elem()
  300. } else {
  301. rvn = reflect.New(d.h.SliceType).Elem()
  302. d.decodeValue(rvn, nil)
  303. }
  304. }
  305. case valueTypeExt:
  306. tag, bytes := n.u, n.l // calling decode below might taint the values
  307. bfn := d.h.getExtForTag(tag)
  308. var re = RawExt{Tag: tag}
  309. if bytes == nil {
  310. // it is one of the InterfaceExt ones: json and cbor.
  311. // most likely cbor, as json decoding never reveals valueTypeExt (no tagging support)
  312. if bfn == nil {
  313. d.decode(&re.Value)
  314. rvn = reflect.ValueOf(&re).Elem()
  315. } else {
  316. rvn = reflect.New(bfn.rt)
  317. if bfn.ext == SelfExt {
  318. d.decodeValue(rvn, d.h.fnNoExt(rvn.Type().Elem()))
  319. } else {
  320. d.interfaceExtConvertAndDecode(rv2i(rvn), bfn.ext)
  321. }
  322. rvn = rvn.Elem()
  323. }
  324. } else {
  325. // one of the BytesExt ones: binc, msgpack, simple
  326. if bfn == nil {
  327. re.Data = detachZeroCopyBytes(d.bytes, nil, bytes)
  328. rvn = reflect.ValueOf(&re).Elem()
  329. } else {
  330. rvn = reflect.New(bfn.rt)
  331. if bfn.ext == SelfExt {
  332. d.sideDecode(rv2i(rvn), bytes)
  333. } else {
  334. bfn.ext.ReadExt(rv2i(rvn), bytes)
  335. }
  336. rvn = rvn.Elem()
  337. }
  338. }
  339. case valueTypeNil:
  340. // no-op
  341. case valueTypeInt:
  342. rvn = n.ri()
  343. case valueTypeUint:
  344. rvn = n.ru()
  345. case valueTypeFloat:
  346. rvn = n.rf()
  347. case valueTypeBool:
  348. rvn = n.rb()
  349. case valueTypeString, valueTypeSymbol:
  350. rvn = n.rs()
  351. case valueTypeBytes:
  352. rvn = n.rl()
  353. case valueTypeTime:
  354. rvn = n.rt()
  355. default:
  356. panicv.errorf("kInterfaceNaked: unexpected valueType: %d", n.v)
  357. }
  358. return
  359. }
  360. func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
  361. // Note:
  362. // A consequence of how kInterface works, is that
  363. // if an interface already contains something, we try
  364. // to decode into what was there before.
  365. // We do not replace with a generic value (as got from decodeNaked).
  366. // every interface passed here MUST be settable.
  367. var rvn reflect.Value
  368. if rvisnil(rv) || d.h.InterfaceReset {
  369. // check if mapping to a type: if so, initialize it and move on
  370. rvn = d.h.intf2impl(f.ti.rtid)
  371. if rvn.IsValid() {
  372. rv.Set(rvn)
  373. } else {
  374. rvn = d.kInterfaceNaked(f)
  375. if rvn.IsValid() {
  376. rv.Set(rvn)
  377. } else if d.h.InterfaceReset {
  378. // reset to zero value based on current type in there.
  379. rv.Set(reflect.Zero(rv.Elem().Type()))
  380. }
  381. return
  382. }
  383. } else {
  384. // now we have a non-nil interface value, meaning it contains a type
  385. rvn = rv.Elem()
  386. }
  387. if d.d.TryDecodeAsNil() {
  388. rv.Set(reflect.Zero(rvn.Type()))
  389. return
  390. }
  391. // Note: interface{} is settable, but underlying type may not be.
  392. // Consequently, we MAY have to create a decodable value out of the underlying value,
  393. // decode into it, and reset the interface itself.
  394. // fmt.Printf(">>>> kInterface: rvn type: %v, rv type: %v\n", rvn.Type(), rv.Type())
  395. rvn2, canDecode := isDecodeable(rvn)
  396. if canDecode {
  397. d.decodeValue(rvn2, nil)
  398. return
  399. }
  400. rvn2 = reflect.New(rvn.Type()).Elem()
  401. rvn2.Set(rvn)
  402. d.decodeValue(rvn2, nil)
  403. rv.Set(rvn2)
  404. }
  405. func decStructFieldKey(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) {
  406. // use if-else-if, not switch (which compiles to binary-search)
  407. // since keyType is typically valueTypeString, branch prediction is pretty good.
  408. if keyType == valueTypeString {
  409. rvkencname = dd.DecodeStringAsBytes()
  410. } else if keyType == valueTypeInt {
  411. rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10)
  412. } else if keyType == valueTypeUint {
  413. rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10)
  414. } else if keyType == valueTypeFloat {
  415. rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64)
  416. } else {
  417. rvkencname = dd.DecodeStringAsBytes()
  418. }
  419. return rvkencname
  420. }
  421. func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  422. fti := f.ti
  423. dd := d.d
  424. sfn := structFieldNode{v: rv, update: true}
  425. ctyp := dd.ContainerType()
  426. var mf MissingFielder
  427. if fti.mf {
  428. mf = rv2i(rv).(MissingFielder)
  429. } else if fti.mfp {
  430. mf = rv2i(rv.Addr()).(MissingFielder)
  431. }
  432. if ctyp == valueTypeMap {
  433. containerLen := d.mapStart()
  434. if containerLen == 0 {
  435. d.mapEnd()
  436. return
  437. }
  438. tisfi := fti.sfiSort
  439. hasLen := containerLen >= 0
  440. var rvkencname []byte
  441. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  442. d.mapElemKey()
  443. rvkencname = decStructFieldKey(dd, fti.keyType, &d.b)
  444. d.mapElemValue()
  445. if k := fti.indexForEncName(rvkencname); k > -1 {
  446. si := tisfi[k]
  447. if dd.TryDecodeAsNil() {
  448. si.setToZeroValue(rv)
  449. } else {
  450. d.decodeValue(sfn.field(si), nil)
  451. }
  452. } else if mf != nil {
  453. // store rvkencname in new []byte, as it previously shares Decoder.b, which is used in decode
  454. name2 := rvkencname
  455. rvkencname = make([]byte, len(rvkencname))
  456. copy(rvkencname, name2)
  457. var f interface{}
  458. d.decode(&f)
  459. if !mf.CodecMissingField(rvkencname, f) && d.h.ErrorIfNoField {
  460. d.errorf("no matching struct field found when decoding stream map with key: %s ",
  461. stringView(rvkencname))
  462. }
  463. } else {
  464. d.structFieldNotFound(-1, stringView(rvkencname))
  465. }
  466. // keepAlive4StringView(rvkencnameB) // not needed, as reference is outside loop
  467. }
  468. d.mapEnd()
  469. } else if ctyp == valueTypeArray {
  470. containerLen := d.arrayStart()
  471. if containerLen == 0 {
  472. d.arrayEnd()
  473. return
  474. }
  475. // Not much gain from doing it two ways for array.
  476. // Arrays are not used as much for structs.
  477. hasLen := containerLen >= 0
  478. var checkbreak bool
  479. for j, si := range fti.sfiSrc {
  480. if hasLen && j == containerLen {
  481. break
  482. }
  483. if !hasLen && dd.CheckBreak() {
  484. checkbreak = true
  485. break
  486. }
  487. d.arrayElem()
  488. if dd.TryDecodeAsNil() {
  489. si.setToZeroValue(rv)
  490. } else {
  491. d.decodeValue(sfn.field(si), nil)
  492. }
  493. }
  494. if (hasLen && containerLen > len(fti.sfiSrc)) || (!hasLen && !checkbreak) {
  495. // read remaining values and throw away
  496. for j := len(fti.sfiSrc); ; j++ {
  497. if (hasLen && j == containerLen) || (!hasLen && dd.CheckBreak()) {
  498. break
  499. }
  500. d.arrayElem()
  501. d.structFieldNotFound(j, "")
  502. }
  503. }
  504. d.arrayEnd()
  505. } else {
  506. d.errorstr(errstrOnlyMapOrArrayCanDecodeIntoStruct)
  507. return
  508. }
  509. }
  510. func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
  511. // A slice can be set from a map or array in stream.
  512. // This way, the order can be kept (as order is lost with map).
  513. frt := f.ti.rt
  514. if f.seq == seqTypeChan && f.ti.chandir&uint8(reflect.SendDir) == 0 {
  515. d.errorf("receive-only channel cannot be decoded")
  516. }
  517. dd := d.d
  518. rtelem0 := f.ti.elem
  519. ctyp := dd.ContainerType()
  520. if ctyp == valueTypeBytes || ctyp == valueTypeString {
  521. // you can only decode bytes or string in the stream into a slice or array of bytes
  522. if !(f.ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) {
  523. d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", frt)
  524. }
  525. if f.seq == seqTypeChan {
  526. bs2 := dd.DecodeBytes(nil, true)
  527. irv := rv2i(rv)
  528. ch, ok := irv.(chan<- byte)
  529. if !ok {
  530. ch = irv.(chan byte)
  531. }
  532. for _, b := range bs2 {
  533. ch <- b
  534. }
  535. } else {
  536. rvbs := rv.Bytes()
  537. bs2 := dd.DecodeBytes(rvbs, false)
  538. // if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) {
  539. if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
  540. if rv.CanSet() {
  541. rv.SetBytes(bs2)
  542. } else if len(rvbs) > 0 && len(bs2) > 0 {
  543. copy(rvbs, bs2)
  544. }
  545. }
  546. }
  547. return
  548. }
  549. // array := f.seq == seqTypeChan
  550. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map)
  551. // an array can never return a nil slice. so no need to check f.array here.
  552. if containerLenS == 0 {
  553. if rv.CanSet() {
  554. if f.seq == seqTypeSlice {
  555. if rvisnil(rv) {
  556. rv.Set(reflect.MakeSlice(frt, 0, 0))
  557. } else {
  558. rvssetlen(rv, 0)
  559. }
  560. } else if f.seq == seqTypeChan {
  561. if rvisnil(rv) {
  562. rv.Set(reflect.MakeChan(frt, 0))
  563. }
  564. }
  565. }
  566. slh.End()
  567. return
  568. }
  569. rtelem0Size := int(rtelem0.Size())
  570. rtElem0Kind := rtelem0.Kind()
  571. rtelem0Mut := !isImmutableKind(rtElem0Kind)
  572. rtelem := rtelem0
  573. rtelemkind := rtelem.Kind()
  574. for rtelemkind == reflect.Ptr {
  575. rtelem = rtelem.Elem()
  576. rtelemkind = rtelem.Kind()
  577. }
  578. var fn *codecFn
  579. var rvCanset = rv.CanSet()
  580. var rvChanged bool
  581. var rv0 = rv
  582. var rv9 reflect.Value
  583. rvlen := rv.Len()
  584. rvcap := rv.Cap()
  585. hasLen := containerLenS > 0
  586. if hasLen && f.seq == seqTypeSlice {
  587. if containerLenS > rvcap {
  588. oldRvlenGtZero := rvlen > 0
  589. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size()))
  590. if rvlen <= rvcap {
  591. if rvCanset {
  592. rvssetlen(rv, rvlen)
  593. }
  594. } else if rvCanset {
  595. rv = reflect.MakeSlice(frt, rvlen, rvlen)
  596. rvcap = rvlen
  597. rvChanged = true
  598. } else {
  599. d.errorf("cannot decode into non-settable slice")
  600. }
  601. if rvChanged && oldRvlenGtZero && rtelem0Mut { // !isImmutableKind(rtelem0.Kind()) {
  602. reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
  603. }
  604. } else if containerLenS != rvlen {
  605. rvlen = containerLenS
  606. if rvCanset {
  607. rvssetlen(rv, rvlen)
  608. }
  609. // else {
  610. // rv = rv.Slice(0, rvlen)
  611. // rvChanged = true
  612. // d.errorf("cannot decode into non-settable slice")
  613. // }
  614. }
  615. }
  616. // consider creating new element once, and just decoding into it.
  617. var rtelem0Zero reflect.Value
  618. var rtelem0ZeroValid bool
  619. var decodeAsNil bool
  620. var j int
  621. for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ {
  622. if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rvisnil(rv) {
  623. if hasLen {
  624. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size)
  625. } else if f.seq == seqTypeSlice {
  626. rvlen = decDefSliceCap
  627. } else {
  628. rvlen = decDefChanCap
  629. }
  630. if rvCanset {
  631. if f.seq == seqTypeSlice {
  632. rv = reflect.MakeSlice(frt, rvlen, rvlen)
  633. rvChanged = true
  634. } else { // chan
  635. rv = reflect.MakeChan(frt, rvlen)
  636. rvChanged = true
  637. }
  638. } else {
  639. d.errorf("cannot decode into non-settable slice")
  640. }
  641. }
  642. slh.ElemContainerState(j)
  643. decodeAsNil = dd.TryDecodeAsNil()
  644. if f.seq == seqTypeChan {
  645. if decodeAsNil {
  646. rv.Send(reflect.Zero(rtelem0))
  647. continue
  648. }
  649. if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rvisnil(rv9)) {
  650. rv9 = reflect.New(rtelem0).Elem()
  651. }
  652. if fn == nil {
  653. fn = d.h.fn(rtelem)
  654. }
  655. d.decodeValue(rv9, fn)
  656. rv.Send(rv9)
  657. } else {
  658. // if indefinite, etc, then expand the slice if necessary
  659. var decodeIntoBlank bool
  660. if j >= rvlen {
  661. if f.seq == seqTypeArray {
  662. d.arrayCannotExpand(rvlen, j+1)
  663. decodeIntoBlank = true
  664. } else { // if f.seq == seqTypeSlice
  665. // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // append logic + varargs
  666. var rvcap2 int
  667. var rvErrmsg2 string
  668. rv9, rvcap2, rvChanged, rvErrmsg2 =
  669. expandSliceRV(rv, frt, rvCanset, rtelem0Size, 1, rvlen, rvcap)
  670. if rvErrmsg2 != "" {
  671. d.errorf(rvErrmsg2)
  672. }
  673. rvlen++
  674. if rvChanged {
  675. rv = rv9
  676. rvcap = rvcap2
  677. }
  678. }
  679. }
  680. if decodeIntoBlank {
  681. if !decodeAsNil {
  682. d.swallow()
  683. }
  684. } else {
  685. rv9 = rv.Index(j)
  686. if d.h.SliceElementReset || decodeAsNil {
  687. if !rtelem0ZeroValid {
  688. rtelem0ZeroValid = true
  689. rtelem0Zero = reflect.Zero(rtelem0)
  690. }
  691. rv9.Set(rtelem0Zero)
  692. if decodeAsNil {
  693. continue
  694. }
  695. }
  696. if fn == nil {
  697. fn = d.h.fn(rtelem)
  698. }
  699. d.decodeValue(rv9, fn)
  700. }
  701. }
  702. }
  703. if f.seq == seqTypeSlice {
  704. if j < rvlen {
  705. if rv.CanSet() {
  706. rvssetlen(rv, j)
  707. } else if rvCanset {
  708. rv = rv.Slice(0, j)
  709. rvChanged = true
  710. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  711. rvlen = j
  712. } else if j == 0 && rvisnil(rv) {
  713. if rvCanset {
  714. rv = reflect.MakeSlice(frt, 0, 0)
  715. rvChanged = true
  716. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  717. }
  718. }
  719. slh.End()
  720. if rvChanged { // infers rvCanset=true, so it can be reset
  721. rv0.Set(rv)
  722. }
  723. }
  724. // func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
  725. // // d.decodeValueFn(rv.Slice(0, rv.Len()))
  726. // f.kSlice(rv.Slice(0, rv.Len()))
  727. // }
  728. func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
  729. dd := d.d
  730. containerLen := d.mapStart()
  731. ti := f.ti
  732. if rvisnil(rv) {
  733. rvlen := decInferLen(containerLen, d.h.MaxInitLen, int(ti.key.Size()+ti.elem.Size()))
  734. rv.Set(makeMapReflect(ti.rt, rvlen))
  735. }
  736. if containerLen == 0 {
  737. d.mapEnd()
  738. return
  739. }
  740. ktype, vtype := ti.key, ti.elem
  741. ktypeId := rt2id(ktype)
  742. vtypeKind := vtype.Kind()
  743. // ktypeKind := ktype.Kind()
  744. var keyFn, valFn *codecFn
  745. var ktypeLo, vtypeLo reflect.Type
  746. for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
  747. }
  748. for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
  749. }
  750. rvvMut := !isImmutableKind(vtypeKind)
  751. // we do a doMapGet if kind is mutable, and InterfaceReset=true if interface
  752. var doMapGet, doMapSet bool
  753. if !d.h.MapValueReset {
  754. if rvvMut {
  755. if vtypeKind == reflect.Interface {
  756. if !d.h.InterfaceReset {
  757. doMapGet = true
  758. }
  759. } else {
  760. doMapGet = true
  761. }
  762. }
  763. }
  764. var rvk, rvkn, rvv, rvvn, rvva, rvvz reflect.Value
  765. var rvvaSet bool
  766. rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk.
  767. ktypeIsString := ktypeId == stringTypId
  768. ktypeIsIntf := ktypeId == intfTypId
  769. hasLen := containerLen > 0
  770. var kstrbs []byte
  771. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  772. if j == 0 {
  773. // rvvz = reflect.Zero(vtype)
  774. // rvkz = reflect.Zero(ktype)
  775. if !rvkMut {
  776. rvkn = reflect.New(ktype).Elem() //, ktypeKind)
  777. }
  778. if !rvvMut {
  779. rvvn = reflect.New(vtype).Elem() //, vtypeKind)
  780. }
  781. }
  782. if rvkMut {
  783. rvk = reflect.New(ktype).Elem() //, ktypeKind)
  784. } else {
  785. rvk = rvkn
  786. }
  787. d.mapElemKey()
  788. if ktypeIsString {
  789. kstrbs = dd.DecodeStringAsBytes()
  790. rvk.SetString(stringView(kstrbs)) // NOTE: if doing an insert, use real string (not stringview)
  791. } else {
  792. if keyFn == nil {
  793. keyFn = d.h.fn(ktypeLo)
  794. }
  795. d.decodeValue(rvk, keyFn)
  796. }
  797. // special case if interface wrapping a byte array.
  798. if ktypeIsIntf {
  799. if rvk2 := rvk.Elem(); rvk2.IsValid() && rvk2.Type() == uint8SliceTyp {
  800. rvk.Set(reflect.ValueOf(d.string(rvk2.Bytes())))
  801. }
  802. // NOTE: consider failing early if map/slice/func
  803. }
  804. d.mapElemValue()
  805. // Brittle, but OK per TryDecodeAsNil() contract.
  806. // i.e. TryDecodeAsNil never shares slices with other decDriver procedures
  807. if dd.TryDecodeAsNil() {
  808. if d.h.DeleteOnNilMapValue {
  809. mapDelete(rv, rvk)
  810. } else {
  811. if ktypeIsString { // set to a real string (not string view)
  812. rvk.SetString(d.string(kstrbs))
  813. }
  814. if !rvvz.IsValid() {
  815. rvvz = reflect.Zero(vtype)
  816. }
  817. mapSet(rv, rvk, rvvz)
  818. }
  819. continue
  820. }
  821. doMapSet = true // set to false if u do a get, and its a non-nil pointer
  822. if doMapGet {
  823. if !rvvaSet {
  824. rvva = mapAddressableRV(vtype)
  825. rvvaSet = true
  826. }
  827. rvv = mapGet(rv, rvk, rvva) // reflect.Value{})
  828. if vtypeKind == reflect.Ptr {
  829. if rvv.IsValid() && !rvisnil(rvv) {
  830. doMapSet = false
  831. } else {
  832. rvv = reflect.New(vtype.Elem())
  833. }
  834. } else if rvv.IsValid() && vtypeKind == reflect.Interface && !rvisnil(rvv) {
  835. rvvn = reflect.New(vtype).Elem()
  836. rvvn.Set(rvv)
  837. rvv = rvvn
  838. } else if rvvMut {
  839. rvv = reflect.New(vtype).Elem()
  840. } else {
  841. rvv = rvvn
  842. }
  843. } else if rvvMut {
  844. rvv = reflect.New(vtype).Elem() //, vtypeKind)
  845. } else {
  846. rvv = rvvn
  847. }
  848. if valFn == nil {
  849. valFn = d.h.fn(vtypeLo)
  850. }
  851. // We MUST be done with the stringview of the key, BEFORE decoding the value (rvv)
  852. // so that we don't unknowingly reuse the rvk backing buffer during rvv decode.
  853. if doMapSet && ktypeIsString { // set to a real string (not string view)
  854. rvk.SetString(d.string(kstrbs))
  855. }
  856. d.decodeValue(rvv, valFn)
  857. if doMapSet {
  858. mapSet(rv, rvk, rvv)
  859. }
  860. // if ktypeIsString {
  861. // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop
  862. // }
  863. }
  864. d.mapEnd()
  865. }
  866. // decNaked is used to keep track of the primitives decoded.
  867. // Without it, we would have to decode each primitive and wrap it
  868. // in an interface{}, causing an allocation.
  869. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  870. // so we can rest assured that no other decoding happens while these
  871. // primitives are being decoded.
  872. //
  873. // maps and arrays are not handled by this mechanism.
  874. // However, RawExt is, and we accommodate for extensions that decode
  875. // RawExt from DecodeNaked, but need to decode the value subsequently.
  876. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
  877. //
  878. // However, decNaked also keeps some arrays of default maps and slices
  879. // used in DecodeNaked. This way, we can get a pointer to it
  880. // without causing a new heap allocation.
  881. //
  882. // kInterfaceNaked will ensure that there is no allocation for the common
  883. // uses.
  884. type decNaked struct {
  885. // r RawExt // used for RawExt, uint, []byte.
  886. // primitives below
  887. u uint64
  888. i int64
  889. f float64
  890. l []byte
  891. s string
  892. // ---- cpu cache line boundary?
  893. t time.Time
  894. b bool
  895. // state
  896. v valueType
  897. // _ [6]bool // padding
  898. // ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above
  899. //
  900. // _ [3]uint64 // padding
  901. }
  902. // func (n *decNaked) init() {
  903. // n.ru = reflect.ValueOf(&n.u).Elem()
  904. // n.ri = reflect.ValueOf(&n.i).Elem()
  905. // n.rf = reflect.ValueOf(&n.f).Elem()
  906. // n.rl = reflect.ValueOf(&n.l).Elem()
  907. // n.rs = reflect.ValueOf(&n.s).Elem()
  908. // n.rt = reflect.ValueOf(&n.t).Elem()
  909. // n.rb = reflect.ValueOf(&n.b).Elem()
  910. // // n.rr[] = reflect.ValueOf(&n.)
  911. // }
  912. // type decNakedPooler struct {
  913. // n *decNaked
  914. // nsp *sync.Pool
  915. // }
  916. // // naked must be called before each call to .DecodeNaked, as they will use it.
  917. // func (d *decNakedPooler) naked() *decNaked {
  918. // if d.n == nil {
  919. // // consider one of:
  920. // // - get from sync.Pool (if GC is frequent, there's no value here)
  921. // // - new alloc (safest. only init'ed if it a naked decode will be done)
  922. // // - field in Decoder (makes the Decoder struct very big)
  923. // // To support using a decoder where a DecodeNaked is not needed,
  924. // // we prefer #1 or #2.
  925. // // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool
  926. // // d.n.init()
  927. // var v interface{}
  928. // d.nsp, v = pool.decNaked()
  929. // d.n = v.(*decNaked)
  930. // }
  931. // return d.n
  932. // }
  933. // func (d *decNakedPooler) end() {
  934. // if d.n != nil {
  935. // // if n != nil, then nsp != nil (they are always set together)
  936. // d.nsp.Put(d.n)
  937. // d.n, d.nsp = nil, nil
  938. // }
  939. // }
  940. // type rtid2rv struct {
  941. // rtid uintptr
  942. // rv reflect.Value
  943. // }
  944. // Decoder reads and decodes an object from an input stream in a supported format.
  945. //
  946. // Decoder is NOT safe for concurrent use i.e. a Decoder cannot be used
  947. // concurrently in multiple goroutines.
  948. //
  949. // However, as Decoder could be allocation heavy to initialize, a Reset method is provided
  950. // so its state can be reused to decode new input streams repeatedly.
  951. // This is the idiomatic way to use.
  952. type Decoder struct {
  953. panicHdl
  954. // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
  955. // Try to put things that go together to fit within a cache line (8 words).
  956. d decDriver
  957. // NOTE: Decoder shouldn't call its read methods,
  958. // as the handler MAY need to do some coordination.
  959. // r *decReaderSwitch
  960. // bi *bufioDecReader
  961. // cache the mapTypeId and sliceTypeId for faster comparisons
  962. mtid uintptr
  963. stid uintptr
  964. jdec *jsonDecDriver
  965. h *BasicHandle
  966. hh Handle
  967. // ---- cpu cache line boundary?
  968. decReaderSwitch
  969. // ---- cpu cache line boundary?
  970. n decNaked
  971. // cr containerStateRecv
  972. // _ [4]uint8 // padding
  973. is map[string]string // used for interning strings
  974. err error
  975. // ---- cpu cache line boundary?
  976. // ---- writable fields during execution --- *try* to keep in sep cache line
  977. maxdepth int16
  978. depth int16
  979. c containerState
  980. _ [3]byte // padding
  981. b [decScratchByteArrayLen]byte // scratch buffer, used by Decoder and xxxDecDrivers
  982. // padding - false sharing help // modify 232 if Decoder struct changes.
  983. // _ [cacheLineSize - 232%cacheLineSize]byte
  984. }
  985. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  986. //
  987. // For efficiency, Users are encouraged to configure ReaderBufferSize on the handle
  988. // OR pass in a memory buffered reader (eg bufio.Reader, bytes.Buffer).
  989. func NewDecoder(r io.Reader, h Handle) *Decoder {
  990. d := newDecoder(h)
  991. d.Reset(r)
  992. return d
  993. }
  994. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  995. // from a byte slice with zero copying.
  996. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  997. d := newDecoder(h)
  998. d.ResetBytes(in)
  999. return d
  1000. }
  1001. // var defaultDecNaked decNaked
  1002. func newDecoder(h Handle) *Decoder {
  1003. d := &Decoder{h: basicHandle(h), err: errDecoderNotInitialized}
  1004. d.bytes = true
  1005. if useFinalizers {
  1006. runtime.SetFinalizer(d, (*Decoder).finalize)
  1007. }
  1008. // d.r = &d.decReaderSwitch
  1009. d.hh = h
  1010. d.be = h.isBinary()
  1011. // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
  1012. var jh *JsonHandle
  1013. jh, d.js = h.(*JsonHandle)
  1014. d.jdec = nil
  1015. if d.js {
  1016. d.jsms = jh.MapKeyAsString
  1017. }
  1018. d.esep = d.hh.hasElemSeparators()
  1019. if d.h.InternString {
  1020. d.is = make(map[string]string, 32)
  1021. }
  1022. d.d = h.newDecDriver(d)
  1023. if d.js {
  1024. d.jdec = d.d.(*jsonDecDriver)
  1025. }
  1026. // d.cr, _ = d.d.(containerStateRecv)
  1027. return d
  1028. }
  1029. func (d *Decoder) r() *decReaderSwitch {
  1030. return &d.decReaderSwitch
  1031. }
  1032. func (d *Decoder) resetCommon() {
  1033. // d.r = &d.decReaderSwitch
  1034. d.d.reset()
  1035. d.err = nil
  1036. d.depth = 0
  1037. d.maxdepth = d.h.MaxDepth
  1038. if d.maxdepth <= 0 {
  1039. d.maxdepth = decDefMaxDepth
  1040. }
  1041. // reset all things which were cached from the Handle, but could change
  1042. d.mtid, d.stid = 0, 0
  1043. d.mtr, d.str = false, false
  1044. if d.h.MapType != nil {
  1045. d.mtid = rt2id(d.h.MapType)
  1046. d.mtr = fastpathAV.index(d.mtid) != -1
  1047. }
  1048. if d.h.SliceType != nil {
  1049. d.stid = rt2id(d.h.SliceType)
  1050. d.str = fastpathAV.index(d.stid) != -1
  1051. }
  1052. }
  1053. // Reset the Decoder with a new Reader to decode from,
  1054. // clearing all state from last run(s).
  1055. func (d *Decoder) Reset(r io.Reader) {
  1056. if r == nil {
  1057. return
  1058. }
  1059. d.bytes = false
  1060. // d.typ = entryTypeUnset
  1061. if d.h.ReaderBufferSize > 0 {
  1062. if d.bi == nil {
  1063. d.bi = new(bufioDecReader)
  1064. }
  1065. d.bi.reset(r, d.h.ReaderBufferSize)
  1066. // d.r = d.bi
  1067. // d.typ = entryTypeBufio
  1068. d.bufio = true
  1069. } else {
  1070. // d.ri.x = &d.b
  1071. // d.s = d.sa[:0]
  1072. if d.ri == nil {
  1073. d.ri = new(ioDecReader)
  1074. }
  1075. d.ri.reset(r)
  1076. // d.r = d.ri
  1077. // d.typ = entryTypeIo
  1078. d.bufio = false
  1079. }
  1080. d.resetCommon()
  1081. }
  1082. // ResetBytes resets the Decoder with a new []byte to decode from,
  1083. // clearing all state from last run(s).
  1084. func (d *Decoder) ResetBytes(in []byte) {
  1085. if in == nil {
  1086. return
  1087. }
  1088. d.bytes = true
  1089. d.bufio = false
  1090. // d.typ = entryTypeBytes
  1091. d.rb.reset(in)
  1092. // d.r = &d.rb
  1093. d.resetCommon()
  1094. }
  1095. func (d *Decoder) naked() *decNaked {
  1096. return &d.n
  1097. }
  1098. // Decode decodes the stream from reader and stores the result in the
  1099. // value pointed to by v. v cannot be a nil pointer. v can also be
  1100. // a reflect.Value of a pointer.
  1101. //
  1102. // Note that a pointer to a nil interface is not a nil pointer.
  1103. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  1104. // We will decode and store a value in that nil interface.
  1105. //
  1106. // Sample usages:
  1107. // // Decoding into a non-nil typed value
  1108. // var f float32
  1109. // err = codec.NewDecoder(r, handle).Decode(&f)
  1110. //
  1111. // // Decoding into nil interface
  1112. // var v interface{}
  1113. // dec := codec.NewDecoder(r, handle)
  1114. // err = dec.Decode(&v)
  1115. //
  1116. // When decoding into a nil interface{}, we will decode into an appropriate value based
  1117. // on the contents of the stream:
  1118. // - Numbers are decoded as float64, int64 or uint64.
  1119. // - Other values are decoded appropriately depending on the type:
  1120. // bool, string, []byte, time.Time, etc
  1121. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  1122. // Configurations exist on the Handle to override defaults
  1123. // (e.g. for MapType, SliceType and how to decode raw bytes).
  1124. //
  1125. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  1126. // type of the value. When a value is seen:
  1127. // - If an extension is registered for it, call that extension function
  1128. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  1129. // - Else decode it based on its reflect.Kind
  1130. //
  1131. // There are some special rules when decoding into containers (slice/array/map/struct).
  1132. // Decode will typically use the stream contents to UPDATE the container i.e. the values
  1133. // in these containers will not be zero'ed before decoding.
  1134. // - A map can be decoded from a stream map, by updating matching keys.
  1135. // - A slice can be decoded from a stream array,
  1136. // by updating the first n elements, where n is length of the stream.
  1137. // - A slice can be decoded from a stream map, by decoding as if
  1138. // it contains a sequence of key-value pairs.
  1139. // - A struct can be decoded from a stream map, by updating matching fields.
  1140. // - A struct can be decoded from a stream array,
  1141. // by updating fields as they occur in the struct (by index).
  1142. //
  1143. // This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update
  1144. // in place by default). However, the consequence of this is that values in slices or maps
  1145. // which are not zero'ed before hand, will have part of the prior values in place after decode
  1146. // if the stream doesn't contain an update for those parts.
  1147. //
  1148. // This in-place update can be disabled by configuring the MapValueReset and SliceElementReset
  1149. // decode options available on every handle.
  1150. //
  1151. // Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice,
  1152. // we reset the destination map or slice to a zero-length value.
  1153. //
  1154. // However, when decoding a stream nil, we reset the destination container
  1155. // to its "zero" value (e.g. nil for slice/map, etc).
  1156. //
  1157. // Note: we allow nil values in the stream anywhere except for map keys.
  1158. // A nil value in the encoded stream where a map key is expected is treated as an error.
  1159. func (d *Decoder) Decode(v interface{}) (err error) {
  1160. // tried to use closure, as runtime optimizes defer with no params.
  1161. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  1162. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  1163. // defer func() { d.deferred(&err) }()
  1164. // { x, y := d, &err; defer func() { x.deferred(y) }() }
  1165. if d.err != nil {
  1166. return d.err
  1167. }
  1168. if recoverPanicToErr {
  1169. defer func() {
  1170. if x := recover(); x != nil {
  1171. panicValToErr(d, x, &d.err)
  1172. if d.err != err {
  1173. err = d.err
  1174. }
  1175. }
  1176. }()
  1177. }
  1178. // defer d.deferred(&err)
  1179. d.mustDecode(v)
  1180. return
  1181. }
  1182. // MustDecode is like Decode, but panics if unable to Decode.
  1183. // This provides insight to the code location that triggered the error.
  1184. func (d *Decoder) MustDecode(v interface{}) {
  1185. if d.err != nil {
  1186. panic(d.err)
  1187. }
  1188. d.mustDecode(v)
  1189. }
  1190. // MustDecode is like Decode, but panics if unable to Decode.
  1191. // This provides insight to the code location that triggered the error.
  1192. func (d *Decoder) mustDecode(v interface{}) {
  1193. // TODO: Top-level: ensure that v is a pointer and not nil.
  1194. if d.bi == nil {
  1195. if d.d.TryDecodeAsNil() {
  1196. setZero(v)
  1197. } else {
  1198. d.decode(v)
  1199. }
  1200. d.d.atEndOfDecode()
  1201. return
  1202. }
  1203. if d.d.TryDecodeAsNil() {
  1204. setZero(v)
  1205. } else {
  1206. d.bi.calls++
  1207. d.decode(v)
  1208. d.bi.calls--
  1209. }
  1210. if d.bi.calls == 0 {
  1211. d.d.atEndOfDecode()
  1212. if !d.h.ExplicitRelease {
  1213. d.bi.release()
  1214. }
  1215. }
  1216. }
  1217. // func (d *Decoder) deferred(err1 *error) {
  1218. // if recoverPanicToErr {
  1219. // if x := recover(); x != nil {
  1220. // panicValToErr(d, x, err1)
  1221. // panicValToErr(d, x, &d.err)
  1222. // }
  1223. // }
  1224. // }
  1225. //go:noinline -- as it is run by finalizer
  1226. func (d *Decoder) finalize() {
  1227. d.Release()
  1228. }
  1229. // Release releases shared (pooled) resources.
  1230. //
  1231. // It is important to call Release() when done with a Decoder, so those resources
  1232. // are released instantly for use by subsequently created Decoders.
  1233. //
  1234. // By default, Release() is automatically called unless the option ExplicitRelease is set.
  1235. func (d *Decoder) Release() {
  1236. if d.bi != nil {
  1237. d.bi.release()
  1238. }
  1239. // d.decNakedPooler.end()
  1240. }
  1241. // // this is not a smart swallow, as it allocates objects and does unnecessary work.
  1242. // func (d *Decoder) swallowViaHammer() {
  1243. // var blank interface{}
  1244. // d.decodeValueNoFn(reflect.ValueOf(&blank).Elem())
  1245. // }
  1246. func (d *Decoder) swallow() {
  1247. // smarter decode that just swallows the content
  1248. dd := d.d
  1249. if dd.TryDecodeAsNil() {
  1250. return
  1251. }
  1252. switch dd.ContainerType() {
  1253. case valueTypeMap:
  1254. containerLen := d.mapStart()
  1255. hasLen := containerLen >= 0
  1256. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1257. // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break}
  1258. d.mapElemKey()
  1259. d.swallow()
  1260. d.mapElemValue()
  1261. d.swallow()
  1262. }
  1263. d.mapEnd()
  1264. case valueTypeArray:
  1265. containerLen := d.arrayStart()
  1266. hasLen := containerLen >= 0
  1267. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1268. d.arrayElem()
  1269. d.swallow()
  1270. }
  1271. d.arrayEnd()
  1272. case valueTypeBytes:
  1273. dd.DecodeBytes(d.b[:], true)
  1274. case valueTypeString:
  1275. dd.DecodeStringAsBytes()
  1276. default:
  1277. // these are all primitives, which we can get from decodeNaked
  1278. // if RawExt using Value, complete the processing.
  1279. n := d.naked()
  1280. dd.DecodeNaked()
  1281. if n.v == valueTypeExt && n.l == nil {
  1282. var v2 interface{}
  1283. d.decode(&v2)
  1284. }
  1285. }
  1286. }
  1287. func setZero(iv interface{}) {
  1288. if iv == nil || definitelyNil(iv) {
  1289. return
  1290. }
  1291. var canDecode bool
  1292. switch v := iv.(type) {
  1293. case *string:
  1294. *v = ""
  1295. case *bool:
  1296. *v = false
  1297. case *int:
  1298. *v = 0
  1299. case *int8:
  1300. *v = 0
  1301. case *int16:
  1302. *v = 0
  1303. case *int32:
  1304. *v = 0
  1305. case *int64:
  1306. *v = 0
  1307. case *uint:
  1308. *v = 0
  1309. case *uint8:
  1310. *v = 0
  1311. case *uint16:
  1312. *v = 0
  1313. case *uint32:
  1314. *v = 0
  1315. case *uint64:
  1316. *v = 0
  1317. case *float32:
  1318. *v = 0
  1319. case *float64:
  1320. *v = 0
  1321. case *[]uint8:
  1322. *v = nil
  1323. case *Raw:
  1324. *v = nil
  1325. case *time.Time:
  1326. *v = time.Time{}
  1327. case reflect.Value:
  1328. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  1329. v.Set(reflect.Zero(v.Type()))
  1330. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  1331. default:
  1332. if !fastpathDecodeSetZeroTypeSwitch(iv) {
  1333. v := reflect.ValueOf(iv)
  1334. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  1335. v.Set(reflect.Zero(v.Type()))
  1336. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  1337. }
  1338. }
  1339. }
  1340. func (d *Decoder) decode(iv interface{}) {
  1341. // a switch with only concrete types can be optimized.
  1342. // consequently, we deal with nil and interfaces outside the switch.
  1343. if iv == nil {
  1344. d.errorstr(errstrCannotDecodeIntoNil)
  1345. return
  1346. }
  1347. switch v := iv.(type) {
  1348. // case nil:
  1349. // case Selfer:
  1350. case reflect.Value:
  1351. v = d.ensureDecodeable(v)
  1352. d.decodeValue(v, nil)
  1353. case *string:
  1354. *v = string(d.d.DecodeStringAsBytes())
  1355. case *bool:
  1356. *v = d.d.DecodeBool()
  1357. case *int:
  1358. *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))
  1359. case *int8:
  1360. *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8))
  1361. case *int16:
  1362. *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16))
  1363. case *int32:
  1364. *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32))
  1365. case *int64:
  1366. *v = d.d.DecodeInt64()
  1367. case *uint:
  1368. *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))
  1369. case *uint8:
  1370. *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))
  1371. case *uint16:
  1372. *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))
  1373. case *uint32:
  1374. *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))
  1375. case *uint64:
  1376. *v = d.d.DecodeUint64()
  1377. case *float32:
  1378. *v = float32(d.decodeFloat32())
  1379. case *float64:
  1380. *v = d.d.DecodeFloat64()
  1381. case *[]uint8:
  1382. *v = d.d.DecodeBytes(*v, false)
  1383. case []uint8:
  1384. b := d.d.DecodeBytes(v, false)
  1385. if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) {
  1386. copy(v, b)
  1387. }
  1388. case *time.Time:
  1389. *v = d.d.DecodeTime()
  1390. case *Raw:
  1391. *v = d.rawBytes()
  1392. case *interface{}:
  1393. d.decodeValue(reflect.ValueOf(iv).Elem(), nil)
  1394. // d.decodeValueNotNil(reflect.ValueOf(iv).Elem())
  1395. default:
  1396. if v, ok := iv.(Selfer); ok {
  1397. v.CodecDecodeSelf(d)
  1398. } else if !fastpathDecodeTypeSwitch(iv, d) {
  1399. v := reflect.ValueOf(iv)
  1400. v = d.ensureDecodeable(v)
  1401. d.decodeValue(v, nil) // TODO: find a way to say: no fast path??? Not necessary???
  1402. // d.decodeValueFallback(v)
  1403. }
  1404. }
  1405. }
  1406. func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn) {
  1407. // If stream is not containing a nil value, then we can deref to the base
  1408. // non-pointer value, and decode into that.
  1409. var rvp reflect.Value
  1410. var rvpValid bool
  1411. if rv.Kind() == reflect.Ptr {
  1412. rvpValid = true
  1413. for {
  1414. if rvisnil(rv) {
  1415. rv.Set(reflect.New(rv.Type().Elem()))
  1416. }
  1417. rvp = rv
  1418. rv = rv.Elem()
  1419. if rv.Kind() != reflect.Ptr {
  1420. break
  1421. }
  1422. }
  1423. }
  1424. if fn == nil {
  1425. fn = d.h.fn(rv.Type())
  1426. }
  1427. if fn.i.addrD {
  1428. if rvpValid {
  1429. fn.fd(d, &fn.i, rvp)
  1430. } else if rv.CanAddr() {
  1431. fn.fd(d, &fn.i, rv.Addr())
  1432. } else if !fn.i.addrF {
  1433. fn.fd(d, &fn.i, rv)
  1434. } else {
  1435. d.errorf("cannot decode into a non-pointer value")
  1436. }
  1437. } else {
  1438. fn.fd(d, &fn.i, rv)
  1439. }
  1440. // return rv
  1441. }
  1442. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  1443. // NOTE: rvkencname may be a stringView, so don't pass it to another function.
  1444. if d.h.ErrorIfNoField {
  1445. if index >= 0 {
  1446. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  1447. return
  1448. } else if rvkencname != "" {
  1449. d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
  1450. return
  1451. }
  1452. }
  1453. d.swallow()
  1454. }
  1455. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  1456. if d.h.ErrorIfNoArrayExpand {
  1457. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  1458. }
  1459. }
  1460. func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) {
  1461. switch rv.Kind() {
  1462. case reflect.Array:
  1463. return rv, rv.CanAddr()
  1464. case reflect.Ptr:
  1465. if !rvisnil(rv) {
  1466. return rv.Elem(), true
  1467. }
  1468. case reflect.Slice, reflect.Chan, reflect.Map:
  1469. if !rvisnil(rv) {
  1470. return rv, true
  1471. }
  1472. }
  1473. return
  1474. }
  1475. func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) {
  1476. // decode can take any reflect.Value that is a inherently addressable i.e.
  1477. // - array
  1478. // - non-nil chan (we will SEND to it)
  1479. // - non-nil slice (we will set its elements)
  1480. // - non-nil map (we will put into it)
  1481. // - non-nil pointer (we can "update" it)
  1482. rv2, canDecode := isDecodeable(rv)
  1483. if canDecode {
  1484. return
  1485. }
  1486. if !rv.IsValid() {
  1487. d.errorstr(errstrCannotDecodeIntoNil)
  1488. return
  1489. }
  1490. if !rv.CanInterface() {
  1491. d.errorf("cannot decode into a value without an interface: %v", rv)
  1492. return
  1493. }
  1494. rvi := rv2i(rv)
  1495. rvk := rv.Kind()
  1496. d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi)
  1497. return
  1498. }
  1499. func (d *Decoder) depthIncr() {
  1500. d.depth++
  1501. if d.depth >= d.maxdepth {
  1502. panic(errMaxDepthExceeded)
  1503. }
  1504. }
  1505. func (d *Decoder) depthDecr() {
  1506. d.depth--
  1507. }
  1508. // Possibly get an interned version of a string
  1509. //
  1510. // This should mostly be used for map keys, where the key type is string.
  1511. // This is because keys of a map/struct are typically reused across many objects.
  1512. func (d *Decoder) string(v []byte) (s string) {
  1513. if d.is == nil {
  1514. return string(v) // don't return stringView, as we need a real string here.
  1515. }
  1516. s, ok := d.is[string(v)] // no allocation here, per go implementation
  1517. if !ok {
  1518. s = string(v) // new allocation here
  1519. d.is[s] = s
  1520. }
  1521. return s
  1522. }
  1523. // nextValueBytes returns the next value in the stream as a set of bytes.
  1524. func (d *Decoder) nextValueBytes() (bs []byte) {
  1525. d.d.uncacheRead()
  1526. d.r().track()
  1527. d.swallow()
  1528. bs = d.r().stopTrack()
  1529. return
  1530. }
  1531. func (d *Decoder) rawBytes() []byte {
  1532. // ensure that this is not a view into the bytes
  1533. // i.e. make new copy always.
  1534. bs := d.nextValueBytes()
  1535. bs2 := make([]byte, len(bs))
  1536. copy(bs2, bs)
  1537. return bs2
  1538. }
  1539. func (d *Decoder) wrapErr(v interface{}, err *error) {
  1540. *err = decodeError{codecError: codecError{name: d.hh.Name(), err: v}, pos: int(d.r().numread())}
  1541. }
  1542. // NumBytesRead returns the number of bytes read
  1543. func (d *Decoder) NumBytesRead() int {
  1544. return int(d.r().numread())
  1545. }
  1546. // decodeFloat32 will delegate to an appropriate DecodeFloat32 implementation (if exists),
  1547. // else if will call DecodeFloat64 and ensure the value doesn't overflow.
  1548. //
  1549. // Note that we return float64 to reduce unnecessary conversions
  1550. func (d *Decoder) decodeFloat32() float32 {
  1551. if d.js {
  1552. return d.jdec.DecodeFloat32() // custom implementation for 32-bit
  1553. }
  1554. return float32(chkOvf.Float32V(d.d.DecodeFloat64()))
  1555. }
  1556. // ---- container tracking
  1557. // Note: We update the .c after calling the callback.
  1558. // This way, the callback can know what the last status was.
  1559. func (d *Decoder) mapStart() (v int) {
  1560. v = d.d.ReadMapStart()
  1561. d.depthIncr()
  1562. d.c = containerMapStart
  1563. return
  1564. }
  1565. func (d *Decoder) mapElemKey() {
  1566. if d.js {
  1567. d.jdec.ReadMapElemKey()
  1568. }
  1569. d.c = containerMapKey
  1570. }
  1571. func (d *Decoder) mapElemValue() {
  1572. if d.js {
  1573. d.jdec.ReadMapElemValue()
  1574. }
  1575. d.c = containerMapValue
  1576. }
  1577. func (d *Decoder) mapEnd() {
  1578. d.d.ReadMapEnd()
  1579. d.depthDecr()
  1580. d.c = containerMapEnd
  1581. d.c = 0
  1582. }
  1583. func (d *Decoder) arrayStart() (v int) {
  1584. v = d.d.ReadArrayStart()
  1585. d.depthIncr()
  1586. d.c = containerArrayStart
  1587. return
  1588. }
  1589. func (d *Decoder) arrayElem() {
  1590. if d.js {
  1591. d.jdec.ReadArrayElem()
  1592. }
  1593. d.c = containerArrayElem
  1594. }
  1595. func (d *Decoder) arrayEnd() {
  1596. d.d.ReadArrayEnd()
  1597. d.depthDecr()
  1598. d.c = containerArrayEnd
  1599. d.c = 0
  1600. }
  1601. func (d *Decoder) interfaceExtConvertAndDecode(v interface{}, ext Ext) {
  1602. // var v interface{} = ext.ConvertExt(rv)
  1603. // d.d.decode(&v)
  1604. // ext.UpdateExt(rv, v)
  1605. // assume v is a pointer:
  1606. // - if struct|array, pass as is to ConvertExt
  1607. // - else make it non-addressable and pass to ConvertExt
  1608. // - make return value from ConvertExt addressable
  1609. // - decode into it
  1610. // - return the interface for passing into UpdateExt.
  1611. // - interface should be a pointer if struct|array, else a value
  1612. var s interface{}
  1613. rv := reflect.ValueOf(v)
  1614. rv2 := rv.Elem()
  1615. rvk := rv2.Kind()
  1616. if rvk == reflect.Struct || rvk == reflect.Array {
  1617. s = ext.ConvertExt(v)
  1618. } else {
  1619. s = ext.ConvertExt(rv2i(rv2))
  1620. }
  1621. rv = reflect.ValueOf(s)
  1622. if !rv.CanAddr() {
  1623. if rv.Kind() == reflect.Ptr {
  1624. rv2 = reflect.New(rv.Type().Elem())
  1625. rv2.Set(rv)
  1626. } else {
  1627. rv2 = reflect.New(rv.Type()).Elem()
  1628. rv2.Set(rv)
  1629. }
  1630. rv = rv2
  1631. }
  1632. d.decodeValue(rv, nil)
  1633. ext.UpdateExt(v, rv2i(rv))
  1634. }
  1635. func (d *Decoder) sideDecode(v interface{}, bs []byte) {
  1636. rv := baseRV(v)
  1637. NewDecoderBytes(bs, d.hh).decodeValue(rv, d.h.fnNoExt(rv.Type()))
  1638. }
  1639. // --------------------------------------------------
  1640. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  1641. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  1642. type decSliceHelper struct {
  1643. d *Decoder
  1644. ct valueType
  1645. array bool
  1646. }
  1647. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  1648. x.ct = d.d.ContainerType()
  1649. x.d = d
  1650. switch x.ct {
  1651. case valueTypeArray:
  1652. x.array = true
  1653. clen = d.arrayStart()
  1654. case valueTypeMap:
  1655. clen = d.mapStart() * 2
  1656. default:
  1657. d.errorf("only encoded map or array can be decoded into a slice (%d)", x.ct)
  1658. }
  1659. return
  1660. }
  1661. func (x decSliceHelper) End() {
  1662. if x.array {
  1663. x.d.arrayEnd()
  1664. } else {
  1665. x.d.mapEnd()
  1666. }
  1667. }
  1668. func (x decSliceHelper) ElemContainerState(index int) {
  1669. if x.array {
  1670. x.d.arrayElem()
  1671. } else if index%2 == 0 {
  1672. x.d.mapElemKey()
  1673. } else {
  1674. x.d.mapElemValue()
  1675. }
  1676. }
  1677. func decByteSlice(r *decReaderSwitch, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  1678. if clen == 0 {
  1679. return zeroByteSlice
  1680. }
  1681. if len(bs) == clen {
  1682. bsOut = bs
  1683. r.readb(bsOut)
  1684. } else if cap(bs) >= clen {
  1685. bsOut = bs[:clen]
  1686. r.readb(bsOut)
  1687. } else {
  1688. // bsOut = make([]byte, clen)
  1689. len2 := decInferLen(clen, maxInitLen, 1)
  1690. bsOut = make([]byte, len2)
  1691. r.readb(bsOut)
  1692. for len2 < clen {
  1693. len3 := decInferLen(clen-len2, maxInitLen, 1)
  1694. bs3 := bsOut
  1695. bsOut = make([]byte, len2+len3)
  1696. copy(bsOut, bs3)
  1697. r.readb(bsOut[len2:])
  1698. len2 += len3
  1699. }
  1700. }
  1701. return
  1702. }
  1703. // func decByteSliceZeroCopy(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  1704. // if _, ok := r.(*bytesDecReader); ok && clen <= maxInitLen {
  1705. // return r.readx(clen)
  1706. // }
  1707. // return decByteSlice(r, clen, maxInitLen, bs)
  1708. // }
  1709. func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
  1710. if xlen := len(in); xlen > 0 {
  1711. if isBytesReader || xlen <= scratchByteArrayLen {
  1712. if cap(dest) >= xlen {
  1713. out = dest[:xlen]
  1714. } else {
  1715. out = make([]byte, xlen)
  1716. }
  1717. copy(out, in)
  1718. return
  1719. }
  1720. }
  1721. return in
  1722. }
  1723. // decInferLen will infer a sensible length, given the following:
  1724. // - clen: length wanted.
  1725. // - maxlen: max length to be returned.
  1726. // if <= 0, it is unset, and we infer it based on the unit size
  1727. // - unit: number of bytes for each element of the collection
  1728. func decInferLen(clen, maxlen, unit int) (rvlen int) {
  1729. const maxLenIfUnset = 8 // 64
  1730. // handle when maxlen is not set i.e. <= 0
  1731. // clen==0: use 0
  1732. // maxlen<=0, clen<0: use default
  1733. // maxlen> 0, clen<0: use default
  1734. // maxlen<=0, clen>0: infer maxlen, and cap on it
  1735. // maxlen> 0, clen>0: cap at maxlen
  1736. if clen == 0 {
  1737. return
  1738. }
  1739. if clen < 0 {
  1740. return maxLenIfUnset
  1741. }
  1742. if unit == 0 {
  1743. return clen
  1744. }
  1745. if maxlen <= 0 {
  1746. // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
  1747. // maxlen = 256 * 1024 / unit
  1748. // if maxlen < (4 * 1024) {
  1749. // maxlen = 4 * 1024
  1750. // }
  1751. if unit < (256 / 4) {
  1752. maxlen = 256 * 1024 / unit
  1753. } else {
  1754. maxlen = 4 * 1024
  1755. }
  1756. // if maxlen > maxLenIfUnset {
  1757. // maxlen = maxLenIfUnset
  1758. // }
  1759. }
  1760. if clen > maxlen {
  1761. rvlen = maxlen
  1762. } else {
  1763. rvlen = clen
  1764. }
  1765. return
  1766. }
  1767. func expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) (
  1768. s2 reflect.Value, scap2 int, changed bool, err string) {
  1769. l1 := slen + num // new slice length
  1770. if l1 < slen {
  1771. err = errmsgExpandSliceOverflow
  1772. return
  1773. }
  1774. if l1 <= scap {
  1775. if s.CanSet() {
  1776. rvssetlen(s, l1)
  1777. } else if canChange {
  1778. s2 = s.Slice(0, l1)
  1779. scap2 = scap
  1780. changed = true
  1781. } else {
  1782. err = errmsgExpandSliceCannotChange
  1783. return
  1784. }
  1785. return
  1786. }
  1787. if !canChange {
  1788. err = errmsgExpandSliceCannotChange
  1789. return
  1790. }
  1791. scap2 = growCap(scap, stElemSize, num)
  1792. s2 = reflect.MakeSlice(st, l1, scap2)
  1793. changed = true
  1794. reflect.Copy(s2, s)
  1795. return
  1796. }
  1797. func decReadFull(r io.Reader, bs []byte) (n uint, err error) {
  1798. var nn int
  1799. for n < uint(len(bs)) && err == nil {
  1800. nn, err = r.Read(bs[n:])
  1801. if nn > 0 {
  1802. if err == io.EOF {
  1803. // leave EOF for next time
  1804. err = nil
  1805. }
  1806. n += uint(nn)
  1807. }
  1808. }
  1809. // do not do this - it serves no purpose
  1810. // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
  1811. return
  1812. }
  1813. func decNakedReadRawBytes(dr decDriver, d *Decoder, n *decNaked, rawToString bool) {
  1814. if rawToString {
  1815. n.v = valueTypeString
  1816. n.s = string(dr.DecodeBytes(d.b[:], true))
  1817. } else {
  1818. n.v = valueTypeBytes
  1819. n.l = dr.DecodeBytes(nil, false)
  1820. }
  1821. }