decode.go 64 KB

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