decode.go 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109
  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. "reflect"
  10. "runtime"
  11. "strconv"
  12. "time"
  13. )
  14. // Some tagging information for error messages.
  15. const (
  16. msgBadDesc = "unrecognized descriptor byte"
  17. // msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v"
  18. )
  19. const (
  20. decDefMaxDepth = 1024 // maximum depth
  21. decDefSliceCap = 8
  22. decDefChanCap = 64 // should be large, as cap cannot be expanded
  23. decScratchByteArrayLen = cacheLineSize // + (8 * 2) // - (8 * 1)
  24. )
  25. var (
  26. errstrOnlyMapOrArrayCanDecodeIntoStruct = "only encoded map or array can be decoded into a struct"
  27. errstrCannotDecodeIntoNil = "cannot decode into nil"
  28. errmsgExpandSliceOverflow = "expand slice: slice overflow"
  29. errmsgExpandSliceCannotChange = "expand slice: cannot change"
  30. errDecoderNotInitialized = errors.New("Decoder not initialized")
  31. errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read")
  32. errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read")
  33. errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown")
  34. errMaxDepthExceeded = errors.New("maximum decoding depth exceeded")
  35. )
  36. /*
  37. // decReader abstracts the reading source, allowing implementations that can
  38. // read from an io.Reader or directly off a byte slice with zero-copying.
  39. //
  40. // Deprecated: Use decReaderSwitch instead.
  41. type decReader interface {
  42. unreadn1()
  43. // readx will use the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR
  44. // just return a view of the []byte being decoded from.
  45. // Ensure you call detachZeroCopyBytes later if this needs to be sent outside codec control.
  46. readx(n int) []byte
  47. readb([]byte)
  48. readn1() uint8
  49. numread() uint // number of bytes read
  50. track()
  51. stopTrack() []byte
  52. // skip will skip any byte that matches, and return the first non-matching byte
  53. skip(accept *bitset256) (token byte)
  54. // readTo will read any byte that matches, stopping once no-longer matching.
  55. readTo(in []byte, accept *bitset256) (out []byte)
  56. // readUntil will read, only stopping once it matches the 'stop' byte.
  57. readUntil(in []byte, stop byte) (out []byte)
  58. }
  59. */
  60. type decDriver interface {
  61. // this will check if the next token is a break.
  62. CheckBreak() bool
  63. // TryDecodeAsNil tries to decode as nil.
  64. // Note: TryDecodeAsNil should be careful not to share any temporary []byte with
  65. // the rest of the decDriver. This is because sometimes, we optimize by holding onto
  66. // a transient []byte, and ensuring the only other call we make to the decDriver
  67. // during that time is maybe a TryDecodeAsNil() call.
  68. TryDecodeAsNil() bool
  69. // ContainerType returns one of: Bytes, String, Nil, Slice or Map. Return unSet if not known.
  70. ContainerType() (vt valueType)
  71. // IsBuiltinType(rt uintptr) bool
  72. // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt.
  73. // For maps and arrays, it will not do the decoding in-band, but will signal
  74. // the decoder, so that is done later, by setting the decNaked.valueType field.
  75. //
  76. // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
  77. // for extensions, DecodeNaked must read the tag and the []byte if it exists.
  78. // if the []byte is not read, then kInterfaceNaked will treat it as a Handle
  79. // that stores the subsequent value in-band, and complete reading the RawExt.
  80. //
  81. // extensions should also use readx to decode them, for efficiency.
  82. // kInterface will extract the detached byte slice if it has to pass it outside its realm.
  83. DecodeNaked()
  84. // Deprecated: use DecodeInt64 and DecodeUint64 instead
  85. // DecodeInt(bitsize uint8) (i int64)
  86. // DecodeUint(bitsize uint8) (ui uint64)
  87. DecodeInt64() (i int64)
  88. DecodeUint64() (ui uint64)
  89. DecodeFloat64() (f float64)
  90. DecodeBool() (b bool)
  91. // DecodeString can also decode symbols.
  92. // It looks redundant as DecodeBytes is available.
  93. // However, some codecs (e.g. binc) support symbols and can
  94. // return a pre-stored string value, meaning that it can bypass
  95. // the cost of []byte->string conversion.
  96. DecodeString() (s string)
  97. DecodeStringAsBytes() (v []byte)
  98. // DecodeBytes may be called directly, without going through reflection.
  99. // Consequently, it must be designed to handle possible nil.
  100. DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte)
  101. // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
  102. // decodeExt will decode into a *RawExt or into an extension.
  103. DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64)
  104. // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
  105. DecodeTime() (t time.Time)
  106. ReadArrayStart() int
  107. ReadArrayElem()
  108. ReadArrayEnd()
  109. ReadMapStart() int
  110. ReadMapElemKey()
  111. ReadMapElemValue()
  112. ReadMapEnd()
  113. reset()
  114. uncacheRead()
  115. }
  116. type decodeError struct {
  117. codecError
  118. pos int
  119. }
  120. func (d decodeError) Error() string {
  121. return fmt.Sprintf("%s decode error [pos %d]: %v", d.name, d.pos, d.err)
  122. }
  123. type decDriverNoopContainerReader struct{}
  124. func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { return }
  125. func (x decDriverNoopContainerReader) ReadArrayElem() {}
  126. func (x decDriverNoopContainerReader) ReadArrayEnd() {}
  127. func (x decDriverNoopContainerReader) ReadMapStart() (v int) { return }
  128. func (x decDriverNoopContainerReader) ReadMapElemKey() {}
  129. func (x decDriverNoopContainerReader) ReadMapElemValue() {}
  130. func (x decDriverNoopContainerReader) ReadMapEnd() {}
  131. func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return }
  132. // func (x decNoSeparator) uncacheRead() {}
  133. // DecodeOptions captures configuration options during decode.
  134. type DecodeOptions struct {
  135. // MapType specifies type to use during schema-less decoding of a map in the stream.
  136. // If nil (unset), we default to map[string]interface{} iff json handle and MapStringAsKey=true,
  137. // else map[interface{}]interface{}.
  138. MapType reflect.Type
  139. // SliceType specifies type to use during schema-less decoding of an array in the stream.
  140. // If nil (unset), we default to []interface{} for all formats.
  141. SliceType reflect.Type
  142. // MaxInitLen defines the maxinum initial length that we "make" a collection
  143. // (string, slice, map, chan). If 0 or negative, we default to a sensible value
  144. // based on the size of an element in the collection.
  145. //
  146. // For example, when decoding, a stream may say that it has 2^64 elements.
  147. // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash.
  148. // Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
  149. MaxInitLen int
  150. // ReaderBufferSize is the size of the buffer used when reading.
  151. //
  152. // if > 0, we use a smart buffer internally for performance purposes.
  153. ReaderBufferSize int
  154. // MaxDepth defines the maximum depth when decoding nested
  155. // maps and slices. If 0 or negative, we default to a suitably large number (currently 1024).
  156. MaxDepth int16
  157. // If ErrorIfNoField, return an error when decoding a map
  158. // from a codec stream into a struct, and no matching struct field is found.
  159. ErrorIfNoField bool
  160. // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
  161. // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
  162. // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
  163. ErrorIfNoArrayExpand bool
  164. // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
  165. SignedInteger bool
  166. // MapValueReset controls how we decode into a map value.
  167. //
  168. // By default, we MAY retrieve the mapping for a key, and then decode into that.
  169. // However, especially with big maps, that retrieval may be expensive and unnecessary
  170. // if the stream already contains all that is necessary to recreate the value.
  171. //
  172. // If true, we will never retrieve the previous mapping,
  173. // but rather decode into a new value and set that in the map.
  174. //
  175. // If false, we will retrieve the previous mapping if necessary e.g.
  176. // the previous mapping is a pointer, or is a struct or array with pre-set state,
  177. // or is an interface.
  178. MapValueReset bool
  179. // SliceElementReset: on decoding a slice, reset the element to a zero value first.
  180. //
  181. // concern: if the slice already contained some garbage, we will decode into that garbage.
  182. SliceElementReset bool
  183. // InterfaceReset controls how we decode into an interface.
  184. //
  185. // By default, when we see a field that is an interface{...},
  186. // or a map with interface{...} value, we will attempt decoding into the
  187. // "contained" value.
  188. //
  189. // However, this prevents us from reading a string into an interface{}
  190. // that formerly contained a number.
  191. //
  192. // If true, we will decode into a new "blank" value, and set that in the interface.
  193. // If false, we will decode into whatever is contained in the interface.
  194. InterfaceReset bool
  195. // InternString controls interning of strings during decoding.
  196. //
  197. // Some handles, e.g. json, typically will read map keys as strings.
  198. // If the set of keys are finite, it may help reduce allocation to
  199. // look them up from a map (than to allocate them afresh).
  200. //
  201. // Note: Handles will be smart when using the intern functionality.
  202. // Every string should not be interned.
  203. // An excellent use-case for interning is struct field names,
  204. // or map keys where key type is string.
  205. InternString bool
  206. // PreferArrayOverSlice controls whether to decode to an array or a slice.
  207. //
  208. // This only impacts decoding into a nil interface{}.
  209. // Consequently, it has no effect on codecgen.
  210. //
  211. // *Note*: This only applies if using go1.5 and above,
  212. // as it requires reflect.ArrayOf support which was absent before go1.5.
  213. PreferArrayOverSlice bool
  214. // DeleteOnNilMapValue controls how to decode a nil value in the stream.
  215. //
  216. // If true, we will delete the mapping of the key.
  217. // Else, just set the mapping to the zero value of the type.
  218. DeleteOnNilMapValue bool
  219. // RawToString controls how raw bytes in a stream are decoded into a nil interface{}.
  220. // By default, they are decoded as []byte, but can be decoded as string (if configured).
  221. RawToString bool
  222. }
  223. // ------------------------------------------------
  224. type unreadByteStatus uint8
  225. // unreadByteStatus goes from
  226. // undefined (when initialized) -- (read) --> canUnread -- (unread) --> canRead ...
  227. const (
  228. unreadByteUndefined unreadByteStatus = iota
  229. unreadByteCanRead
  230. unreadByteCanUnread
  231. )
  232. type ioDecReaderCommon struct {
  233. r io.Reader // the reader passed in
  234. n uint // num read
  235. l byte // last byte
  236. ls unreadByteStatus // last byte status
  237. trb bool // tracking bytes turned on
  238. _ bool
  239. b [4]byte // tiny buffer for reading single bytes
  240. tr []byte // tracking bytes read
  241. }
  242. func (z *ioDecReaderCommon) reset(r io.Reader) {
  243. z.r = r
  244. z.ls = unreadByteUndefined
  245. z.l, z.n = 0, 0
  246. z.trb = false
  247. if z.tr != nil {
  248. z.tr = z.tr[:0]
  249. }
  250. }
  251. func (z *ioDecReaderCommon) numread() uint {
  252. return z.n
  253. }
  254. func (z *ioDecReaderCommon) track() {
  255. if z.tr != nil {
  256. z.tr = z.tr[:0]
  257. }
  258. z.trb = true
  259. }
  260. func (z *ioDecReaderCommon) stopTrack() (bs []byte) {
  261. z.trb = false
  262. return z.tr
  263. }
  264. // ------------------------------------------
  265. // ioDecReader is a decReader that reads off an io.Reader.
  266. //
  267. // It also has a fallback implementation of ByteScanner if needed.
  268. type ioDecReader struct {
  269. ioDecReaderCommon
  270. rr io.Reader
  271. br io.ByteScanner
  272. x [scratchByteArrayLen]byte // for: get struct field name, swallow valueTypeBytes, etc
  273. _ [1]uint64 // padding
  274. }
  275. func (z *ioDecReader) reset(r io.Reader) {
  276. z.ioDecReaderCommon.reset(r)
  277. var ok bool
  278. z.rr = r
  279. z.br, ok = r.(io.ByteScanner)
  280. if !ok {
  281. z.br = z
  282. z.rr = z
  283. }
  284. }
  285. func (z *ioDecReader) Read(p []byte) (n int, err error) {
  286. if len(p) == 0 {
  287. return
  288. }
  289. var firstByte bool
  290. if z.ls == unreadByteCanRead {
  291. z.ls = unreadByteCanUnread
  292. p[0] = z.l
  293. if len(p) == 1 {
  294. n = 1
  295. return
  296. }
  297. firstByte = true
  298. p = p[1:]
  299. }
  300. n, err = z.r.Read(p)
  301. if n > 0 {
  302. if err == io.EOF && n == len(p) {
  303. err = nil // read was successful, so postpone EOF (till next time)
  304. }
  305. z.l = p[n-1]
  306. z.ls = unreadByteCanUnread
  307. }
  308. if firstByte {
  309. n++
  310. }
  311. return
  312. }
  313. func (z *ioDecReader) ReadByte() (c byte, err error) {
  314. n, err := z.Read(z.b[:1])
  315. if n == 1 {
  316. c = z.b[0]
  317. if err == io.EOF {
  318. err = nil // read was successful, so postpone EOF (till next time)
  319. }
  320. }
  321. return
  322. }
  323. func (z *ioDecReader) UnreadByte() (err error) {
  324. switch z.ls {
  325. case unreadByteCanUnread:
  326. z.ls = unreadByteCanRead
  327. case unreadByteCanRead:
  328. err = errDecUnreadByteLastByteNotRead
  329. case unreadByteUndefined:
  330. err = errDecUnreadByteNothingToRead
  331. default:
  332. err = errDecUnreadByteUnknown
  333. }
  334. return
  335. }
  336. func (z *ioDecReader) readx(n uint) (bs []byte) {
  337. if n == 0 {
  338. return
  339. }
  340. if n < uint(len(z.x)) {
  341. bs = z.x[:n]
  342. } else {
  343. bs = make([]byte, n)
  344. }
  345. if _, err := decReadFull(z.rr, bs); err != nil {
  346. panic(err)
  347. }
  348. z.n += uint(len(bs))
  349. if z.trb {
  350. z.tr = append(z.tr, bs...)
  351. }
  352. return
  353. }
  354. func (z *ioDecReader) readb(bs []byte) {
  355. if len(bs) == 0 {
  356. return
  357. }
  358. if _, err := decReadFull(z.rr, bs); err != nil {
  359. panic(err)
  360. }
  361. z.n += uint(len(bs))
  362. if z.trb {
  363. z.tr = append(z.tr, bs...)
  364. }
  365. }
  366. func (z *ioDecReader) readn1eof() (b uint8, eof bool) {
  367. b, err := z.br.ReadByte()
  368. if err == nil {
  369. z.n++
  370. if z.trb {
  371. z.tr = append(z.tr, b)
  372. }
  373. } else if err == io.EOF {
  374. eof = true
  375. } else {
  376. panic(err)
  377. }
  378. return
  379. }
  380. func (z *ioDecReader) readn1() (b uint8) {
  381. b, err := z.br.ReadByte()
  382. if err == nil {
  383. z.n++
  384. if z.trb {
  385. z.tr = append(z.tr, b)
  386. }
  387. return
  388. }
  389. panic(err)
  390. }
  391. func (z *ioDecReader) skip(accept *bitset256) (token byte) {
  392. var eof bool
  393. // for {
  394. // token, eof = z.readn1eof()
  395. // if eof {
  396. // return
  397. // }
  398. // if accept.isset(token) {
  399. // continue
  400. // }
  401. // return
  402. // }
  403. LOOP:
  404. token, eof = z.readn1eof()
  405. if eof {
  406. return
  407. }
  408. if accept.isset(token) {
  409. goto LOOP
  410. }
  411. return
  412. }
  413. func (z *ioDecReader) readTo(in []byte, accept *bitset256) []byte {
  414. // out = in
  415. // for {
  416. // token, eof := z.readn1eof()
  417. // if eof {
  418. // return
  419. // }
  420. // if accept.isset(token) {
  421. // out = append(out, token)
  422. // } else {
  423. // z.unreadn1()
  424. // return
  425. // }
  426. // }
  427. LOOP:
  428. token, eof := z.readn1eof()
  429. if eof {
  430. return in
  431. }
  432. if accept.isset(token) {
  433. // out = append(out, token)
  434. in = append(in, token)
  435. goto LOOP
  436. }
  437. z.unreadn1()
  438. return in
  439. }
  440. func (z *ioDecReader) readUntil(in []byte, stop byte) (out []byte) {
  441. out = in
  442. // for {
  443. // token, eof := z.readn1eof()
  444. // if eof {
  445. // panic(io.EOF)
  446. // }
  447. // out = append(out, token)
  448. // if token == stop {
  449. // return
  450. // }
  451. // }
  452. LOOP:
  453. token, eof := z.readn1eof()
  454. if eof {
  455. panic(io.EOF)
  456. }
  457. out = append(out, token)
  458. if token == stop {
  459. return
  460. }
  461. goto LOOP
  462. }
  463. //go:noinline
  464. func (z *ioDecReader) unreadn1() {
  465. err := z.br.UnreadByte()
  466. if err != nil {
  467. panic(err)
  468. }
  469. z.n--
  470. if z.trb {
  471. if l := len(z.tr) - 1; l >= 0 {
  472. z.tr = z.tr[:l]
  473. }
  474. }
  475. }
  476. // ------------------------------------
  477. type bufioDecReader struct {
  478. ioDecReaderCommon
  479. c uint // cursor
  480. buf []byte
  481. bytesBufPooler
  482. // err error
  483. // Extensions can call Decode() within a current Decode() call.
  484. // We need to know when the top level Decode() call returns,
  485. // so we can decide whether to Release() or not.
  486. calls uint16 // what depth in mustDecode are we in now.
  487. _ [6]uint8 // padding
  488. _ [1]uint64 // padding
  489. }
  490. func (z *bufioDecReader) reset(r io.Reader, bufsize int) {
  491. z.ioDecReaderCommon.reset(r)
  492. z.c = 0
  493. z.calls = 0
  494. if cap(z.buf) >= bufsize {
  495. z.buf = z.buf[:0]
  496. } else {
  497. z.buf = z.bytesBufPooler.get(bufsize)[:0]
  498. // z.buf = make([]byte, 0, bufsize)
  499. }
  500. }
  501. func (z *bufioDecReader) release() {
  502. z.buf = nil
  503. z.bytesBufPooler.end()
  504. }
  505. func (z *bufioDecReader) readb(p []byte) {
  506. var n = uint(copy(p, z.buf[z.c:]))
  507. z.n += n
  508. z.c += n
  509. if len(p) == int(n) {
  510. if z.trb {
  511. z.tr = append(z.tr, p...) // cost=9
  512. }
  513. } else {
  514. z.readbFill(p, n)
  515. }
  516. }
  517. //go:noinline - fallback when z.buf is consumed
  518. func (z *bufioDecReader) readbFill(p0 []byte, n uint) {
  519. // at this point, there's nothing in z.buf to read (z.buf is fully consumed)
  520. p := p0[n:]
  521. var n2 uint
  522. var err error
  523. if len(p) > cap(z.buf) {
  524. n2, err = decReadFull(z.r, p)
  525. if err != nil {
  526. panic(err)
  527. }
  528. n += n2
  529. z.n += n2
  530. // always keep last byte in z.buf
  531. z.buf = z.buf[:1]
  532. z.buf[0] = p[len(p)-1]
  533. z.c = 1
  534. if z.trb {
  535. z.tr = append(z.tr, p0[:n]...)
  536. }
  537. return
  538. }
  539. // z.c is now 0, and len(p) <= cap(z.buf)
  540. LOOP:
  541. // for len(p) > 0 && z.err == nil {
  542. if len(p) > 0 {
  543. z.buf = z.buf[0:cap(z.buf)]
  544. var n1 int
  545. n1, err = z.r.Read(z.buf)
  546. n2 = uint(n1)
  547. if n2 == 0 && err != nil {
  548. panic(err)
  549. }
  550. z.buf = z.buf[:n2]
  551. n2 = uint(copy(p, z.buf))
  552. z.c = n2
  553. n += n2
  554. z.n += n2
  555. p = p[n2:]
  556. goto LOOP
  557. }
  558. if z.c == 0 {
  559. z.buf = z.buf[:1]
  560. z.buf[0] = p[len(p)-1]
  561. z.c = 1
  562. }
  563. if z.trb {
  564. z.tr = append(z.tr, p0[:n]...)
  565. }
  566. }
  567. func (z *bufioDecReader) readn1() (b byte) {
  568. // fast-path, so we elide calling into Read() most of the time
  569. if z.c < uint(len(z.buf)) {
  570. b = z.buf[z.c]
  571. z.c++
  572. z.n++
  573. if z.trb {
  574. z.tr = append(z.tr, b)
  575. }
  576. } else { // meaning z.c == len(z.buf) or greater ... so need to fill
  577. z.readbFill(z.b[:1], 0)
  578. b = z.b[0]
  579. }
  580. return
  581. }
  582. func (z *bufioDecReader) unreadn1() {
  583. if z.c == 0 {
  584. panic(errDecUnreadByteNothingToRead)
  585. }
  586. z.c--
  587. z.n--
  588. if z.trb {
  589. z.tr = z.tr[:len(z.tr)-1]
  590. }
  591. }
  592. func (z *bufioDecReader) readx(n uint) (bs []byte) {
  593. if n == 0 {
  594. // return
  595. } else if z.c+n <= uint(len(z.buf)) {
  596. bs = z.buf[z.c : z.c+n]
  597. z.n += n
  598. z.c += n
  599. if z.trb {
  600. z.tr = append(z.tr, bs...)
  601. }
  602. } else {
  603. bs = make([]byte, n)
  604. // n no longer used - can reuse
  605. n = uint(copy(bs, z.buf[z.c:]))
  606. z.n += n
  607. z.c += n
  608. z.readbFill(bs, n)
  609. }
  610. return
  611. }
  612. //go:noinline - track called by Decoder.nextValueBytes() (called by jsonUnmarshal,rawBytes)
  613. func (z *bufioDecReader) doTrack(y uint) {
  614. z.tr = append(z.tr, z.buf[z.c:y]...) // cost=14???
  615. }
  616. func (z *bufioDecReader) skipLoopFn(i uint) {
  617. z.n += (i - z.c) - 1
  618. i++
  619. if z.trb {
  620. // z.tr = append(z.tr, z.buf[z.c:i]...)
  621. z.doTrack(i)
  622. }
  623. z.c = i
  624. }
  625. func (z *bufioDecReader) skip(accept *bitset256) (token byte) {
  626. // token, _ = z.search(nil, accept, 0, 1); return
  627. // for i := z.c; i < len(z.buf); i++ {
  628. // if token = z.buf[i]; !accept.isset(token) {
  629. // z.skipLoopFn(i)
  630. // return
  631. // }
  632. // }
  633. i := z.c
  634. LOOP:
  635. if i < uint(len(z.buf)) {
  636. // inline z.skipLoopFn(i) and refactor, so cost is within inline budget
  637. token = z.buf[i]
  638. i++
  639. if accept.isset(token) {
  640. goto LOOP
  641. }
  642. z.n += i - 2 - z.c
  643. if z.trb {
  644. z.doTrack(i)
  645. }
  646. z.c = i
  647. return
  648. }
  649. return z.skipFill(accept)
  650. }
  651. func (z *bufioDecReader) skipFill(accept *bitset256) (token byte) {
  652. z.n += uint(len(z.buf)) - z.c
  653. if z.trb {
  654. z.tr = append(z.tr, z.buf[z.c:]...)
  655. }
  656. var n2 int
  657. var err error
  658. for {
  659. z.c = 0
  660. z.buf = z.buf[0:cap(z.buf)]
  661. n2, err = z.r.Read(z.buf)
  662. if n2 == 0 && err != nil {
  663. panic(err)
  664. }
  665. z.buf = z.buf[:n2]
  666. var i int
  667. for i, token = range z.buf {
  668. if !accept.isset(token) {
  669. z.skipLoopFn(uint(i))
  670. return
  671. }
  672. }
  673. // for i := 0; i < n2; i++ {
  674. // if token = z.buf[i]; !accept.isset(token) {
  675. // z.skipLoopFn(i)
  676. // return
  677. // }
  678. // }
  679. z.n += uint(n2)
  680. if z.trb {
  681. z.tr = append(z.tr, z.buf...)
  682. }
  683. }
  684. }
  685. func (z *bufioDecReader) readToLoopFn(i uint, out0 []byte) (out []byte) {
  686. // out0 is never nil
  687. z.n += (i - z.c) - 1
  688. out = append(out0, z.buf[z.c:i]...)
  689. if z.trb {
  690. z.doTrack(i)
  691. }
  692. z.c = i
  693. return
  694. }
  695. func (z *bufioDecReader) readTo(in []byte, accept *bitset256) (out []byte) {
  696. // _, out = z.search(in, accept, 0, 2); return
  697. // for i := z.c; i < len(z.buf); i++ {
  698. // if !accept.isset(z.buf[i]) {
  699. // return z.readToLoopFn(i, nil)
  700. // }
  701. // }
  702. i := z.c
  703. LOOP:
  704. if i < uint(len(z.buf)) {
  705. if !accept.isset(z.buf[i]) {
  706. // return z.readToLoopFn(i, nil)
  707. // inline readToLoopFn here (for performance)
  708. z.n += (i - z.c) - 1
  709. out = z.buf[z.c:i]
  710. if z.trb {
  711. z.doTrack(i)
  712. }
  713. z.c = i
  714. return
  715. }
  716. i++
  717. goto LOOP
  718. }
  719. return z.readToFill(in, accept)
  720. }
  721. func (z *bufioDecReader) readToFill(in []byte, accept *bitset256) (out []byte) {
  722. z.n += uint(len(z.buf)) - z.c
  723. out = append(in, z.buf[z.c:]...)
  724. if z.trb {
  725. z.tr = append(z.tr, z.buf[z.c:]...)
  726. }
  727. var n2 int
  728. var err error
  729. for {
  730. z.c = 0
  731. z.buf = z.buf[0:cap(z.buf)]
  732. n2, err = z.r.Read(z.buf)
  733. if n2 == 0 && err != nil {
  734. if err == io.EOF {
  735. return // readTo should read until it matches or end is reached
  736. }
  737. panic(err)
  738. }
  739. z.buf = z.buf[:n2]
  740. for i, token := range z.buf {
  741. if !accept.isset(token) {
  742. return z.readToLoopFn(uint(i), out)
  743. }
  744. }
  745. // for i := 0; i < n2; i++ {
  746. // if !accept.isset(z.buf[i]) {
  747. // return z.readToLoopFn(i, out)
  748. // }
  749. // }
  750. out = append(out, z.buf...)
  751. z.n += uint(n2)
  752. if z.trb {
  753. z.tr = append(z.tr, z.buf...)
  754. }
  755. }
  756. }
  757. func (z *bufioDecReader) readUntilLoopFn(i uint, out0 []byte) (out []byte) {
  758. z.n += (i - z.c) - 1
  759. i++
  760. out = append(out0, z.buf[z.c:i]...)
  761. if z.trb {
  762. // z.tr = append(z.tr, z.buf[z.c:i]...)
  763. z.doTrack(i)
  764. }
  765. z.c = i
  766. return
  767. }
  768. func (z *bufioDecReader) readUntil(in []byte, stop byte) (out []byte) {
  769. // _, out = z.search(in, nil, stop, 4); return
  770. // for i := z.c; i < len(z.buf); i++ {
  771. // if z.buf[i] == stop {
  772. // return z.readUntilLoopFn(i, nil)
  773. // }
  774. // }
  775. i := z.c
  776. LOOP:
  777. if i < uint(len(z.buf)) {
  778. if z.buf[i] == stop {
  779. // inline readUntilLoopFn
  780. // return z.readUntilLoopFn(i, nil)
  781. z.n += (i - z.c) - 1
  782. i++
  783. out = z.buf[z.c:i]
  784. if z.trb {
  785. z.doTrack(i)
  786. }
  787. z.c = i
  788. return
  789. }
  790. i++
  791. goto LOOP
  792. }
  793. return z.readUntilFill(in, stop)
  794. }
  795. func (z *bufioDecReader) readUntilFill(in []byte, stop byte) (out []byte) {
  796. z.n += uint(len(z.buf)) - z.c
  797. out = append(in, z.buf[z.c:]...)
  798. if z.trb {
  799. z.tr = append(z.tr, z.buf[z.c:]...)
  800. }
  801. var n1 int
  802. var n2 uint
  803. var err error
  804. for {
  805. z.c = 0
  806. z.buf = z.buf[0:cap(z.buf)]
  807. n1, err = z.r.Read(z.buf)
  808. n2 = uint(n1)
  809. if n2 == 0 && err != nil {
  810. panic(err)
  811. }
  812. z.buf = z.buf[:n2]
  813. for i, token := range z.buf {
  814. if token == stop {
  815. return z.readUntilLoopFn(uint(i), out)
  816. }
  817. }
  818. // for i := 0; i < n2; i++ {
  819. // if z.buf[i] == stop {
  820. // return z.readUntilLoopFn(i, out)
  821. // }
  822. // }
  823. out = append(out, z.buf...)
  824. z.n += n2
  825. if z.trb {
  826. z.tr = append(z.tr, z.buf...)
  827. }
  828. }
  829. }
  830. // ------------------------------------
  831. var errBytesDecReaderCannotUnread = errors.New("cannot unread last byte read")
  832. // bytesDecReader is a decReader that reads off a byte slice with zero copying
  833. type bytesDecReader struct {
  834. b []byte // data
  835. c uint // cursor
  836. t uint // track start
  837. // a int // available
  838. }
  839. func (z *bytesDecReader) reset(in []byte) {
  840. z.b = in
  841. // z.a = len(in)
  842. z.c = 0
  843. z.t = 0
  844. }
  845. func (z *bytesDecReader) numread() uint {
  846. return z.c
  847. }
  848. func (z *bytesDecReader) unreadn1() {
  849. if z.c == 0 || len(z.b) == 0 {
  850. panic(errBytesDecReaderCannotUnread)
  851. }
  852. z.c--
  853. // z.a++
  854. }
  855. func (z *bytesDecReader) readx(n uint) (bs []byte) {
  856. // slicing from a non-constant start position is more expensive,
  857. // as more computation is required to decipher the pointer start position.
  858. // However, we do it only once, and it's better than reslicing both z.b and return value.
  859. // if n <= 0 {
  860. // } else if z.a == 0 {
  861. // panic(io.EOF)
  862. // } else if n > z.a {
  863. // panic(io.ErrUnexpectedEOF)
  864. // } else {
  865. // c0 := z.c
  866. // z.c = c0 + n
  867. // z.a = z.a - n
  868. // bs = z.b[c0:z.c]
  869. // }
  870. // return
  871. if n != 0 {
  872. z.c += n
  873. if z.c > uint(len(z.b)) {
  874. z.c = uint(len(z.b))
  875. panic(io.EOF)
  876. }
  877. bs = z.b[z.c-n : z.c]
  878. }
  879. return
  880. // if n == 0 {
  881. // } else if z.c+n > uint(len(z.b)) {
  882. // z.c = uint(len(z.b))
  883. // panic(io.EOF)
  884. // } else {
  885. // z.c += n
  886. // bs = z.b[z.c-n : z.c]
  887. // }
  888. // return
  889. // if n == 0 {
  890. // return
  891. // }
  892. // if z.c == uint(len(z.b)) {
  893. // panic(io.EOF)
  894. // }
  895. // if z.c+n > uint(len(z.b)) {
  896. // panic(io.ErrUnexpectedEOF)
  897. // }
  898. // // z.a -= n
  899. // z.c += n
  900. // return z.b[z.c-n : z.c]
  901. }
  902. func (z *bytesDecReader) readb(bs []byte) {
  903. copy(bs, z.readx(uint(len(bs))))
  904. }
  905. func (z *bytesDecReader) readn1() (v uint8) {
  906. if z.c == uint(len(z.b)) {
  907. panic(io.EOF)
  908. }
  909. v = z.b[z.c]
  910. z.c++
  911. // z.a--
  912. return
  913. }
  914. // func (z *bytesDecReader) readn1eof() (v uint8, eof bool) {
  915. // if z.a == 0 {
  916. // eof = true
  917. // return
  918. // }
  919. // v = z.b[z.c]
  920. // z.c++
  921. // z.a--
  922. // return
  923. // }
  924. func (z *bytesDecReader) skip(accept *bitset256) (token byte) {
  925. i := z.c
  926. // if i == len(z.b) {
  927. // goto END
  928. // // panic(io.EOF)
  929. // }
  930. // Replace loop with goto construct, so that this can be inlined
  931. // for i := z.c; i < blen; i++ {
  932. // if !accept.isset(z.b[i]) {
  933. // token = z.b[i]
  934. // i++
  935. // z.a -= (i - z.c)
  936. // z.c = i
  937. // return
  938. // }
  939. // }
  940. // i := z.c
  941. LOOP:
  942. if i < uint(len(z.b)) {
  943. token = z.b[i]
  944. i++
  945. if accept.isset(token) {
  946. goto LOOP
  947. }
  948. // z.a -= (i - z.c)
  949. z.c = i
  950. return
  951. }
  952. // END:
  953. panic(io.EOF)
  954. // // z.a = 0
  955. // z.c = blen
  956. // return
  957. }
  958. func (z *bytesDecReader) readTo(_ []byte, accept *bitset256) (out []byte) {
  959. return z.readToNoInput(accept)
  960. }
  961. func (z *bytesDecReader) readToNoInput(accept *bitset256) (out []byte) {
  962. i := z.c
  963. if i == uint(len(z.b)) {
  964. panic(io.EOF)
  965. }
  966. // Replace loop with goto construct, so that this can be inlined
  967. // for i := z.c; i < blen; i++ {
  968. // if !accept.isset(z.b[i]) {
  969. // out = z.b[z.c:i]
  970. // z.a -= (i - z.c)
  971. // z.c = i
  972. // return
  973. // }
  974. // }
  975. // out = z.b[z.c:]
  976. // z.a, z.c = 0, blen
  977. // return
  978. // i := z.c
  979. // LOOP:
  980. // if i < blen {
  981. // if accept.isset(z.b[i]) {
  982. // i++
  983. // goto LOOP
  984. // }
  985. // out = z.b[z.c:i]
  986. // z.a -= (i - z.c)
  987. // z.c = i
  988. // return
  989. // }
  990. // out = z.b[z.c:]
  991. // // z.a, z.c = 0, blen
  992. // z.a = 0
  993. // z.c = blen
  994. // return
  995. // c := i
  996. LOOP:
  997. if i < uint(len(z.b)) {
  998. if accept.isset(z.b[i]) {
  999. i++
  1000. goto LOOP
  1001. }
  1002. }
  1003. out = z.b[z.c:i]
  1004. // z.a -= (i - z.c)
  1005. z.c = i
  1006. return // z.b[c:i]
  1007. // z.c, i = i, z.c
  1008. // return z.b[i:z.c]
  1009. }
  1010. func (z *bytesDecReader) readUntil(_ []byte, stop byte) (out []byte) {
  1011. return z.readUntilNoInput(stop)
  1012. }
  1013. func (z *bytesDecReader) readUntilNoInput(stop byte) (out []byte) {
  1014. i := z.c
  1015. // if i == len(z.b) {
  1016. // panic(io.EOF)
  1017. // }
  1018. // Replace loop with goto construct, so that this can be inlined
  1019. // for i := z.c; i < blen; i++ {
  1020. // if z.b[i] == stop {
  1021. // i++
  1022. // out = z.b[z.c:i]
  1023. // z.a -= (i - z.c)
  1024. // z.c = i
  1025. // return
  1026. // }
  1027. // }
  1028. LOOP:
  1029. if i < uint(len(z.b)) {
  1030. if z.b[i] == stop {
  1031. i++
  1032. out = z.b[z.c:i]
  1033. // z.a -= (i - z.c)
  1034. z.c = i
  1035. return
  1036. }
  1037. i++
  1038. goto LOOP
  1039. }
  1040. // z.a = 0
  1041. // z.c = blen
  1042. panic(io.EOF)
  1043. }
  1044. func (z *bytesDecReader) track() {
  1045. z.t = z.c
  1046. }
  1047. func (z *bytesDecReader) stopTrack() (bs []byte) {
  1048. return z.b[z.t:z.c]
  1049. }
  1050. // ----------------------------------------
  1051. // func (d *Decoder) builtin(f *codecFnInfo, rv reflect.Value) {
  1052. // d.d.DecodeBuiltin(f.ti.rtid, rv2i(rv))
  1053. // }
  1054. func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) {
  1055. d.d.DecodeExt(rv2i(rv), 0, nil)
  1056. }
  1057. func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) {
  1058. d.d.DecodeExt(rv2i(rv), f.xfTag, f.xfFn)
  1059. }
  1060. func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) {
  1061. rv2i(rv).(Selfer).CodecDecodeSelf(d)
  1062. }
  1063. func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) {
  1064. bm := rv2i(rv).(encoding.BinaryUnmarshaler)
  1065. xbs := d.d.DecodeBytes(nil, true)
  1066. if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil {
  1067. panic(fnerr)
  1068. }
  1069. }
  1070. func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) {
  1071. tm := rv2i(rv).(encoding.TextUnmarshaler)
  1072. fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes())
  1073. if fnerr != nil {
  1074. panic(fnerr)
  1075. }
  1076. }
  1077. func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) {
  1078. tm := rv2i(rv).(jsonUnmarshaler)
  1079. // bs := d.d.DecodeBytes(d.b[:], true, true)
  1080. // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
  1081. fnerr := tm.UnmarshalJSON(d.nextValueBytes())
  1082. if fnerr != nil {
  1083. panic(fnerr)
  1084. }
  1085. }
  1086. func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) {
  1087. d.errorf("no decoding function defined for kind %v", rv.Kind())
  1088. }
  1089. // var kIntfCtr uint64
  1090. func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) {
  1091. // nil interface:
  1092. // use some hieristics to decode it appropriately
  1093. // based on the detected next value in the stream.
  1094. n := d.naked()
  1095. d.d.DecodeNaked()
  1096. if n.v == valueTypeNil {
  1097. return
  1098. }
  1099. // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader).
  1100. if f.ti.numMeth > 0 {
  1101. d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth)
  1102. return
  1103. }
  1104. // var useRvn bool
  1105. switch n.v {
  1106. case valueTypeMap:
  1107. // if json, default to a map type with string keys
  1108. mtid := d.mtid
  1109. if mtid == 0 {
  1110. if d.jsms {
  1111. mtid = mapStrIntfTypId
  1112. } else {
  1113. mtid = mapIntfIntfTypId
  1114. }
  1115. }
  1116. if mtid == mapIntfIntfTypId {
  1117. var v2 map[interface{}]interface{}
  1118. d.decode(&v2)
  1119. rvn = reflect.ValueOf(&v2).Elem()
  1120. } else if mtid == mapStrIntfTypId { // for json performance
  1121. var v2 map[string]interface{}
  1122. d.decode(&v2)
  1123. rvn = reflect.ValueOf(&v2).Elem()
  1124. } else {
  1125. if d.mtr {
  1126. rvn = reflect.New(d.h.MapType)
  1127. d.decode(rv2i(rvn))
  1128. rvn = rvn.Elem()
  1129. } else {
  1130. rvn = reflect.New(d.h.MapType).Elem()
  1131. d.decodeValue(rvn, nil, true)
  1132. }
  1133. }
  1134. case valueTypeArray:
  1135. if d.stid == 0 || d.stid == intfSliceTypId {
  1136. var v2 []interface{}
  1137. d.decode(&v2)
  1138. rvn = reflect.ValueOf(&v2).Elem()
  1139. if reflectArrayOfSupported && d.stid == 0 && d.h.PreferArrayOverSlice {
  1140. rvn2 := reflect.New(reflectArrayOf(rvn.Len(), intfTyp)).Elem()
  1141. reflect.Copy(rvn2, rvn)
  1142. rvn = rvn2
  1143. }
  1144. } else {
  1145. if d.str {
  1146. rvn = reflect.New(d.h.SliceType)
  1147. d.decode(rv2i(rvn))
  1148. rvn = rvn.Elem()
  1149. } else {
  1150. rvn = reflect.New(d.h.SliceType).Elem()
  1151. d.decodeValue(rvn, nil, true)
  1152. }
  1153. }
  1154. case valueTypeExt:
  1155. var v interface{}
  1156. tag, bytes := n.u, n.l // calling decode below might taint the values
  1157. if bytes == nil {
  1158. d.decode(&v)
  1159. }
  1160. bfn := d.h.getExtForTag(tag)
  1161. if bfn == nil {
  1162. var re RawExt
  1163. re.Tag = tag
  1164. re.Data = detachZeroCopyBytes(d.bytes, nil, bytes)
  1165. re.Value = v
  1166. rvn = reflect.ValueOf(&re).Elem()
  1167. } else {
  1168. rvnA := reflect.New(bfn.rt)
  1169. if bytes != nil {
  1170. bfn.ext.ReadExt(rv2i(rvnA), bytes)
  1171. } else {
  1172. bfn.ext.UpdateExt(rv2i(rvnA), v)
  1173. }
  1174. rvn = rvnA.Elem()
  1175. }
  1176. case valueTypeNil:
  1177. // no-op
  1178. case valueTypeInt:
  1179. rvn = n.ri()
  1180. case valueTypeUint:
  1181. rvn = n.ru()
  1182. case valueTypeFloat:
  1183. rvn = n.rf()
  1184. case valueTypeBool:
  1185. rvn = n.rb()
  1186. case valueTypeString, valueTypeSymbol:
  1187. rvn = n.rs()
  1188. case valueTypeBytes:
  1189. rvn = n.rl()
  1190. case valueTypeTime:
  1191. rvn = n.rt()
  1192. default:
  1193. panicv.errorf("kInterfaceNaked: unexpected valueType: %d", n.v)
  1194. }
  1195. return
  1196. }
  1197. func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
  1198. // Note:
  1199. // A consequence of how kInterface works, is that
  1200. // if an interface already contains something, we try
  1201. // to decode into what was there before.
  1202. // We do not replace with a generic value (as got from decodeNaked).
  1203. // every interface passed here MUST be settable.
  1204. var rvn reflect.Value
  1205. if rv.IsNil() || d.h.InterfaceReset {
  1206. // check if mapping to a type: if so, initialize it and move on
  1207. rvn = d.h.intf2impl(f.ti.rtid)
  1208. if rvn.IsValid() {
  1209. rv.Set(rvn)
  1210. } else {
  1211. rvn = d.kInterfaceNaked(f)
  1212. if rvn.IsValid() {
  1213. rv.Set(rvn)
  1214. } else if d.h.InterfaceReset {
  1215. // reset to zero value based on current type in there.
  1216. rv.Set(reflect.Zero(rv.Elem().Type()))
  1217. }
  1218. return
  1219. }
  1220. } else {
  1221. // now we have a non-nil interface value, meaning it contains a type
  1222. rvn = rv.Elem()
  1223. }
  1224. if d.d.TryDecodeAsNil() {
  1225. rv.Set(reflect.Zero(rvn.Type()))
  1226. return
  1227. }
  1228. // Note: interface{} is settable, but underlying type may not be.
  1229. // Consequently, we MAY have to create a decodable value out of the underlying value,
  1230. // decode into it, and reset the interface itself.
  1231. // fmt.Printf(">>>> kInterface: rvn type: %v, rv type: %v\n", rvn.Type(), rv.Type())
  1232. rvn2, canDecode := isDecodeable(rvn)
  1233. if canDecode {
  1234. d.decodeValue(rvn2, nil, true)
  1235. return
  1236. }
  1237. rvn2 = reflect.New(rvn.Type()).Elem()
  1238. rvn2.Set(rvn)
  1239. d.decodeValue(rvn2, nil, true)
  1240. rv.Set(rvn2)
  1241. }
  1242. func decStructFieldKey(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) {
  1243. // use if-else-if, not switch (which compiles to binary-search)
  1244. // since keyType is typically valueTypeString, branch prediction is pretty good.
  1245. if keyType == valueTypeString {
  1246. rvkencname = dd.DecodeStringAsBytes()
  1247. } else if keyType == valueTypeInt {
  1248. rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10)
  1249. } else if keyType == valueTypeUint {
  1250. rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10)
  1251. } else if keyType == valueTypeFloat {
  1252. rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64)
  1253. } else {
  1254. rvkencname = dd.DecodeStringAsBytes()
  1255. }
  1256. return rvkencname
  1257. }
  1258. func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  1259. fti := f.ti
  1260. dd := d.d
  1261. elemsep := d.esep
  1262. sfn := structFieldNode{v: rv, update: true}
  1263. ctyp := dd.ContainerType()
  1264. var mf MissingFielder
  1265. if fti.mf {
  1266. mf = rv2i(rv).(MissingFielder)
  1267. } else if fti.mfp {
  1268. mf = rv2i(rv.Addr()).(MissingFielder)
  1269. }
  1270. if ctyp == valueTypeMap {
  1271. containerLen := dd.ReadMapStart()
  1272. if containerLen == 0 {
  1273. dd.ReadMapEnd()
  1274. return
  1275. }
  1276. d.depthIncr()
  1277. tisfi := fti.sfiSort
  1278. hasLen := containerLen >= 0
  1279. var rvkencname []byte
  1280. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1281. if elemsep {
  1282. dd.ReadMapElemKey()
  1283. }
  1284. rvkencname = decStructFieldKey(dd, fti.keyType, &d.b)
  1285. if elemsep {
  1286. dd.ReadMapElemValue()
  1287. }
  1288. if k := fti.indexForEncName(rvkencname); k > -1 {
  1289. si := tisfi[k]
  1290. if dd.TryDecodeAsNil() {
  1291. si.setToZeroValue(rv)
  1292. } else {
  1293. d.decodeValue(sfn.field(si), nil, true)
  1294. }
  1295. } else if mf != nil {
  1296. // store rvkencname in new []byte, as it previously shares Decoder.b, which is used in decode
  1297. name2 := rvkencname
  1298. rvkencname = make([]byte, len(rvkencname))
  1299. copy(rvkencname, name2)
  1300. var f interface{}
  1301. // xdebugf("kStruct: mf != nil: before decode: rvkencname: %s", rvkencname)
  1302. d.decode(&f)
  1303. // xdebugf("kStruct: mf != nil: after decode: rvkencname: %s", rvkencname)
  1304. if !mf.CodecMissingField(rvkencname, f) && d.h.ErrorIfNoField {
  1305. d.errorf("no matching struct field found when decoding stream map with key: %s ",
  1306. stringView(rvkencname))
  1307. }
  1308. } else {
  1309. d.structFieldNotFound(-1, stringView(rvkencname))
  1310. }
  1311. // keepAlive4StringView(rvkencnameB) // not needed, as reference is outside loop
  1312. }
  1313. dd.ReadMapEnd()
  1314. d.depthDecr()
  1315. } else if ctyp == valueTypeArray {
  1316. containerLen := dd.ReadArrayStart()
  1317. if containerLen == 0 {
  1318. dd.ReadArrayEnd()
  1319. return
  1320. }
  1321. d.depthIncr()
  1322. // Not much gain from doing it two ways for array.
  1323. // Arrays are not used as much for structs.
  1324. hasLen := containerLen >= 0
  1325. var checkbreak bool
  1326. for j, si := range fti.sfiSrc {
  1327. if hasLen && j == containerLen {
  1328. break
  1329. }
  1330. if !hasLen && dd.CheckBreak() {
  1331. checkbreak = true
  1332. break
  1333. }
  1334. if elemsep {
  1335. dd.ReadArrayElem()
  1336. }
  1337. if dd.TryDecodeAsNil() {
  1338. si.setToZeroValue(rv)
  1339. } else {
  1340. d.decodeValue(sfn.field(si), nil, true)
  1341. }
  1342. }
  1343. if (hasLen && containerLen > len(fti.sfiSrc)) || (!hasLen && !checkbreak) {
  1344. // read remaining values and throw away
  1345. for j := len(fti.sfiSrc); ; j++ {
  1346. if (hasLen && j == containerLen) || (!hasLen && dd.CheckBreak()) {
  1347. break
  1348. }
  1349. if elemsep {
  1350. dd.ReadArrayElem()
  1351. }
  1352. d.structFieldNotFound(j, "")
  1353. }
  1354. }
  1355. dd.ReadArrayEnd()
  1356. d.depthDecr()
  1357. } else {
  1358. d.errorstr(errstrOnlyMapOrArrayCanDecodeIntoStruct)
  1359. return
  1360. }
  1361. }
  1362. func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
  1363. // A slice can be set from a map or array in stream.
  1364. // This way, the order can be kept (as order is lost with map).
  1365. ti := f.ti
  1366. if f.seq == seqTypeChan && ti.chandir&uint8(reflect.SendDir) == 0 {
  1367. d.errorf("receive-only channel cannot be decoded")
  1368. }
  1369. dd := d.d
  1370. rtelem0 := ti.elem
  1371. ctyp := dd.ContainerType()
  1372. if ctyp == valueTypeBytes || ctyp == valueTypeString {
  1373. // you can only decode bytes or string in the stream into a slice or array of bytes
  1374. if !(ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) {
  1375. d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
  1376. }
  1377. if f.seq == seqTypeChan {
  1378. bs2 := dd.DecodeBytes(nil, true)
  1379. irv := rv2i(rv)
  1380. ch, ok := irv.(chan<- byte)
  1381. if !ok {
  1382. ch = irv.(chan byte)
  1383. }
  1384. for _, b := range bs2 {
  1385. ch <- b
  1386. }
  1387. } else {
  1388. rvbs := rv.Bytes()
  1389. bs2 := dd.DecodeBytes(rvbs, false)
  1390. // if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) {
  1391. if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
  1392. if rv.CanSet() {
  1393. rv.SetBytes(bs2)
  1394. } else if len(rvbs) > 0 && len(bs2) > 0 {
  1395. copy(rvbs, bs2)
  1396. }
  1397. }
  1398. }
  1399. return
  1400. }
  1401. // array := f.seq == seqTypeChan
  1402. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map)
  1403. // an array can never return a nil slice. so no need to check f.array here.
  1404. if containerLenS == 0 {
  1405. if rv.CanSet() {
  1406. if f.seq == seqTypeSlice {
  1407. if rv.IsNil() {
  1408. rv.Set(reflect.MakeSlice(ti.rt, 0, 0))
  1409. } else {
  1410. rv.SetLen(0)
  1411. }
  1412. } else if f.seq == seqTypeChan {
  1413. if rv.IsNil() {
  1414. rv.Set(reflect.MakeChan(ti.rt, 0))
  1415. }
  1416. }
  1417. }
  1418. slh.End()
  1419. return
  1420. }
  1421. d.depthIncr()
  1422. rtelem0Size := int(rtelem0.Size())
  1423. rtElem0Kind := rtelem0.Kind()
  1424. rtelem0Mut := !isImmutableKind(rtElem0Kind)
  1425. rtelem := rtelem0
  1426. rtelemkind := rtelem.Kind()
  1427. for rtelemkind == reflect.Ptr {
  1428. rtelem = rtelem.Elem()
  1429. rtelemkind = rtelem.Kind()
  1430. }
  1431. var fn *codecFn
  1432. var rvCanset = rv.CanSet()
  1433. var rvChanged bool
  1434. var rv0 = rv
  1435. var rv9 reflect.Value
  1436. rvlen := rv.Len()
  1437. rvcap := rv.Cap()
  1438. hasLen := containerLenS > 0
  1439. if hasLen && f.seq == seqTypeSlice {
  1440. if containerLenS > rvcap {
  1441. oldRvlenGtZero := rvlen > 0
  1442. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size()))
  1443. if rvlen <= rvcap {
  1444. if rvCanset {
  1445. rv.SetLen(rvlen)
  1446. }
  1447. } else if rvCanset {
  1448. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  1449. rvcap = rvlen
  1450. rvChanged = true
  1451. } else {
  1452. d.errorf("cannot decode into non-settable slice")
  1453. }
  1454. if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) {
  1455. reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
  1456. }
  1457. } else if containerLenS != rvlen {
  1458. rvlen = containerLenS
  1459. if rvCanset {
  1460. rv.SetLen(rvlen)
  1461. }
  1462. // else {
  1463. // rv = rv.Slice(0, rvlen)
  1464. // rvChanged = true
  1465. // d.errorf("cannot decode into non-settable slice")
  1466. // }
  1467. }
  1468. }
  1469. // consider creating new element once, and just decoding into it.
  1470. var rtelem0Zero reflect.Value
  1471. var rtelem0ZeroValid bool
  1472. var decodeAsNil bool
  1473. var j int
  1474. for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ {
  1475. if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rv.IsNil() {
  1476. if hasLen {
  1477. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size)
  1478. } else if f.seq == seqTypeSlice {
  1479. rvlen = decDefSliceCap
  1480. } else {
  1481. rvlen = decDefChanCap
  1482. }
  1483. if rvCanset {
  1484. if f.seq == seqTypeSlice {
  1485. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  1486. rvChanged = true
  1487. } else { // chan
  1488. rv = reflect.MakeChan(ti.rt, rvlen)
  1489. rvChanged = true
  1490. }
  1491. } else {
  1492. d.errorf("cannot decode into non-settable slice")
  1493. }
  1494. }
  1495. slh.ElemContainerState(j)
  1496. decodeAsNil = dd.TryDecodeAsNil()
  1497. if f.seq == seqTypeChan {
  1498. if decodeAsNil {
  1499. rv.Send(reflect.Zero(rtelem0))
  1500. continue
  1501. }
  1502. if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rv9.IsNil()) {
  1503. rv9 = reflect.New(rtelem0).Elem()
  1504. }
  1505. if fn == nil {
  1506. fn = d.h.fn(rtelem, true, true)
  1507. }
  1508. d.decodeValue(rv9, fn, true)
  1509. rv.Send(rv9)
  1510. } else {
  1511. // if indefinite, etc, then expand the slice if necessary
  1512. var decodeIntoBlank bool
  1513. if j >= rvlen {
  1514. if f.seq == seqTypeArray {
  1515. d.arrayCannotExpand(rvlen, j+1)
  1516. decodeIntoBlank = true
  1517. } else { // if f.seq == seqTypeSlice
  1518. // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // append logic + varargs
  1519. var rvcap2 int
  1520. var rvErrmsg2 string
  1521. rv9, rvcap2, rvChanged, rvErrmsg2 =
  1522. expandSliceRV(rv, ti.rt, rvCanset, rtelem0Size, 1, rvlen, rvcap)
  1523. if rvErrmsg2 != "" {
  1524. d.errorf(rvErrmsg2)
  1525. }
  1526. rvlen++
  1527. if rvChanged {
  1528. rv = rv9
  1529. rvcap = rvcap2
  1530. }
  1531. }
  1532. }
  1533. if decodeIntoBlank {
  1534. if !decodeAsNil {
  1535. d.swallow()
  1536. }
  1537. } else {
  1538. rv9 = rv.Index(j)
  1539. if d.h.SliceElementReset || decodeAsNil {
  1540. if !rtelem0ZeroValid {
  1541. rtelem0ZeroValid = true
  1542. rtelem0Zero = reflect.Zero(rtelem0)
  1543. }
  1544. rv9.Set(rtelem0Zero)
  1545. if decodeAsNil {
  1546. continue
  1547. }
  1548. }
  1549. if fn == nil {
  1550. fn = d.h.fn(rtelem, true, true)
  1551. }
  1552. d.decodeValue(rv9, fn, true)
  1553. }
  1554. }
  1555. }
  1556. if f.seq == seqTypeSlice {
  1557. if j < rvlen {
  1558. if rv.CanSet() {
  1559. rv.SetLen(j)
  1560. } else if rvCanset {
  1561. rv = rv.Slice(0, j)
  1562. rvChanged = true
  1563. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1564. rvlen = j
  1565. } else if j == 0 && rv.IsNil() {
  1566. if rvCanset {
  1567. rv = reflect.MakeSlice(ti.rt, 0, 0)
  1568. rvChanged = true
  1569. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1570. }
  1571. }
  1572. slh.End()
  1573. if rvChanged { // infers rvCanset=true, so it can be reset
  1574. rv0.Set(rv)
  1575. }
  1576. d.depthDecr()
  1577. }
  1578. // func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
  1579. // // d.decodeValueFn(rv.Slice(0, rv.Len()))
  1580. // f.kSlice(rv.Slice(0, rv.Len()))
  1581. // }
  1582. func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
  1583. dd := d.d
  1584. containerLen := dd.ReadMapStart()
  1585. elemsep := d.esep
  1586. ti := f.ti
  1587. if rv.IsNil() {
  1588. rvlen := decInferLen(containerLen, d.h.MaxInitLen, int(ti.key.Size()+ti.elem.Size()))
  1589. rv.Set(makeMapReflect(ti.rt, rvlen))
  1590. }
  1591. if containerLen == 0 {
  1592. dd.ReadMapEnd()
  1593. return
  1594. }
  1595. d.depthIncr()
  1596. ktype, vtype := ti.key, ti.elem
  1597. ktypeId := rt2id(ktype)
  1598. vtypeKind := vtype.Kind()
  1599. var keyFn, valFn *codecFn
  1600. var ktypeLo, vtypeLo reflect.Type
  1601. for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
  1602. }
  1603. for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
  1604. }
  1605. var mapGet, mapSet bool
  1606. rvvImmut := isImmutableKind(vtypeKind)
  1607. if !d.h.MapValueReset {
  1608. // if pointer, mapGet = true
  1609. // if interface, mapGet = true if !DecodeNakedAlways (else false)
  1610. // if builtin, mapGet = false
  1611. // else mapGet = true
  1612. if vtypeKind == reflect.Ptr {
  1613. mapGet = true
  1614. } else if vtypeKind == reflect.Interface {
  1615. if !d.h.InterfaceReset {
  1616. mapGet = true
  1617. }
  1618. } else if !rvvImmut {
  1619. mapGet = true
  1620. }
  1621. }
  1622. var rvk, rvkp, rvv, rvz reflect.Value
  1623. rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk.
  1624. ktypeIsString := ktypeId == stringTypId
  1625. ktypeIsIntf := ktypeId == intfTypId
  1626. hasLen := containerLen > 0
  1627. var kstrbs []byte
  1628. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1629. if rvkMut || !rvkp.IsValid() {
  1630. rvkp = reflect.New(ktype)
  1631. rvk = rvkp.Elem()
  1632. }
  1633. if elemsep {
  1634. dd.ReadMapElemKey()
  1635. }
  1636. // if false && dd.TryDecodeAsNil() { // nil cannot be a map key, so disregard this block
  1637. // // Previously, if a nil key, we just ignored the mapped value and continued.
  1638. // // However, that makes the result of encoding and then decoding map[intf]intf{nil:nil}
  1639. // // to be an empty map.
  1640. // // Instead, we treat a nil key as the zero value of the type.
  1641. // rvk.Set(reflect.Zero(ktype))
  1642. // } else if ktypeIsString {
  1643. if ktypeIsString {
  1644. kstrbs = dd.DecodeStringAsBytes()
  1645. rvk.SetString(stringView(kstrbs))
  1646. // NOTE: if doing an insert, you MUST use a real string (not stringview)
  1647. } else {
  1648. if keyFn == nil {
  1649. keyFn = d.h.fn(ktypeLo, true, true)
  1650. }
  1651. d.decodeValue(rvk, keyFn, true)
  1652. }
  1653. // special case if a byte array.
  1654. if ktypeIsIntf {
  1655. if rvk2 := rvk.Elem(); rvk2.IsValid() {
  1656. if rvk2.Type() == uint8SliceTyp {
  1657. rvk = reflect.ValueOf(d.string(rvk2.Bytes()))
  1658. } else {
  1659. rvk = rvk2
  1660. }
  1661. }
  1662. }
  1663. if elemsep {
  1664. dd.ReadMapElemValue()
  1665. }
  1666. // Brittle, but OK per TryDecodeAsNil() contract.
  1667. // i.e. TryDecodeAsNil never shares slices with other decDriver procedures
  1668. if dd.TryDecodeAsNil() {
  1669. if ktypeIsString {
  1670. rvk.SetString(d.string(kstrbs))
  1671. }
  1672. if d.h.DeleteOnNilMapValue {
  1673. rv.SetMapIndex(rvk, reflect.Value{})
  1674. } else {
  1675. rv.SetMapIndex(rvk, reflect.Zero(vtype))
  1676. }
  1677. continue
  1678. }
  1679. mapSet = true // set to false if u do a get, and its a non-nil pointer
  1680. if mapGet {
  1681. // mapGet true only in case where kind=Ptr|Interface or kind is otherwise mutable.
  1682. rvv = rv.MapIndex(rvk)
  1683. if !rvv.IsValid() {
  1684. rvv = reflect.New(vtype).Elem()
  1685. } else if vtypeKind == reflect.Ptr {
  1686. if rvv.IsNil() {
  1687. rvv = reflect.New(vtype).Elem()
  1688. } else {
  1689. mapSet = false
  1690. }
  1691. } else if vtypeKind == reflect.Interface {
  1692. // not addressable, and thus not settable.
  1693. // e MUST create a settable/addressable variant
  1694. rvv2 := reflect.New(rvv.Type()).Elem()
  1695. if !rvv.IsNil() {
  1696. rvv2.Set(rvv)
  1697. }
  1698. rvv = rvv2
  1699. }
  1700. // else it is ~mutable, and we can just decode into it directly
  1701. } else if rvvImmut {
  1702. if !rvz.IsValid() {
  1703. rvz = reflect.New(vtype).Elem()
  1704. }
  1705. rvv = rvz
  1706. } else {
  1707. rvv = reflect.New(vtype).Elem()
  1708. }
  1709. // We MUST be done with the stringview of the key, before decoding the value
  1710. // so that we don't bastardize the reused byte array.
  1711. if mapSet && ktypeIsString {
  1712. rvk.SetString(d.string(kstrbs))
  1713. }
  1714. if valFn == nil {
  1715. valFn = d.h.fn(vtypeLo, true, true)
  1716. }
  1717. d.decodeValue(rvv, valFn, true)
  1718. // d.decodeValueFn(rvv, valFn)
  1719. if mapSet {
  1720. rv.SetMapIndex(rvk, rvv)
  1721. }
  1722. // if ktypeIsString {
  1723. // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop
  1724. // }
  1725. }
  1726. dd.ReadMapEnd()
  1727. d.depthDecr()
  1728. }
  1729. // decNaked is used to keep track of the primitives decoded.
  1730. // Without it, we would have to decode each primitive and wrap it
  1731. // in an interface{}, causing an allocation.
  1732. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  1733. // so we can rest assured that no other decoding happens while these
  1734. // primitives are being decoded.
  1735. //
  1736. // maps and arrays are not handled by this mechanism.
  1737. // However, RawExt is, and we accommodate for extensions that decode
  1738. // RawExt from DecodeNaked, but need to decode the value subsequently.
  1739. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
  1740. //
  1741. // However, decNaked also keeps some arrays of default maps and slices
  1742. // used in DecodeNaked. This way, we can get a pointer to it
  1743. // without causing a new heap allocation.
  1744. //
  1745. // kInterfaceNaked will ensure that there is no allocation for the common
  1746. // uses.
  1747. type decNaked struct {
  1748. // r RawExt // used for RawExt, uint, []byte.
  1749. // primitives below
  1750. u uint64
  1751. i int64
  1752. f float64
  1753. l []byte
  1754. s string
  1755. // ---- cpu cache line boundary?
  1756. t time.Time
  1757. b bool
  1758. // state
  1759. v valueType
  1760. _ [6]bool // padding
  1761. // ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above
  1762. //
  1763. // _ [3]uint64 // padding
  1764. }
  1765. // func (n *decNaked) init() {
  1766. // n.ru = reflect.ValueOf(&n.u).Elem()
  1767. // n.ri = reflect.ValueOf(&n.i).Elem()
  1768. // n.rf = reflect.ValueOf(&n.f).Elem()
  1769. // n.rl = reflect.ValueOf(&n.l).Elem()
  1770. // n.rs = reflect.ValueOf(&n.s).Elem()
  1771. // n.rt = reflect.ValueOf(&n.t).Elem()
  1772. // n.rb = reflect.ValueOf(&n.b).Elem()
  1773. // // n.rr[] = reflect.ValueOf(&n.)
  1774. // }
  1775. // type decNakedPooler struct {
  1776. // n *decNaked
  1777. // nsp *sync.Pool
  1778. // }
  1779. // // naked must be called before each call to .DecodeNaked, as they will use it.
  1780. // func (d *decNakedPooler) naked() *decNaked {
  1781. // if d.n == nil {
  1782. // // consider one of:
  1783. // // - get from sync.Pool (if GC is frequent, there's no value here)
  1784. // // - new alloc (safest. only init'ed if it a naked decode will be done)
  1785. // // - field in Decoder (makes the Decoder struct very big)
  1786. // // To support using a decoder where a DecodeNaked is not needed,
  1787. // // we prefer #1 or #2.
  1788. // // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool
  1789. // // d.n.init()
  1790. // var v interface{}
  1791. // d.nsp, v = pool.decNaked()
  1792. // d.n = v.(*decNaked)
  1793. // }
  1794. // return d.n
  1795. // }
  1796. // func (d *decNakedPooler) end() {
  1797. // if d.n != nil {
  1798. // // if n != nil, then nsp != nil (they are always set together)
  1799. // d.nsp.Put(d.n)
  1800. // d.n, d.nsp = nil, nil
  1801. // }
  1802. // }
  1803. // type rtid2rv struct {
  1804. // rtid uintptr
  1805. // rv reflect.Value
  1806. // }
  1807. // --------------
  1808. type decReaderSwitch struct {
  1809. rb bytesDecReader
  1810. // ---- cpu cache line boundary?
  1811. ri *ioDecReader
  1812. bi *bufioDecReader
  1813. mtr, str bool // whether maptype or slicetype are known types
  1814. be bool // is binary encoding
  1815. js bool // is json handle
  1816. jsms bool // is json handle, and MapKeyAsString
  1817. esep bool // has elem separators
  1818. // typ entryType
  1819. bytes bool // is bytes reader
  1820. bufio bool // is this a bufioDecReader?
  1821. }
  1822. // numread, track and stopTrack are always inlined, as they just check int fields, etc.
  1823. /*
  1824. func (z *decReaderSwitch) numread() int {
  1825. switch z.typ {
  1826. case entryTypeBytes:
  1827. return z.rb.numread()
  1828. case entryTypeIo:
  1829. return z.ri.numread()
  1830. default:
  1831. return z.bi.numread()
  1832. }
  1833. }
  1834. func (z *decReaderSwitch) track() {
  1835. switch z.typ {
  1836. case entryTypeBytes:
  1837. z.rb.track()
  1838. case entryTypeIo:
  1839. z.ri.track()
  1840. default:
  1841. z.bi.track()
  1842. }
  1843. }
  1844. func (z *decReaderSwitch) stopTrack() []byte {
  1845. switch z.typ {
  1846. case entryTypeBytes:
  1847. return z.rb.stopTrack()
  1848. case entryTypeIo:
  1849. return z.ri.stopTrack()
  1850. default:
  1851. return z.bi.stopTrack()
  1852. }
  1853. }
  1854. func (z *decReaderSwitch) unreadn1() {
  1855. switch z.typ {
  1856. case entryTypeBytes:
  1857. z.rb.unreadn1()
  1858. case entryTypeIo:
  1859. z.ri.unreadn1()
  1860. default:
  1861. z.bi.unreadn1()
  1862. }
  1863. }
  1864. func (z *decReaderSwitch) readx(n int) []byte {
  1865. switch z.typ {
  1866. case entryTypeBytes:
  1867. return z.rb.readx(n)
  1868. case entryTypeIo:
  1869. return z.ri.readx(n)
  1870. default:
  1871. return z.bi.readx(n)
  1872. }
  1873. }
  1874. func (z *decReaderSwitch) readb(s []byte) {
  1875. switch z.typ {
  1876. case entryTypeBytes:
  1877. z.rb.readb(s)
  1878. case entryTypeIo:
  1879. z.ri.readb(s)
  1880. default:
  1881. z.bi.readb(s)
  1882. }
  1883. }
  1884. func (z *decReaderSwitch) readn1() uint8 {
  1885. switch z.typ {
  1886. case entryTypeBytes:
  1887. return z.rb.readn1()
  1888. case entryTypeIo:
  1889. return z.ri.readn1()
  1890. default:
  1891. return z.bi.readn1()
  1892. }
  1893. }
  1894. func (z *decReaderSwitch) skip(accept *bitset256) (token byte) {
  1895. switch z.typ {
  1896. case entryTypeBytes:
  1897. return z.rb.skip(accept)
  1898. case entryTypeIo:
  1899. return z.ri.skip(accept)
  1900. default:
  1901. return z.bi.skip(accept)
  1902. }
  1903. }
  1904. func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) {
  1905. switch z.typ {
  1906. case entryTypeBytes:
  1907. return z.rb.readTo(in, accept)
  1908. case entryTypeIo:
  1909. return z.ri.readTo(in, accept)
  1910. default:
  1911. return z.bi.readTo(in, accept)
  1912. }
  1913. }
  1914. func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) {
  1915. switch z.typ {
  1916. case entryTypeBytes:
  1917. return z.rb.readUntil(in, stop)
  1918. case entryTypeIo:
  1919. return z.ri.readUntil(in, stop)
  1920. default:
  1921. return z.bi.readUntil(in, stop)
  1922. }
  1923. }
  1924. */
  1925. // the if/else-if/else block is expensive to inline.
  1926. // Each node of this construct costs a lot and dominates the budget.
  1927. // Best to only do an if fast-path else block (so fast-path is inlined).
  1928. // This is irrespective of inlineExtraCallCost set in $GOROOT/src/cmd/compile/internal/gc/inl.go
  1929. //
  1930. // In decReaderSwitch methods below, we delegate all IO functions into their own methods.
  1931. // This allows for the inlining of the common path when z.bytes=true.
  1932. // Go 1.12+ supports inlining methods with up to 1 inlined function (or 2 if no other constructs).
  1933. func (z *decReaderSwitch) numread() uint {
  1934. if z.bytes {
  1935. return z.rb.numread()
  1936. } else if z.bufio {
  1937. return z.bi.numread()
  1938. } else {
  1939. return z.ri.numread()
  1940. }
  1941. }
  1942. func (z *decReaderSwitch) track() {
  1943. if z.bytes {
  1944. z.rb.track()
  1945. } else if z.bufio {
  1946. z.bi.track()
  1947. } else {
  1948. z.ri.track()
  1949. }
  1950. }
  1951. func (z *decReaderSwitch) stopTrack() []byte {
  1952. if z.bytes {
  1953. return z.rb.stopTrack()
  1954. } else if z.bufio {
  1955. return z.bi.stopTrack()
  1956. } else {
  1957. return z.ri.stopTrack()
  1958. }
  1959. }
  1960. // func (z *decReaderSwitch) unreadn1() {
  1961. // if z.bytes {
  1962. // z.rb.unreadn1()
  1963. // } else {
  1964. // z.unreadn1IO()
  1965. // }
  1966. // }
  1967. // func (z *decReaderSwitch) unreadn1IO() {
  1968. // if z.bufio {
  1969. // z.bi.unreadn1()
  1970. // } else {
  1971. // z.ri.unreadn1()
  1972. // }
  1973. // }
  1974. func (z *decReaderSwitch) unreadn1() {
  1975. if z.bytes {
  1976. z.rb.unreadn1()
  1977. } else if z.bufio {
  1978. z.bi.unreadn1()
  1979. } else {
  1980. z.ri.unreadn1() // not inlined
  1981. }
  1982. }
  1983. func (z *decReaderSwitch) readx(n uint) []byte {
  1984. if z.bytes {
  1985. return z.rb.readx(n)
  1986. }
  1987. return z.readxIO(n)
  1988. }
  1989. func (z *decReaderSwitch) readxIO(n uint) []byte {
  1990. if z.bufio {
  1991. return z.bi.readx(n)
  1992. }
  1993. return z.ri.readx(n)
  1994. }
  1995. func (z *decReaderSwitch) readb(s []byte) {
  1996. if z.bytes {
  1997. z.rb.readb(s)
  1998. } else {
  1999. z.readbIO(s)
  2000. }
  2001. }
  2002. //go:noinline - fallback for io, ensures z.bytes path is inlined
  2003. func (z *decReaderSwitch) readbIO(s []byte) {
  2004. if z.bufio {
  2005. z.bi.readb(s)
  2006. } else {
  2007. z.ri.readb(s)
  2008. }
  2009. }
  2010. func (z *decReaderSwitch) readn1() uint8 {
  2011. if z.bytes {
  2012. return z.rb.readn1()
  2013. }
  2014. return z.readn1IO()
  2015. }
  2016. func (z *decReaderSwitch) readn1IO() uint8 {
  2017. if z.bufio {
  2018. return z.bi.readn1()
  2019. }
  2020. return z.ri.readn1()
  2021. }
  2022. func (z *decReaderSwitch) skip(accept *bitset256) (token byte) {
  2023. if z.bytes {
  2024. return z.rb.skip(accept)
  2025. }
  2026. return z.skipIO(accept)
  2027. }
  2028. func (z *decReaderSwitch) skipIO(accept *bitset256) (token byte) {
  2029. if z.bufio {
  2030. return z.bi.skip(accept)
  2031. }
  2032. return z.ri.skip(accept)
  2033. }
  2034. func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) {
  2035. if z.bytes {
  2036. return z.rb.readToNoInput(accept) // z.rb.readTo(in, accept)
  2037. }
  2038. return z.readToIO(in, accept)
  2039. }
  2040. //go:noinline - fallback for io, ensures z.bytes path is inlined
  2041. func (z *decReaderSwitch) readToIO(in []byte, accept *bitset256) (out []byte) {
  2042. if z.bufio {
  2043. return z.bi.readTo(in, accept)
  2044. }
  2045. return z.ri.readTo(in, accept)
  2046. }
  2047. func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) {
  2048. if z.bytes {
  2049. return z.rb.readUntilNoInput(stop)
  2050. }
  2051. return z.readUntilIO(in, stop)
  2052. }
  2053. func (z *decReaderSwitch) readUntilIO(in []byte, stop byte) (out []byte) {
  2054. if z.bufio {
  2055. return z.bi.readUntil(in, stop)
  2056. }
  2057. return z.ri.readUntil(in, stop)
  2058. }
  2059. // Decoder reads and decodes an object from an input stream in a supported format.
  2060. //
  2061. // Decoder is NOT safe for concurrent use i.e. a Decoder cannot be used
  2062. // concurrently in multiple goroutines.
  2063. //
  2064. // However, as Decoder could be allocation heavy to initialize, a Reset method is provided
  2065. // so its state can be reused to decode new input streams repeatedly.
  2066. // This is the idiomatic way to use.
  2067. type Decoder struct {
  2068. panicHdl
  2069. // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
  2070. // Try to put things that go together to fit within a cache line (8 words).
  2071. d decDriver
  2072. // NOTE: Decoder shouldn't call it's read methods,
  2073. // as the handler MAY need to do some coordination.
  2074. r *decReaderSwitch
  2075. // bi *bufioDecReader
  2076. // cache the mapTypeId and sliceTypeId for faster comparisons
  2077. mtid uintptr
  2078. stid uintptr
  2079. hh Handle
  2080. h *BasicHandle
  2081. // ---- cpu cache line boundary?
  2082. decReaderSwitch
  2083. // ---- cpu cache line boundary?
  2084. n decNaked
  2085. // cr containerStateRecv
  2086. err error
  2087. depth int16
  2088. maxdepth int16
  2089. _ [4]uint8 // padding
  2090. is map[string]string // used for interning strings
  2091. // ---- cpu cache line boundary?
  2092. b [decScratchByteArrayLen]byte // scratch buffer, used by Decoder and xxxEncDrivers
  2093. // padding - false sharing help // modify 232 if Decoder struct changes.
  2094. // _ [cacheLineSize - 232%cacheLineSize]byte
  2095. }
  2096. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  2097. //
  2098. // For efficiency, Users are encouraged to configure ReaderBufferSize on the handle
  2099. // OR pass in a memory buffered reader (eg bufio.Reader, bytes.Buffer).
  2100. func NewDecoder(r io.Reader, h Handle) *Decoder {
  2101. d := newDecoder(h)
  2102. d.Reset(r)
  2103. return d
  2104. }
  2105. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  2106. // from a byte slice with zero copying.
  2107. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  2108. d := newDecoder(h)
  2109. d.ResetBytes(in)
  2110. return d
  2111. }
  2112. // var defaultDecNaked decNaked
  2113. func newDecoder(h Handle) *Decoder {
  2114. d := &Decoder{h: basicHandle(h), err: errDecoderNotInitialized}
  2115. d.bytes = true
  2116. if useFinalizers {
  2117. runtime.SetFinalizer(d, (*Decoder).finalize)
  2118. // xdebugf(">>>> new(Decoder) with finalizer")
  2119. }
  2120. d.r = &d.decReaderSwitch
  2121. d.hh = h
  2122. d.be = h.isBinary()
  2123. // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
  2124. var jh *JsonHandle
  2125. jh, d.js = h.(*JsonHandle)
  2126. if d.js {
  2127. d.jsms = jh.MapKeyAsString
  2128. }
  2129. d.esep = d.hh.hasElemSeparators()
  2130. if d.h.InternString {
  2131. d.is = make(map[string]string, 32)
  2132. }
  2133. d.d = h.newDecDriver(d)
  2134. // d.cr, _ = d.d.(containerStateRecv)
  2135. return d
  2136. }
  2137. func (d *Decoder) resetCommon() {
  2138. // d.r = &d.decReaderSwitch
  2139. d.d.reset()
  2140. d.err = nil
  2141. d.depth = 0
  2142. d.maxdepth = d.h.MaxDepth
  2143. if d.maxdepth <= 0 {
  2144. d.maxdepth = decDefMaxDepth
  2145. }
  2146. // reset all things which were cached from the Handle, but could change
  2147. d.mtid, d.stid = 0, 0
  2148. d.mtr, d.str = false, false
  2149. if d.h.MapType != nil {
  2150. d.mtid = rt2id(d.h.MapType)
  2151. d.mtr = fastpathAV.index(d.mtid) != -1
  2152. }
  2153. if d.h.SliceType != nil {
  2154. d.stid = rt2id(d.h.SliceType)
  2155. d.str = fastpathAV.index(d.stid) != -1
  2156. }
  2157. }
  2158. // Reset the Decoder with a new Reader to decode from,
  2159. // clearing all state from last run(s).
  2160. func (d *Decoder) Reset(r io.Reader) {
  2161. if r == nil {
  2162. return
  2163. }
  2164. d.bytes = false
  2165. // d.typ = entryTypeUnset
  2166. if d.h.ReaderBufferSize > 0 {
  2167. if d.bi == nil {
  2168. d.bi = new(bufioDecReader)
  2169. }
  2170. d.bi.reset(r, d.h.ReaderBufferSize)
  2171. // d.r = d.bi
  2172. // d.typ = entryTypeBufio
  2173. d.bufio = true
  2174. } else {
  2175. // d.ri.x = &d.b
  2176. // d.s = d.sa[:0]
  2177. if d.ri == nil {
  2178. d.ri = new(ioDecReader)
  2179. }
  2180. d.ri.reset(r)
  2181. // d.r = d.ri
  2182. // d.typ = entryTypeIo
  2183. d.bufio = false
  2184. }
  2185. d.resetCommon()
  2186. }
  2187. // ResetBytes resets the Decoder with a new []byte to decode from,
  2188. // clearing all state from last run(s).
  2189. func (d *Decoder) ResetBytes(in []byte) {
  2190. if in == nil {
  2191. return
  2192. }
  2193. d.bytes = true
  2194. d.bufio = false
  2195. // d.typ = entryTypeBytes
  2196. d.rb.reset(in)
  2197. // d.r = &d.rb
  2198. d.resetCommon()
  2199. }
  2200. func (d *Decoder) naked() *decNaked {
  2201. return &d.n
  2202. }
  2203. // Decode decodes the stream from reader and stores the result in the
  2204. // value pointed to by v. v cannot be a nil pointer. v can also be
  2205. // a reflect.Value of a pointer.
  2206. //
  2207. // Note that a pointer to a nil interface is not a nil pointer.
  2208. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  2209. // We will decode and store a value in that nil interface.
  2210. //
  2211. // Sample usages:
  2212. // // Decoding into a non-nil typed value
  2213. // var f float32
  2214. // err = codec.NewDecoder(r, handle).Decode(&f)
  2215. //
  2216. // // Decoding into nil interface
  2217. // var v interface{}
  2218. // dec := codec.NewDecoder(r, handle)
  2219. // err = dec.Decode(&v)
  2220. //
  2221. // When decoding into a nil interface{}, we will decode into an appropriate value based
  2222. // on the contents of the stream:
  2223. // - Numbers are decoded as float64, int64 or uint64.
  2224. // - Other values are decoded appropriately depending on the type:
  2225. // bool, string, []byte, time.Time, etc
  2226. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  2227. // Configurations exist on the Handle to override defaults
  2228. // (e.g. for MapType, SliceType and how to decode raw bytes).
  2229. //
  2230. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  2231. // type of the value. When a value is seen:
  2232. // - If an extension is registered for it, call that extension function
  2233. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  2234. // - Else decode it based on its reflect.Kind
  2235. //
  2236. // There are some special rules when decoding into containers (slice/array/map/struct).
  2237. // Decode will typically use the stream contents to UPDATE the container i.e. the values
  2238. // in these containers will not be zero'ed before decoding.
  2239. // - A map can be decoded from a stream map, by updating matching keys.
  2240. // - A slice can be decoded from a stream array,
  2241. // by updating the first n elements, where n is length of the stream.
  2242. // - A slice can be decoded from a stream map, by decoding as if
  2243. // it contains a sequence of key-value pairs.
  2244. // - A struct can be decoded from a stream map, by updating matching fields.
  2245. // - A struct can be decoded from a stream array,
  2246. // by updating fields as they occur in the struct (by index).
  2247. //
  2248. // This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update
  2249. // in place by default). However, the consequence of this is that values in slices or maps
  2250. // which are not zero'ed before hand, will have part of the prior values in place after decode
  2251. // if the stream doesn't contain an update for those parts.
  2252. //
  2253. // This in-place update can be disabled by configuring the MapValueReset and SliceElementReset
  2254. // decode options available on every handle.
  2255. //
  2256. // Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice,
  2257. // we reset the destination map or slice to a zero-length value.
  2258. //
  2259. // However, when decoding a stream nil, we reset the destination container
  2260. // to its "zero" value (e.g. nil for slice/map, etc).
  2261. //
  2262. // Note: we allow nil values in the stream anywhere except for map keys.
  2263. // A nil value in the encoded stream where a map key is expected is treated as an error.
  2264. func (d *Decoder) Decode(v interface{}) (err error) {
  2265. // tried to use closure, as runtime optimizes defer with no params.
  2266. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  2267. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  2268. // defer func() { d.deferred(&err) }()
  2269. // { x, y := d, &err; defer func() { x.deferred(y) }() }
  2270. if d.err != nil {
  2271. return d.err
  2272. }
  2273. if recoverPanicToErr {
  2274. defer func() {
  2275. if x := recover(); x != nil {
  2276. panicValToErr(d, x, &d.err)
  2277. err = d.err
  2278. }
  2279. }()
  2280. }
  2281. // defer d.deferred(&err)
  2282. d.mustDecode(v)
  2283. return
  2284. }
  2285. // MustDecode is like Decode, but panics if unable to Decode.
  2286. // This provides insight to the code location that triggered the error.
  2287. func (d *Decoder) MustDecode(v interface{}) {
  2288. if d.err != nil {
  2289. panic(d.err)
  2290. }
  2291. d.mustDecode(v)
  2292. }
  2293. // MustDecode is like Decode, but panics if unable to Decode.
  2294. // This provides insight to the code location that triggered the error.
  2295. func (d *Decoder) mustDecode(v interface{}) {
  2296. // TODO: Top-level: ensure that v is a pointer and not nil.
  2297. if d.d.TryDecodeAsNil() {
  2298. setZero(v)
  2299. return
  2300. }
  2301. if d.bi == nil {
  2302. d.decode(v)
  2303. return
  2304. }
  2305. d.bi.calls++
  2306. d.decode(v)
  2307. // xprintf.(">>>>>>>> >>>>>>>> num decFns: %v\n", d.cf.sn)
  2308. d.bi.calls--
  2309. if !d.h.ExplicitRelease && d.bi.calls == 0 {
  2310. d.bi.release()
  2311. }
  2312. }
  2313. // func (d *Decoder) deferred(err1 *error) {
  2314. // if recoverPanicToErr {
  2315. // if x := recover(); x != nil {
  2316. // panicValToErr(d, x, err1)
  2317. // panicValToErr(d, x, &d.err)
  2318. // }
  2319. // }
  2320. // }
  2321. //go:noinline -- as it is run by finalizer
  2322. func (d *Decoder) finalize() {
  2323. // xdebugf("finalizing Decoder")
  2324. d.Release()
  2325. }
  2326. // Release releases shared (pooled) resources.
  2327. //
  2328. // It is important to call Release() when done with a Decoder, so those resources
  2329. // are released instantly for use by subsequently created Decoders.
  2330. //
  2331. // By default, Release() is automatically called unless the option ExplicitRelease is set.
  2332. func (d *Decoder) Release() {
  2333. if d.bi != nil {
  2334. d.bi.release()
  2335. }
  2336. // d.decNakedPooler.end()
  2337. }
  2338. // // this is not a smart swallow, as it allocates objects and does unnecessary work.
  2339. // func (d *Decoder) swallowViaHammer() {
  2340. // var blank interface{}
  2341. // d.decodeValueNoFn(reflect.ValueOf(&blank).Elem())
  2342. // }
  2343. func (d *Decoder) swallow() {
  2344. // smarter decode that just swallows the content
  2345. dd := d.d
  2346. if dd.TryDecodeAsNil() {
  2347. return
  2348. }
  2349. elemsep := d.esep
  2350. switch dd.ContainerType() {
  2351. case valueTypeMap:
  2352. containerLen := dd.ReadMapStart()
  2353. d.depthIncr()
  2354. hasLen := containerLen >= 0
  2355. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  2356. // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break}
  2357. if elemsep {
  2358. dd.ReadMapElemKey()
  2359. }
  2360. d.swallow()
  2361. if elemsep {
  2362. dd.ReadMapElemValue()
  2363. }
  2364. d.swallow()
  2365. }
  2366. dd.ReadMapEnd()
  2367. d.depthDecr()
  2368. case valueTypeArray:
  2369. containerLen := dd.ReadArrayStart()
  2370. d.depthIncr()
  2371. hasLen := containerLen >= 0
  2372. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  2373. if elemsep {
  2374. dd.ReadArrayElem()
  2375. }
  2376. d.swallow()
  2377. }
  2378. dd.ReadArrayEnd()
  2379. d.depthDecr()
  2380. case valueTypeBytes:
  2381. dd.DecodeBytes(d.b[:], true)
  2382. case valueTypeString:
  2383. dd.DecodeStringAsBytes()
  2384. default:
  2385. // these are all primitives, which we can get from decodeNaked
  2386. // if RawExt using Value, complete the processing.
  2387. n := d.naked()
  2388. dd.DecodeNaked()
  2389. if n.v == valueTypeExt && n.l == nil {
  2390. var v2 interface{}
  2391. d.decode(&v2)
  2392. }
  2393. }
  2394. }
  2395. func setZero(iv interface{}) {
  2396. if iv == nil || definitelyNil(iv) {
  2397. return
  2398. }
  2399. var canDecode bool
  2400. switch v := iv.(type) {
  2401. case *string:
  2402. *v = ""
  2403. case *bool:
  2404. *v = false
  2405. case *int:
  2406. *v = 0
  2407. case *int8:
  2408. *v = 0
  2409. case *int16:
  2410. *v = 0
  2411. case *int32:
  2412. *v = 0
  2413. case *int64:
  2414. *v = 0
  2415. case *uint:
  2416. *v = 0
  2417. case *uint8:
  2418. *v = 0
  2419. case *uint16:
  2420. *v = 0
  2421. case *uint32:
  2422. *v = 0
  2423. case *uint64:
  2424. *v = 0
  2425. case *float32:
  2426. *v = 0
  2427. case *float64:
  2428. *v = 0
  2429. case *[]uint8:
  2430. *v = nil
  2431. case *Raw:
  2432. *v = nil
  2433. case *time.Time:
  2434. *v = time.Time{}
  2435. case reflect.Value:
  2436. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2437. v.Set(reflect.Zero(v.Type()))
  2438. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2439. default:
  2440. if !fastpathDecodeSetZeroTypeSwitch(iv) {
  2441. v := reflect.ValueOf(iv)
  2442. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2443. v.Set(reflect.Zero(v.Type()))
  2444. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2445. }
  2446. }
  2447. }
  2448. func (d *Decoder) decode(iv interface{}) {
  2449. // a switch with only concrete types can be optimized.
  2450. // consequently, we deal with nil and interfaces outside the switch.
  2451. if iv == nil {
  2452. d.errorstr(errstrCannotDecodeIntoNil)
  2453. return
  2454. }
  2455. switch v := iv.(type) {
  2456. // case nil:
  2457. // case Selfer:
  2458. case reflect.Value:
  2459. v = d.ensureDecodeable(v)
  2460. d.decodeValue(v, nil, true)
  2461. case *string:
  2462. *v = d.d.DecodeString()
  2463. case *bool:
  2464. *v = d.d.DecodeBool()
  2465. case *int:
  2466. *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))
  2467. case *int8:
  2468. *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8))
  2469. case *int16:
  2470. *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16))
  2471. case *int32:
  2472. *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32))
  2473. case *int64:
  2474. *v = d.d.DecodeInt64()
  2475. case *uint:
  2476. *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))
  2477. case *uint8:
  2478. *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))
  2479. case *uint16:
  2480. *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))
  2481. case *uint32:
  2482. *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))
  2483. case *uint64:
  2484. *v = d.d.DecodeUint64()
  2485. case *float32:
  2486. f64 := d.d.DecodeFloat64()
  2487. if chkOvf.Float32(f64) {
  2488. d.errorf("float32 overflow: %v", f64)
  2489. }
  2490. *v = float32(f64)
  2491. case *float64:
  2492. *v = d.d.DecodeFloat64()
  2493. case *[]uint8:
  2494. *v = d.d.DecodeBytes(*v, false)
  2495. case []uint8:
  2496. b := d.d.DecodeBytes(v, false)
  2497. if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) {
  2498. copy(v, b)
  2499. }
  2500. case *time.Time:
  2501. *v = d.d.DecodeTime()
  2502. case *Raw:
  2503. *v = d.rawBytes()
  2504. case *interface{}:
  2505. d.decodeValue(reflect.ValueOf(iv).Elem(), nil, true)
  2506. // d.decodeValueNotNil(reflect.ValueOf(iv).Elem())
  2507. default:
  2508. if v, ok := iv.(Selfer); ok {
  2509. v.CodecDecodeSelf(d)
  2510. } else if !fastpathDecodeTypeSwitch(iv, d) {
  2511. v := reflect.ValueOf(iv)
  2512. v = d.ensureDecodeable(v)
  2513. d.decodeValue(v, nil, false)
  2514. // d.decodeValueFallback(v)
  2515. }
  2516. }
  2517. }
  2518. func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn, chkAll bool) {
  2519. // If stream is not containing a nil value, then we can deref to the base
  2520. // non-pointer value, and decode into that.
  2521. var rvp reflect.Value
  2522. var rvpValid bool
  2523. if rv.Kind() == reflect.Ptr {
  2524. rvpValid = true
  2525. for {
  2526. if rv.IsNil() {
  2527. rv.Set(reflect.New(rv.Type().Elem()))
  2528. }
  2529. rvp = rv
  2530. rv = rv.Elem()
  2531. if rv.Kind() != reflect.Ptr {
  2532. break
  2533. }
  2534. }
  2535. }
  2536. if fn == nil {
  2537. // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer
  2538. fn = d.h.fn(rv.Type(), chkAll, true) // chkAll, chkAll)
  2539. }
  2540. if fn.i.addrD {
  2541. if rvpValid {
  2542. fn.fd(d, &fn.i, rvp)
  2543. } else if rv.CanAddr() {
  2544. fn.fd(d, &fn.i, rv.Addr())
  2545. } else if !fn.i.addrF {
  2546. fn.fd(d, &fn.i, rv)
  2547. } else {
  2548. d.errorf("cannot decode into a non-pointer value")
  2549. }
  2550. } else {
  2551. fn.fd(d, &fn.i, rv)
  2552. }
  2553. // return rv
  2554. }
  2555. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  2556. // NOTE: rvkencname may be a stringView, so don't pass it to another function.
  2557. if d.h.ErrorIfNoField {
  2558. if index >= 0 {
  2559. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  2560. return
  2561. } else if rvkencname != "" {
  2562. d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
  2563. return
  2564. }
  2565. }
  2566. d.swallow()
  2567. }
  2568. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  2569. if d.h.ErrorIfNoArrayExpand {
  2570. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  2571. }
  2572. }
  2573. func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) {
  2574. switch rv.Kind() {
  2575. case reflect.Array:
  2576. return rv, rv.CanAddr()
  2577. case reflect.Ptr:
  2578. if !rv.IsNil() {
  2579. return rv.Elem(), true
  2580. }
  2581. case reflect.Slice, reflect.Chan, reflect.Map:
  2582. if !rv.IsNil() {
  2583. return rv, true
  2584. }
  2585. }
  2586. return
  2587. }
  2588. func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) {
  2589. // decode can take any reflect.Value that is a inherently addressable i.e.
  2590. // - array
  2591. // - non-nil chan (we will SEND to it)
  2592. // - non-nil slice (we will set its elements)
  2593. // - non-nil map (we will put into it)
  2594. // - non-nil pointer (we can "update" it)
  2595. rv2, canDecode := isDecodeable(rv)
  2596. if canDecode {
  2597. return
  2598. }
  2599. if !rv.IsValid() {
  2600. d.errorstr(errstrCannotDecodeIntoNil)
  2601. return
  2602. }
  2603. if !rv.CanInterface() {
  2604. d.errorf("cannot decode into a value without an interface: %v", rv)
  2605. return
  2606. }
  2607. rvi := rv2i(rv)
  2608. rvk := rv.Kind()
  2609. d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi)
  2610. return
  2611. }
  2612. func (d *Decoder) depthIncr() {
  2613. d.depth++
  2614. if d.depth >= d.maxdepth {
  2615. panic(errMaxDepthExceeded)
  2616. }
  2617. }
  2618. func (d *Decoder) depthDecr() {
  2619. d.depth--
  2620. }
  2621. // Possibly get an interned version of a string
  2622. //
  2623. // This should mostly be used for map keys, where the key type is string.
  2624. // This is because keys of a map/struct are typically reused across many objects.
  2625. func (d *Decoder) string(v []byte) (s string) {
  2626. if d.is == nil {
  2627. return string(v) // don't return stringView, as we need a real string here.
  2628. }
  2629. s, ok := d.is[string(v)] // no allocation here, per go implementation
  2630. if !ok {
  2631. s = string(v) // new allocation here
  2632. d.is[s] = s
  2633. }
  2634. return s
  2635. }
  2636. // nextValueBytes returns the next value in the stream as a set of bytes.
  2637. func (d *Decoder) nextValueBytes() (bs []byte) {
  2638. d.d.uncacheRead()
  2639. d.r.track()
  2640. d.swallow()
  2641. bs = d.r.stopTrack()
  2642. return
  2643. }
  2644. func (d *Decoder) rawBytes() []byte {
  2645. // ensure that this is not a view into the bytes
  2646. // i.e. make new copy always.
  2647. bs := d.nextValueBytes()
  2648. bs2 := make([]byte, len(bs))
  2649. copy(bs2, bs)
  2650. return bs2
  2651. }
  2652. func (d *Decoder) wrapErr(v interface{}, err *error) {
  2653. *err = decodeError{codecError: codecError{name: d.hh.Name(), err: v}, pos: int(d.r.numread())}
  2654. }
  2655. // NumBytesRead returns the number of bytes read
  2656. func (d *Decoder) NumBytesRead() int {
  2657. return int(d.r.numread())
  2658. }
  2659. // --------------------------------------------------
  2660. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  2661. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  2662. type decSliceHelper struct {
  2663. d *Decoder
  2664. // ct valueType
  2665. array bool
  2666. }
  2667. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  2668. dd := d.d
  2669. ctyp := dd.ContainerType()
  2670. switch ctyp {
  2671. case valueTypeArray:
  2672. x.array = true
  2673. clen = dd.ReadArrayStart()
  2674. case valueTypeMap:
  2675. clen = dd.ReadMapStart() * 2
  2676. default:
  2677. d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp)
  2678. }
  2679. // x.ct = ctyp
  2680. x.d = d
  2681. return
  2682. }
  2683. func (x decSliceHelper) End() {
  2684. if x.array {
  2685. x.d.d.ReadArrayEnd()
  2686. } else {
  2687. x.d.d.ReadMapEnd()
  2688. }
  2689. }
  2690. func (x decSliceHelper) ElemContainerState(index int) {
  2691. if x.array {
  2692. x.d.d.ReadArrayElem()
  2693. } else if index%2 == 0 {
  2694. x.d.d.ReadMapElemKey()
  2695. } else {
  2696. x.d.d.ReadMapElemValue()
  2697. }
  2698. }
  2699. func decByteSlice(r *decReaderSwitch, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2700. if clen == 0 {
  2701. return zeroByteSlice
  2702. }
  2703. if len(bs) == clen {
  2704. bsOut = bs
  2705. r.readb(bsOut)
  2706. } else if cap(bs) >= clen {
  2707. bsOut = bs[:clen]
  2708. r.readb(bsOut)
  2709. } else {
  2710. // bsOut = make([]byte, clen)
  2711. len2 := decInferLen(clen, maxInitLen, 1)
  2712. bsOut = make([]byte, len2)
  2713. r.readb(bsOut)
  2714. for len2 < clen {
  2715. len3 := decInferLen(clen-len2, maxInitLen, 1)
  2716. bs3 := bsOut
  2717. bsOut = make([]byte, len2+len3)
  2718. copy(bsOut, bs3)
  2719. r.readb(bsOut[len2:])
  2720. len2 += len3
  2721. }
  2722. }
  2723. return
  2724. }
  2725. // func decByteSliceZeroCopy(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2726. // if _, ok := r.(*bytesDecReader); ok && clen <= maxInitLen {
  2727. // return r.readx(clen)
  2728. // }
  2729. // return decByteSlice(r, clen, maxInitLen, bs)
  2730. // }
  2731. func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
  2732. if xlen := len(in); xlen > 0 {
  2733. if isBytesReader || xlen <= scratchByteArrayLen {
  2734. if cap(dest) >= xlen {
  2735. out = dest[:xlen]
  2736. } else {
  2737. out = make([]byte, xlen)
  2738. }
  2739. copy(out, in)
  2740. return
  2741. }
  2742. }
  2743. return in
  2744. }
  2745. // decInferLen will infer a sensible length, given the following:
  2746. // - clen: length wanted.
  2747. // - maxlen: max length to be returned.
  2748. // if <= 0, it is unset, and we infer it based on the unit size
  2749. // - unit: number of bytes for each element of the collection
  2750. func decInferLen(clen, maxlen, unit int) (rvlen int) {
  2751. // handle when maxlen is not set i.e. <= 0
  2752. if clen <= 0 {
  2753. return
  2754. }
  2755. if unit == 0 {
  2756. return clen
  2757. }
  2758. if maxlen <= 0 {
  2759. // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
  2760. // maxlen = 256 * 1024 / unit
  2761. // if maxlen < (4 * 1024) {
  2762. // maxlen = 4 * 1024
  2763. // }
  2764. if unit < (256 / 4) {
  2765. maxlen = 256 * 1024 / unit
  2766. } else {
  2767. maxlen = 4 * 1024
  2768. }
  2769. }
  2770. if clen > maxlen {
  2771. rvlen = maxlen
  2772. } else {
  2773. rvlen = clen
  2774. }
  2775. return
  2776. }
  2777. func expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) (
  2778. s2 reflect.Value, scap2 int, changed bool, err string) {
  2779. l1 := slen + num // new slice length
  2780. if l1 < slen {
  2781. err = errmsgExpandSliceOverflow
  2782. return
  2783. }
  2784. if l1 <= scap {
  2785. if s.CanSet() {
  2786. s.SetLen(l1)
  2787. } else if canChange {
  2788. s2 = s.Slice(0, l1)
  2789. scap2 = scap
  2790. changed = true
  2791. } else {
  2792. err = errmsgExpandSliceCannotChange
  2793. return
  2794. }
  2795. return
  2796. }
  2797. if !canChange {
  2798. err = errmsgExpandSliceCannotChange
  2799. return
  2800. }
  2801. scap2 = growCap(scap, stElemSize, num)
  2802. s2 = reflect.MakeSlice(st, l1, scap2)
  2803. changed = true
  2804. reflect.Copy(s2, s)
  2805. return
  2806. }
  2807. func decReadFull(r io.Reader, bs []byte) (n uint, err error) {
  2808. var nn int
  2809. for n < uint(len(bs)) && err == nil {
  2810. nn, err = r.Read(bs[n:])
  2811. if nn > 0 {
  2812. if err == io.EOF {
  2813. // leave EOF for next time
  2814. err = nil
  2815. }
  2816. n += uint(nn)
  2817. }
  2818. }
  2819. // xdebugf("decReadFull: len(bs): %v, n: %v, err: %v", len(bs), n, err)
  2820. // do not do this - it serves no purpose
  2821. // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
  2822. return
  2823. }
  2824. func decNakedReadRawBytes(dr decDriver, d *Decoder, n *decNaked, rawToString bool) {
  2825. if rawToString {
  2826. n.v = valueTypeString
  2827. n.s = string(dr.DecodeBytes(d.b[:], true))
  2828. } else {
  2829. n.v = valueTypeBytes
  2830. n.l = dr.DecodeBytes(nil, false)
  2831. }
  2832. }