decode.go 60 KB

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