decode.go 55 KB

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