decode.go 63 KB

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