decode.go 54 KB

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