decode.go 54 KB

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