decode.go 64 KB

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