decode.go 63 KB

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