decode.go 63 KB

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