decode.go 63 KB

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