decode.go 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223
  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 // - 5 // + (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. DecodeInt64() (i int64)
  85. DecodeUint64() (ui uint64)
  86. DecodeFloat64() (f float64)
  87. DecodeBool() (b bool)
  88. // DecodeStringAsBytes returns the bytes representing a string.
  89. // By definition, it will return a view into a scratch buffer.
  90. //
  91. // Note: This can also decode symbols, if supported.
  92. //
  93. // Users should consume it right away and not store it for later use.
  94. DecodeStringAsBytes() (v []byte)
  95. // DecodeBytes may be called directly, without going through reflection.
  96. // Consequently, it must be designed to handle possible nil.
  97. DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte)
  98. // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
  99. // DecodeExt will decode into a *RawExt or into an extension.
  100. DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64)
  101. // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
  102. DecodeTime() (t time.Time)
  103. ReadArrayStart() int
  104. ReadArrayEnd()
  105. ReadMapStart() int
  106. ReadMapEnd()
  107. reset()
  108. atEndOfDecode()
  109. uncacheRead()
  110. }
  111. type decDriverContainerTracker interface {
  112. ReadArrayElem()
  113. ReadMapElemKey()
  114. ReadMapElemValue()
  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) ReadArrayEnd() {}
  126. func (x decDriverNoopContainerReader) ReadMapStart() (v int) { return }
  127. func (x decDriverNoopContainerReader) ReadMapEnd() {}
  128. func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return }
  129. func (x decDriverNoopContainerReader) atEndOfDecode() {}
  130. // func (x decDriverNoopContainerReader) ReadArrayElem() {}
  131. // func (x decDriverNoopContainerReader) ReadMapElemKey() {}
  132. // func (x decDriverNoopContainerReader) ReadMapElemValue() {}
  133. // func (x decNoSeparator) uncacheRead() {}
  134. // DecodeOptions captures configuration options during decode.
  135. type DecodeOptions struct {
  136. // MapType specifies type to use during schema-less decoding of a map in the stream.
  137. // If nil (unset), we default to map[string]interface{} iff json handle and MapStringAsKey=true,
  138. // else map[interface{}]interface{}.
  139. MapType reflect.Type
  140. // SliceType specifies type to use during schema-less decoding of an array in the stream.
  141. // If nil (unset), we default to []interface{} for all formats.
  142. SliceType reflect.Type
  143. // MaxInitLen defines the maxinum initial length that we "make" a collection
  144. // (string, slice, map, chan). If 0 or negative, we default to a sensible value
  145. // based on the size of an element in the collection.
  146. //
  147. // For example, when decoding, a stream may say that it has 2^64 elements.
  148. // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash.
  149. // Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
  150. MaxInitLen int
  151. // ReaderBufferSize is the size of the buffer used when reading.
  152. //
  153. // if > 0, we use a smart buffer internally for performance purposes.
  154. ReaderBufferSize int
  155. // MaxDepth defines the maximum depth when decoding nested
  156. // maps and slices. If 0 or negative, we default to a suitably large number (currently 1024).
  157. MaxDepth int16
  158. // If ErrorIfNoField, return an error when decoding a map
  159. // from a codec stream into a struct, and no matching struct field is found.
  160. ErrorIfNoField bool
  161. // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
  162. // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
  163. // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
  164. ErrorIfNoArrayExpand bool
  165. // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
  166. SignedInteger bool
  167. // MapValueReset controls how we decode into a map value.
  168. //
  169. // By default, we MAY retrieve the mapping for a key, and then decode into that.
  170. // However, especially with big maps, that retrieval may be expensive and unnecessary
  171. // if the stream already contains all that is necessary to recreate the value.
  172. //
  173. // If true, we will never retrieve the previous mapping,
  174. // but rather decode into a new value and set that in the map.
  175. //
  176. // If false, we will retrieve the previous mapping if necessary e.g.
  177. // the previous mapping is a pointer, or is a struct or array with pre-set state,
  178. // or is an interface.
  179. MapValueReset bool
  180. // SliceElementReset: on decoding a slice, reset the element to a zero value first.
  181. //
  182. // concern: if the slice already contained some garbage, we will decode into that garbage.
  183. SliceElementReset bool
  184. // InterfaceReset controls how we decode into an interface.
  185. //
  186. // By default, when we see a field that is an interface{...},
  187. // or a map with interface{...} value, we will attempt decoding into the
  188. // "contained" value.
  189. //
  190. // However, this prevents us from reading a string into an interface{}
  191. // that formerly contained a number.
  192. //
  193. // If true, we will decode into a new "blank" value, and set that in the interface.
  194. // If false, we will decode into whatever is contained in the interface.
  195. InterfaceReset bool
  196. // InternString controls interning of strings during decoding.
  197. //
  198. // Some handles, e.g. json, typically will read map keys as strings.
  199. // If the set of keys are finite, it may help reduce allocation to
  200. // look them up from a map (than to allocate them afresh).
  201. //
  202. // Note: Handles will be smart when using the intern functionality.
  203. // Every string should not be interned.
  204. // An excellent use-case for interning is struct field names,
  205. // or map keys where key type is string.
  206. InternString bool
  207. // PreferArrayOverSlice controls whether to decode to an array or a slice.
  208. //
  209. // This only impacts decoding into a nil interface{}.
  210. // Consequently, it has no effect on codecgen.
  211. //
  212. // *Note*: This only applies if using go1.5 and above,
  213. // as it requires reflect.ArrayOf support which was absent before go1.5.
  214. PreferArrayOverSlice bool
  215. // DeleteOnNilMapValue controls how to decode a nil value in the stream.
  216. //
  217. // If true, we will delete the mapping of the key.
  218. // Else, just set the mapping to the zero value of the type.
  219. DeleteOnNilMapValue bool
  220. // RawToString controls how raw bytes in a stream are decoded into a nil interface{}.
  221. // By default, they are decoded as []byte, but can be decoded as string (if configured).
  222. RawToString bool
  223. }
  224. // ------------------------------------------------
  225. type unreadByteStatus uint8
  226. // unreadByteStatus goes from
  227. // undefined (when initialized) -- (read) --> canUnread -- (unread) --> canRead ...
  228. const (
  229. unreadByteUndefined unreadByteStatus = iota
  230. unreadByteCanRead
  231. unreadByteCanUnread
  232. )
  233. type ioDecReaderCommon struct {
  234. r io.Reader // the reader passed in
  235. n uint // num read
  236. l byte // last byte
  237. ls unreadByteStatus // last byte status
  238. trb bool // tracking bytes turned on
  239. _ bool
  240. b [4]byte // tiny buffer for reading single bytes
  241. tr []byte // tracking bytes read
  242. }
  243. func (z *ioDecReaderCommon) reset(r io.Reader) {
  244. z.r = r
  245. z.ls = unreadByteUndefined
  246. z.l, z.n = 0, 0
  247. z.trb = false
  248. if z.tr != nil {
  249. z.tr = z.tr[:0]
  250. }
  251. }
  252. func (z *ioDecReaderCommon) numread() uint {
  253. return z.n
  254. }
  255. func (z *ioDecReaderCommon) track() {
  256. if z.tr != nil {
  257. z.tr = z.tr[:0]
  258. }
  259. z.trb = true
  260. }
  261. func (z *ioDecReaderCommon) stopTrack() (bs []byte) {
  262. z.trb = false
  263. return z.tr
  264. }
  265. // ------------------------------------------
  266. // ioDecReader is a decReader that reads off an io.Reader.
  267. //
  268. // It also has a fallback implementation of ByteScanner if needed.
  269. type ioDecReader struct {
  270. ioDecReaderCommon
  271. rr io.Reader
  272. br io.ByteScanner
  273. x [scratchByteArrayLen + 8]byte // for: get struct field name, swallow valueTypeBytes, etc
  274. // _ [1]uint64 // padding
  275. }
  276. func (z *ioDecReader) reset(r io.Reader) {
  277. z.ioDecReaderCommon.reset(r)
  278. var ok bool
  279. z.rr = r
  280. z.br, ok = r.(io.ByteScanner)
  281. if !ok {
  282. z.br = z
  283. z.rr = z
  284. }
  285. }
  286. func (z *ioDecReader) Read(p []byte) (n int, err error) {
  287. if len(p) == 0 {
  288. return
  289. }
  290. var firstByte bool
  291. if z.ls == unreadByteCanRead {
  292. z.ls = unreadByteCanUnread
  293. p[0] = z.l
  294. if len(p) == 1 {
  295. n = 1
  296. return
  297. }
  298. firstByte = true
  299. p = p[1:]
  300. }
  301. n, err = z.r.Read(p)
  302. if n > 0 {
  303. if err == io.EOF && n == len(p) {
  304. err = nil // read was successful, so postpone EOF (till next time)
  305. }
  306. z.l = p[n-1]
  307. z.ls = unreadByteCanUnread
  308. }
  309. if firstByte {
  310. n++
  311. }
  312. return
  313. }
  314. func (z *ioDecReader) ReadByte() (c byte, err error) {
  315. n, err := z.Read(z.b[:1])
  316. if n == 1 {
  317. c = z.b[0]
  318. if err == io.EOF {
  319. err = nil // read was successful, so postpone EOF (till next time)
  320. }
  321. }
  322. return
  323. }
  324. func (z *ioDecReader) UnreadByte() (err error) {
  325. switch z.ls {
  326. case unreadByteCanUnread:
  327. z.ls = unreadByteCanRead
  328. case unreadByteCanRead:
  329. err = errDecUnreadByteLastByteNotRead
  330. case unreadByteUndefined:
  331. err = errDecUnreadByteNothingToRead
  332. default:
  333. err = errDecUnreadByteUnknown
  334. }
  335. return
  336. }
  337. func (z *ioDecReader) readx(n uint) (bs []byte) {
  338. if n == 0 {
  339. return
  340. }
  341. if n < uint(len(z.x)) {
  342. bs = z.x[:n]
  343. } else {
  344. bs = make([]byte, n)
  345. }
  346. if _, err := decReadFull(z.rr, bs); err != nil {
  347. panic(err)
  348. }
  349. z.n += uint(len(bs))
  350. if z.trb {
  351. z.tr = append(z.tr, bs...)
  352. }
  353. return
  354. }
  355. func (z *ioDecReader) readb(bs []byte) {
  356. if len(bs) == 0 {
  357. return
  358. }
  359. if _, err := decReadFull(z.rr, bs); err != nil {
  360. panic(err)
  361. }
  362. z.n += uint(len(bs))
  363. if z.trb {
  364. z.tr = append(z.tr, bs...)
  365. }
  366. }
  367. func (z *ioDecReader) readn1eof() (b uint8, eof bool) {
  368. b, err := z.br.ReadByte()
  369. if err == nil {
  370. z.n++
  371. if z.trb {
  372. z.tr = append(z.tr, b)
  373. }
  374. } else if err == io.EOF {
  375. eof = true
  376. } else {
  377. panic(err)
  378. }
  379. return
  380. }
  381. func (z *ioDecReader) readn1() (b uint8) {
  382. b, err := z.br.ReadByte()
  383. if err == nil {
  384. z.n++
  385. if z.trb {
  386. z.tr = append(z.tr, b)
  387. }
  388. return
  389. }
  390. panic(err)
  391. }
  392. func (z *ioDecReader) skip(accept *bitset256) (token byte) {
  393. var eof bool
  394. // for {
  395. // token, eof = z.readn1eof()
  396. // if eof {
  397. // return
  398. // }
  399. // if accept.isset(token) {
  400. // continue
  401. // }
  402. // return
  403. // }
  404. LOOP:
  405. token, eof = z.readn1eof()
  406. if eof {
  407. return
  408. }
  409. if accept.isset(token) {
  410. goto LOOP
  411. }
  412. return
  413. }
  414. func (z *ioDecReader) readTo(in []byte, accept *bitset256) []byte {
  415. // out = in
  416. // for {
  417. // token, eof := z.readn1eof()
  418. // if eof {
  419. // return
  420. // }
  421. // if accept.isset(token) {
  422. // out = append(out, token)
  423. // } else {
  424. // z.unreadn1()
  425. // return
  426. // }
  427. // }
  428. LOOP:
  429. token, eof := z.readn1eof()
  430. if eof {
  431. return in
  432. }
  433. if accept.isset(token) {
  434. // out = append(out, token)
  435. in = append(in, token)
  436. goto LOOP
  437. }
  438. z.unreadn1()
  439. return in
  440. }
  441. func (z *ioDecReader) readUntil(in []byte, stop byte) (out []byte) {
  442. out = in
  443. // for {
  444. // token, eof := z.readn1eof()
  445. // if eof {
  446. // panic(io.EOF)
  447. // }
  448. // out = append(out, token)
  449. // if token == stop {
  450. // return
  451. // }
  452. // }
  453. LOOP:
  454. token, eof := z.readn1eof()
  455. if eof {
  456. panic(io.EOF)
  457. }
  458. out = append(out, token)
  459. if token == stop {
  460. return
  461. }
  462. goto LOOP
  463. }
  464. //go:noinline
  465. func (z *ioDecReader) unreadn1() {
  466. err := z.br.UnreadByte()
  467. if err != nil {
  468. panic(err)
  469. }
  470. z.n--
  471. if z.trb {
  472. if l := len(z.tr) - 1; l >= 0 {
  473. z.tr = z.tr[:l]
  474. }
  475. }
  476. }
  477. // ------------------------------------
  478. type bufioDecReader struct {
  479. ioDecReaderCommon
  480. _ uint64 // padding (cache-aligned)
  481. c uint // cursor
  482. buf []byte
  483. bytesBufPooler
  484. // err error
  485. // Extensions can call Decode() within a current Decode() call.
  486. // We need to know when the top level Decode() call returns,
  487. // so we can decide whether to Release() or not.
  488. calls uint16 // what depth in mustDecode are we in now.
  489. _ [6]uint8 // padding
  490. }
  491. func (z *bufioDecReader) reset(r io.Reader, bufsize int) {
  492. z.ioDecReaderCommon.reset(r)
  493. z.c = 0
  494. z.calls = 0
  495. if cap(z.buf) >= bufsize {
  496. z.buf = z.buf[:0]
  497. } else {
  498. z.buf = z.bytesBufPooler.get(bufsize)[:0]
  499. // z.buf = make([]byte, 0, bufsize)
  500. }
  501. }
  502. func (z *bufioDecReader) release() {
  503. z.buf = nil
  504. z.bytesBufPooler.end()
  505. }
  506. func (z *bufioDecReader) readb(p []byte) {
  507. var n = uint(copy(p, z.buf[z.c:]))
  508. z.n += n
  509. z.c += n
  510. if len(p) == int(n) {
  511. if z.trb {
  512. z.tr = append(z.tr, p...) // cost=9
  513. }
  514. } else {
  515. z.readbFill(p, n)
  516. }
  517. }
  518. //go:noinline - fallback when z.buf is consumed
  519. func (z *bufioDecReader) readbFill(p0 []byte, n uint) {
  520. // at this point, there's nothing in z.buf to read (z.buf is fully consumed)
  521. p := p0[n:]
  522. var n2 uint
  523. var err error
  524. if len(p) > cap(z.buf) {
  525. n2, err = decReadFull(z.r, p)
  526. if err != nil {
  527. panic(err)
  528. }
  529. n += n2
  530. z.n += n2
  531. // always keep last byte in z.buf
  532. z.buf = z.buf[:1]
  533. z.buf[0] = p[len(p)-1]
  534. z.c = 1
  535. if z.trb {
  536. z.tr = append(z.tr, p0[:n]...)
  537. }
  538. return
  539. }
  540. // z.c is now 0, and len(p) <= cap(z.buf)
  541. LOOP:
  542. // for len(p) > 0 && z.err == nil {
  543. if len(p) > 0 {
  544. z.buf = z.buf[0:cap(z.buf)]
  545. var n1 int
  546. n1, err = z.r.Read(z.buf)
  547. n2 = uint(n1)
  548. if n2 == 0 && err != nil {
  549. panic(err)
  550. }
  551. z.buf = z.buf[:n2]
  552. n2 = uint(copy(p, z.buf))
  553. z.c = n2
  554. n += n2
  555. z.n += n2
  556. p = p[n2:]
  557. goto LOOP
  558. }
  559. if z.c == 0 {
  560. z.buf = z.buf[:1]
  561. z.buf[0] = p[len(p)-1]
  562. z.c = 1
  563. }
  564. if z.trb {
  565. z.tr = append(z.tr, p0[:n]...)
  566. }
  567. }
  568. func (z *bufioDecReader) readn1() (b byte) {
  569. // fast-path, so we elide calling into Read() most of the time
  570. if z.c < uint(len(z.buf)) {
  571. b = z.buf[z.c]
  572. z.c++
  573. z.n++
  574. if z.trb {
  575. z.tr = append(z.tr, b)
  576. }
  577. } else { // meaning z.c == len(z.buf) or greater ... so need to fill
  578. z.readbFill(z.b[:1], 0)
  579. b = z.b[0]
  580. }
  581. return
  582. }
  583. func (z *bufioDecReader) unreadn1() {
  584. if z.c == 0 {
  585. panic(errDecUnreadByteNothingToRead)
  586. }
  587. z.c--
  588. z.n--
  589. if z.trb {
  590. z.tr = z.tr[:len(z.tr)-1]
  591. }
  592. }
  593. func (z *bufioDecReader) readx(n uint) (bs []byte) {
  594. if n == 0 {
  595. // return
  596. } else if z.c+n <= uint(len(z.buf)) {
  597. bs = z.buf[z.c : z.c+n]
  598. z.n += n
  599. z.c += n
  600. if z.trb {
  601. z.tr = append(z.tr, bs...)
  602. }
  603. } else {
  604. bs = make([]byte, n)
  605. // n no longer used - can reuse
  606. n = uint(copy(bs, z.buf[z.c:]))
  607. z.n += n
  608. z.c += n
  609. z.readbFill(bs, n)
  610. }
  611. return
  612. }
  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)
  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)
  1152. }
  1153. }
  1154. case valueTypeExt:
  1155. tag, bytes := n.u, n.l // calling decode below might taint the values
  1156. bfn := d.h.getExtForTag(tag)
  1157. var re = RawExt{Tag: tag}
  1158. if bytes == nil {
  1159. // it is one of the InterfaceExt ones: json and cbor.
  1160. // most likely cbor, as json decoding never reveals valueTypeExt (no tagging support)
  1161. if bfn == nil {
  1162. d.decode(&re.Value)
  1163. rvn = reflect.ValueOf(&re).Elem()
  1164. } else {
  1165. rvn = reflect.New(bfn.rt)
  1166. if bfn.ext == SelfExt {
  1167. d.decodeValue(rvn, d.h.fnNoExt(rvn.Type().Elem()))
  1168. } else {
  1169. d.interfaceExtConvertAndDecode(rv2i(rvn), bfn.ext)
  1170. }
  1171. rvn = rvn.Elem()
  1172. }
  1173. } else {
  1174. // one of the BytesExt ones: binc, msgpack, simple
  1175. if bfn == nil {
  1176. re.Data = detachZeroCopyBytes(d.bytes, nil, bytes)
  1177. rvn = reflect.ValueOf(&re).Elem()
  1178. } else {
  1179. rvn = reflect.New(bfn.rt)
  1180. if bfn.ext == SelfExt {
  1181. d.sideDecode(rv2i(rvn), bytes)
  1182. } else {
  1183. bfn.ext.ReadExt(rv2i(rvn), bytes)
  1184. }
  1185. rvn = rvn.Elem()
  1186. }
  1187. }
  1188. case valueTypeNil:
  1189. // no-op
  1190. case valueTypeInt:
  1191. rvn = n.ri()
  1192. case valueTypeUint:
  1193. rvn = n.ru()
  1194. case valueTypeFloat:
  1195. rvn = n.rf()
  1196. case valueTypeBool:
  1197. rvn = n.rb()
  1198. case valueTypeString, valueTypeSymbol:
  1199. rvn = n.rs()
  1200. case valueTypeBytes:
  1201. rvn = n.rl()
  1202. case valueTypeTime:
  1203. rvn = n.rt()
  1204. default:
  1205. panicv.errorf("kInterfaceNaked: unexpected valueType: %d", n.v)
  1206. }
  1207. return
  1208. }
  1209. func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
  1210. // Note:
  1211. // A consequence of how kInterface works, is that
  1212. // if an interface already contains something, we try
  1213. // to decode into what was there before.
  1214. // We do not replace with a generic value (as got from decodeNaked).
  1215. // every interface passed here MUST be settable.
  1216. var rvn reflect.Value
  1217. if rvisnil(rv) || d.h.InterfaceReset {
  1218. // check if mapping to a type: if so, initialize it and move on
  1219. rvn = d.h.intf2impl(f.ti.rtid)
  1220. if rvn.IsValid() {
  1221. rv.Set(rvn)
  1222. } else {
  1223. rvn = d.kInterfaceNaked(f)
  1224. if rvn.IsValid() {
  1225. rv.Set(rvn)
  1226. } else if d.h.InterfaceReset {
  1227. // reset to zero value based on current type in there.
  1228. rv.Set(reflect.Zero(rv.Elem().Type()))
  1229. }
  1230. return
  1231. }
  1232. } else {
  1233. // now we have a non-nil interface value, meaning it contains a type
  1234. rvn = rv.Elem()
  1235. }
  1236. if d.d.TryDecodeAsNil() {
  1237. rv.Set(reflect.Zero(rvn.Type()))
  1238. return
  1239. }
  1240. // Note: interface{} is settable, but underlying type may not be.
  1241. // Consequently, we MAY have to create a decodable value out of the underlying value,
  1242. // decode into it, and reset the interface itself.
  1243. // fmt.Printf(">>>> kInterface: rvn type: %v, rv type: %v\n", rvn.Type(), rv.Type())
  1244. rvn2, canDecode := isDecodeable(rvn)
  1245. if canDecode {
  1246. d.decodeValue(rvn2, nil)
  1247. return
  1248. }
  1249. rvn2 = reflect.New(rvn.Type()).Elem()
  1250. rvn2.Set(rvn)
  1251. d.decodeValue(rvn2, nil)
  1252. rv.Set(rvn2)
  1253. }
  1254. func decStructFieldKey(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) {
  1255. // use if-else-if, not switch (which compiles to binary-search)
  1256. // since keyType is typically valueTypeString, branch prediction is pretty good.
  1257. if keyType == valueTypeString {
  1258. rvkencname = dd.DecodeStringAsBytes()
  1259. } else if keyType == valueTypeInt {
  1260. rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10)
  1261. } else if keyType == valueTypeUint {
  1262. rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10)
  1263. } else if keyType == valueTypeFloat {
  1264. rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64)
  1265. } else {
  1266. rvkencname = dd.DecodeStringAsBytes()
  1267. }
  1268. return rvkencname
  1269. }
  1270. func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  1271. fti := f.ti
  1272. dd := d.d
  1273. sfn := structFieldNode{v: rv, update: true}
  1274. ctyp := dd.ContainerType()
  1275. var mf MissingFielder
  1276. if fti.mf {
  1277. mf = rv2i(rv).(MissingFielder)
  1278. } else if fti.mfp {
  1279. mf = rv2i(rv.Addr()).(MissingFielder)
  1280. }
  1281. if ctyp == valueTypeMap {
  1282. containerLen := d.mapStart()
  1283. if containerLen == 0 {
  1284. d.mapEnd()
  1285. return
  1286. }
  1287. tisfi := fti.sfiSort
  1288. hasLen := containerLen >= 0
  1289. var rvkencname []byte
  1290. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1291. d.mapElemKey()
  1292. rvkencname = decStructFieldKey(dd, fti.keyType, &d.b)
  1293. d.mapElemValue()
  1294. if k := fti.indexForEncName(rvkencname); k > -1 {
  1295. si := tisfi[k]
  1296. if dd.TryDecodeAsNil() {
  1297. si.setToZeroValue(rv)
  1298. } else {
  1299. d.decodeValue(sfn.field(si), nil)
  1300. }
  1301. } else if mf != nil {
  1302. // store rvkencname in new []byte, as it previously shares Decoder.b, which is used in decode
  1303. name2 := rvkencname
  1304. rvkencname = make([]byte, len(rvkencname))
  1305. copy(rvkencname, name2)
  1306. var f interface{}
  1307. d.decode(&f)
  1308. if !mf.CodecMissingField(rvkencname, f) && d.h.ErrorIfNoField {
  1309. d.errorf("no matching struct field found when decoding stream map with key: %s ",
  1310. stringView(rvkencname))
  1311. }
  1312. } else {
  1313. d.structFieldNotFound(-1, stringView(rvkencname))
  1314. }
  1315. // keepAlive4StringView(rvkencnameB) // not needed, as reference is outside loop
  1316. }
  1317. d.mapEnd()
  1318. } else if ctyp == valueTypeArray {
  1319. containerLen := d.arrayStart()
  1320. if containerLen == 0 {
  1321. d.arrayEnd()
  1322. return
  1323. }
  1324. // Not much gain from doing it two ways for array.
  1325. // Arrays are not used as much for structs.
  1326. hasLen := containerLen >= 0
  1327. var checkbreak bool
  1328. for j, si := range fti.sfiSrc {
  1329. if hasLen && j == containerLen {
  1330. break
  1331. }
  1332. if !hasLen && dd.CheckBreak() {
  1333. checkbreak = true
  1334. break
  1335. }
  1336. d.arrayElem()
  1337. if dd.TryDecodeAsNil() {
  1338. si.setToZeroValue(rv)
  1339. } else {
  1340. d.decodeValue(sfn.field(si), nil)
  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. d.arrayElem()
  1350. d.structFieldNotFound(j, "")
  1351. }
  1352. }
  1353. d.arrayEnd()
  1354. } else {
  1355. d.errorstr(errstrOnlyMapOrArrayCanDecodeIntoStruct)
  1356. return
  1357. }
  1358. }
  1359. func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
  1360. // A slice can be set from a map or array in stream.
  1361. // This way, the order can be kept (as order is lost with map).
  1362. frt := f.ti.rt
  1363. if f.seq == seqTypeChan && f.ti.chandir&uint8(reflect.SendDir) == 0 {
  1364. d.errorf("receive-only channel cannot be decoded")
  1365. }
  1366. dd := d.d
  1367. rtelem0 := f.ti.elem
  1368. ctyp := dd.ContainerType()
  1369. if ctyp == valueTypeBytes || ctyp == valueTypeString {
  1370. // you can only decode bytes or string in the stream into a slice or array of bytes
  1371. if !(f.ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) {
  1372. d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", frt)
  1373. }
  1374. if f.seq == seqTypeChan {
  1375. bs2 := dd.DecodeBytes(nil, true)
  1376. irv := rv2i(rv)
  1377. ch, ok := irv.(chan<- byte)
  1378. if !ok {
  1379. ch = irv.(chan byte)
  1380. }
  1381. for _, b := range bs2 {
  1382. ch <- b
  1383. }
  1384. } else {
  1385. rvbs := rv.Bytes()
  1386. bs2 := dd.DecodeBytes(rvbs, false)
  1387. // if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) {
  1388. if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
  1389. if rv.CanSet() {
  1390. rv.SetBytes(bs2)
  1391. } else if len(rvbs) > 0 && len(bs2) > 0 {
  1392. copy(rvbs, bs2)
  1393. }
  1394. }
  1395. }
  1396. return
  1397. }
  1398. // array := f.seq == seqTypeChan
  1399. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map)
  1400. // an array can never return a nil slice. so no need to check f.array here.
  1401. if containerLenS == 0 {
  1402. if rv.CanSet() {
  1403. if f.seq == seqTypeSlice {
  1404. if rvisnil(rv) {
  1405. rv.Set(reflect.MakeSlice(frt, 0, 0))
  1406. } else {
  1407. rvssetlen(rv, 0)
  1408. }
  1409. } else if f.seq == seqTypeChan {
  1410. if rvisnil(rv) {
  1411. rv.Set(reflect.MakeChan(frt, 0))
  1412. }
  1413. }
  1414. }
  1415. slh.End()
  1416. return
  1417. }
  1418. rtelem0Size := int(rtelem0.Size())
  1419. rtElem0Kind := rtelem0.Kind()
  1420. rtelem0Mut := !isImmutableKind(rtElem0Kind)
  1421. rtelem := rtelem0
  1422. rtelemkind := rtelem.Kind()
  1423. for rtelemkind == reflect.Ptr {
  1424. rtelem = rtelem.Elem()
  1425. rtelemkind = rtelem.Kind()
  1426. }
  1427. var fn *codecFn
  1428. var rvCanset = rv.CanSet()
  1429. var rvChanged bool
  1430. var rv0 = rv
  1431. var rv9 reflect.Value
  1432. rvlen := rv.Len()
  1433. rvcap := rv.Cap()
  1434. hasLen := containerLenS > 0
  1435. if hasLen && f.seq == seqTypeSlice {
  1436. if containerLenS > rvcap {
  1437. oldRvlenGtZero := rvlen > 0
  1438. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size()))
  1439. if rvlen <= rvcap {
  1440. if rvCanset {
  1441. rvssetlen(rv, rvlen)
  1442. }
  1443. } else if rvCanset {
  1444. rv = reflect.MakeSlice(frt, rvlen, rvlen)
  1445. rvcap = rvlen
  1446. rvChanged = true
  1447. } else {
  1448. d.errorf("cannot decode into non-settable slice")
  1449. }
  1450. if rvChanged && oldRvlenGtZero && rtelem0Mut { // !isImmutableKind(rtelem0.Kind()) {
  1451. reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
  1452. }
  1453. } else if containerLenS != rvlen {
  1454. rvlen = containerLenS
  1455. if rvCanset {
  1456. rvssetlen(rv, rvlen)
  1457. }
  1458. // else {
  1459. // rv = rv.Slice(0, rvlen)
  1460. // rvChanged = true
  1461. // d.errorf("cannot decode into non-settable slice")
  1462. // }
  1463. }
  1464. }
  1465. // consider creating new element once, and just decoding into it.
  1466. var rtelem0Zero reflect.Value
  1467. var rtelem0ZeroValid bool
  1468. var decodeAsNil bool
  1469. var j int
  1470. for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ {
  1471. if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rvisnil(rv) {
  1472. if hasLen {
  1473. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size)
  1474. } else if f.seq == seqTypeSlice {
  1475. rvlen = decDefSliceCap
  1476. } else {
  1477. rvlen = decDefChanCap
  1478. }
  1479. if rvCanset {
  1480. if f.seq == seqTypeSlice {
  1481. rv = reflect.MakeSlice(frt, rvlen, rvlen)
  1482. rvChanged = true
  1483. } else { // chan
  1484. rv = reflect.MakeChan(frt, rvlen)
  1485. rvChanged = true
  1486. }
  1487. } else {
  1488. d.errorf("cannot decode into non-settable slice")
  1489. }
  1490. }
  1491. slh.ElemContainerState(j)
  1492. decodeAsNil = dd.TryDecodeAsNil()
  1493. if f.seq == seqTypeChan {
  1494. if decodeAsNil {
  1495. rv.Send(reflect.Zero(rtelem0))
  1496. continue
  1497. }
  1498. if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rvisnil(rv9)) {
  1499. rv9 = reflect.New(rtelem0).Elem()
  1500. }
  1501. if fn == nil {
  1502. fn = d.h.fn(rtelem)
  1503. }
  1504. d.decodeValue(rv9, fn)
  1505. rv.Send(rv9)
  1506. } else {
  1507. // if indefinite, etc, then expand the slice if necessary
  1508. var decodeIntoBlank bool
  1509. if j >= rvlen {
  1510. if f.seq == seqTypeArray {
  1511. d.arrayCannotExpand(rvlen, j+1)
  1512. decodeIntoBlank = true
  1513. } else { // if f.seq == seqTypeSlice
  1514. // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // append logic + varargs
  1515. var rvcap2 int
  1516. var rvErrmsg2 string
  1517. rv9, rvcap2, rvChanged, rvErrmsg2 =
  1518. expandSliceRV(rv, frt, rvCanset, rtelem0Size, 1, rvlen, rvcap)
  1519. if rvErrmsg2 != "" {
  1520. d.errorf(rvErrmsg2)
  1521. }
  1522. rvlen++
  1523. if rvChanged {
  1524. rv = rv9
  1525. rvcap = rvcap2
  1526. }
  1527. }
  1528. }
  1529. if decodeIntoBlank {
  1530. if !decodeAsNil {
  1531. d.swallow()
  1532. }
  1533. } else {
  1534. rv9 = rv.Index(j)
  1535. if d.h.SliceElementReset || decodeAsNil {
  1536. if !rtelem0ZeroValid {
  1537. rtelem0ZeroValid = true
  1538. rtelem0Zero = reflect.Zero(rtelem0)
  1539. }
  1540. rv9.Set(rtelem0Zero)
  1541. if decodeAsNil {
  1542. continue
  1543. }
  1544. }
  1545. if fn == nil {
  1546. fn = d.h.fn(rtelem)
  1547. }
  1548. d.decodeValue(rv9, fn)
  1549. }
  1550. }
  1551. }
  1552. if f.seq == seqTypeSlice {
  1553. if j < rvlen {
  1554. if rv.CanSet() {
  1555. rvssetlen(rv, j)
  1556. } else if rvCanset {
  1557. rv = rv.Slice(0, j)
  1558. rvChanged = true
  1559. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1560. rvlen = j
  1561. } else if j == 0 && rvisnil(rv) {
  1562. if rvCanset {
  1563. rv = reflect.MakeSlice(frt, 0, 0)
  1564. rvChanged = true
  1565. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1566. }
  1567. }
  1568. slh.End()
  1569. if rvChanged { // infers rvCanset=true, so it can be reset
  1570. rv0.Set(rv)
  1571. }
  1572. }
  1573. // func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
  1574. // // d.decodeValueFn(rv.Slice(0, rv.Len()))
  1575. // f.kSlice(rv.Slice(0, rv.Len()))
  1576. // }
  1577. func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
  1578. dd := d.d
  1579. containerLen := d.mapStart()
  1580. ti := f.ti
  1581. if rvisnil(rv) {
  1582. rvlen := decInferLen(containerLen, d.h.MaxInitLen, int(ti.key.Size()+ti.elem.Size()))
  1583. rv.Set(makeMapReflect(ti.rt, rvlen))
  1584. }
  1585. if containerLen == 0 {
  1586. d.mapEnd()
  1587. return
  1588. }
  1589. ktype, vtype := ti.key, ti.elem
  1590. ktypeId := rt2id(ktype)
  1591. vtypeKind := vtype.Kind()
  1592. // ktypeKind := ktype.Kind()
  1593. var keyFn, valFn *codecFn
  1594. var ktypeLo, vtypeLo reflect.Type
  1595. for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
  1596. }
  1597. for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
  1598. }
  1599. rvvMut := !isImmutableKind(vtypeKind)
  1600. // we do a mapGet if kind is mutable, and InterfaceReset=true if interface
  1601. var mapGet, mapSet bool
  1602. if !d.h.MapValueReset {
  1603. if rvvMut {
  1604. if vtypeKind == reflect.Interface {
  1605. if !d.h.InterfaceReset {
  1606. mapGet = true
  1607. }
  1608. } else {
  1609. mapGet = true
  1610. }
  1611. }
  1612. }
  1613. var rvk, rvkn, rvv, rvvn, rvva, rvvz reflect.Value
  1614. var rvvaSet bool
  1615. rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk.
  1616. ktypeIsString := ktypeId == stringTypId
  1617. ktypeIsIntf := ktypeId == intfTypId
  1618. hasLen := containerLen > 0
  1619. var kstrbs []byte
  1620. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1621. if j == 0 {
  1622. // rvvz = reflect.Zero(vtype)
  1623. // rvkz = reflect.Zero(ktype)
  1624. if !rvkMut {
  1625. rvkn = reflect.New(ktype).Elem() //, ktypeKind)
  1626. }
  1627. if !rvvMut {
  1628. rvvn = reflect.New(vtype).Elem() //, vtypeKind)
  1629. }
  1630. }
  1631. if rvkMut {
  1632. rvk = reflect.New(ktype).Elem() //, ktypeKind)
  1633. } else {
  1634. rvk = rvkn
  1635. }
  1636. d.mapElemKey()
  1637. if ktypeIsString {
  1638. kstrbs = dd.DecodeStringAsBytes()
  1639. rvk.SetString(stringView(kstrbs)) // NOTE: if doing an insert, use real string (not stringview)
  1640. } else {
  1641. if keyFn == nil {
  1642. keyFn = d.h.fn(ktypeLo)
  1643. }
  1644. d.decodeValue(rvk, keyFn)
  1645. }
  1646. // special case if interface wrapping a byte array.
  1647. if ktypeIsIntf {
  1648. if rvk2 := rvk.Elem(); rvk2.IsValid() && rvk2.Type() == uint8SliceTyp {
  1649. rvk.Set(reflect.ValueOf(d.string(rvk2.Bytes())))
  1650. }
  1651. // NOTE: consider failing early if map/slice/func
  1652. }
  1653. d.mapElemValue()
  1654. // Brittle, but OK per TryDecodeAsNil() contract.
  1655. // i.e. TryDecodeAsNil never shares slices with other decDriver procedures
  1656. if dd.TryDecodeAsNil() {
  1657. if d.h.DeleteOnNilMapValue {
  1658. rv.SetMapIndex(rvk, reflect.Value{})
  1659. } else {
  1660. if ktypeIsString { // set to a real string (not string view)
  1661. rvk.SetString(d.string(kstrbs))
  1662. }
  1663. if !rvvz.IsValid() {
  1664. rvvz = reflect.Zero(vtype)
  1665. }
  1666. rv.SetMapIndex(rvk, rvvz)
  1667. }
  1668. continue
  1669. }
  1670. mapSet = true // set to false if u do a get, and its a non-nil pointer
  1671. if mapGet {
  1672. if !rvvaSet {
  1673. rvva = mapAddressableRV(vtype)
  1674. rvvaSet = true
  1675. }
  1676. rvv = mapIndex(rv, rvk, rvva) // reflect.Value{})
  1677. if vtypeKind == reflect.Ptr {
  1678. if rvv.IsValid() && !rvisnil(rvv) {
  1679. mapSet = false
  1680. } else {
  1681. rvv = reflect.New(vtype.Elem())
  1682. }
  1683. } else if rvv.IsValid() && vtypeKind == reflect.Interface && !rvisnil(rvv) {
  1684. rvvn = reflect.New(vtype).Elem()
  1685. rvvn.Set(rvv)
  1686. rvv = rvvn
  1687. } else if rvvMut {
  1688. rvv = reflect.New(vtype).Elem()
  1689. } else {
  1690. rvv = rvvn
  1691. }
  1692. } else if rvvMut {
  1693. rvv = reflect.New(vtype).Elem() //, vtypeKind)
  1694. } else {
  1695. rvv = rvvn
  1696. }
  1697. if valFn == nil {
  1698. valFn = d.h.fn(vtypeLo)
  1699. }
  1700. // We MUST be done with the stringview of the key, BEFORE decoding the value (rvv)
  1701. // so that we don't unknowingly reuse the rvk backing buffer during rvv decode.
  1702. if mapSet && ktypeIsString { // set to a real string (not string view)
  1703. rvk.SetString(d.string(kstrbs))
  1704. }
  1705. d.decodeValue(rvv, valFn)
  1706. if mapSet {
  1707. rv.SetMapIndex(rvk, rvv)
  1708. }
  1709. // if ktypeIsString {
  1710. // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop
  1711. // }
  1712. }
  1713. d.mapEnd()
  1714. }
  1715. // decNaked is used to keep track of the primitives decoded.
  1716. // Without it, we would have to decode each primitive and wrap it
  1717. // in an interface{}, causing an allocation.
  1718. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  1719. // so we can rest assured that no other decoding happens while these
  1720. // primitives are being decoded.
  1721. //
  1722. // maps and arrays are not handled by this mechanism.
  1723. // However, RawExt is, and we accommodate for extensions that decode
  1724. // RawExt from DecodeNaked, but need to decode the value subsequently.
  1725. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
  1726. //
  1727. // However, decNaked also keeps some arrays of default maps and slices
  1728. // used in DecodeNaked. This way, we can get a pointer to it
  1729. // without causing a new heap allocation.
  1730. //
  1731. // kInterfaceNaked will ensure that there is no allocation for the common
  1732. // uses.
  1733. type decNaked struct {
  1734. // r RawExt // used for RawExt, uint, []byte.
  1735. // primitives below
  1736. u uint64
  1737. i int64
  1738. f float64
  1739. l []byte
  1740. s string
  1741. // ---- cpu cache line boundary?
  1742. t time.Time
  1743. b bool
  1744. // state
  1745. v valueType
  1746. // _ [6]bool // padding
  1747. // ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above
  1748. //
  1749. // _ [3]uint64 // padding
  1750. }
  1751. // func (n *decNaked) init() {
  1752. // n.ru = reflect.ValueOf(&n.u).Elem()
  1753. // n.ri = reflect.ValueOf(&n.i).Elem()
  1754. // n.rf = reflect.ValueOf(&n.f).Elem()
  1755. // n.rl = reflect.ValueOf(&n.l).Elem()
  1756. // n.rs = reflect.ValueOf(&n.s).Elem()
  1757. // n.rt = reflect.ValueOf(&n.t).Elem()
  1758. // n.rb = reflect.ValueOf(&n.b).Elem()
  1759. // // n.rr[] = reflect.ValueOf(&n.)
  1760. // }
  1761. // type decNakedPooler struct {
  1762. // n *decNaked
  1763. // nsp *sync.Pool
  1764. // }
  1765. // // naked must be called before each call to .DecodeNaked, as they will use it.
  1766. // func (d *decNakedPooler) naked() *decNaked {
  1767. // if d.n == nil {
  1768. // // consider one of:
  1769. // // - get from sync.Pool (if GC is frequent, there's no value here)
  1770. // // - new alloc (safest. only init'ed if it a naked decode will be done)
  1771. // // - field in Decoder (makes the Decoder struct very big)
  1772. // // To support using a decoder where a DecodeNaked is not needed,
  1773. // // we prefer #1 or #2.
  1774. // // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool
  1775. // // d.n.init()
  1776. // var v interface{}
  1777. // d.nsp, v = pool.decNaked()
  1778. // d.n = v.(*decNaked)
  1779. // }
  1780. // return d.n
  1781. // }
  1782. // func (d *decNakedPooler) end() {
  1783. // if d.n != nil {
  1784. // // if n != nil, then nsp != nil (they are always set together)
  1785. // d.nsp.Put(d.n)
  1786. // d.n, d.nsp = nil, nil
  1787. // }
  1788. // }
  1789. // type rtid2rv struct {
  1790. // rtid uintptr
  1791. // rv reflect.Value
  1792. // }
  1793. // --------------
  1794. type decReaderSwitch struct {
  1795. esep bool // has elem separators
  1796. mtr, str bool // whether maptype or slicetype are known types
  1797. be bool // is binary encoding
  1798. js bool // is json handle
  1799. jsms bool // is json handle, and MapKeyAsString
  1800. // typ entryType
  1801. bytes bool // is bytes reader
  1802. bufio bool // is this a bufioDecReader?
  1803. rb bytesDecReader
  1804. ri *ioDecReader
  1805. bi *bufioDecReader
  1806. }
  1807. // numread, track and stopTrack are always inlined, as they just check int fields, etc.
  1808. /*
  1809. func (z *decReaderSwitch) numread() int {
  1810. switch z.typ {
  1811. case entryTypeBytes:
  1812. return z.rb.numread()
  1813. case entryTypeIo:
  1814. return z.ri.numread()
  1815. default:
  1816. return z.bi.numread()
  1817. }
  1818. }
  1819. func (z *decReaderSwitch) track() {
  1820. switch z.typ {
  1821. case entryTypeBytes:
  1822. z.rb.track()
  1823. case entryTypeIo:
  1824. z.ri.track()
  1825. default:
  1826. z.bi.track()
  1827. }
  1828. }
  1829. func (z *decReaderSwitch) stopTrack() []byte {
  1830. switch z.typ {
  1831. case entryTypeBytes:
  1832. return z.rb.stopTrack()
  1833. case entryTypeIo:
  1834. return z.ri.stopTrack()
  1835. default:
  1836. return z.bi.stopTrack()
  1837. }
  1838. }
  1839. func (z *decReaderSwitch) unreadn1() {
  1840. switch z.typ {
  1841. case entryTypeBytes:
  1842. z.rb.unreadn1()
  1843. case entryTypeIo:
  1844. z.ri.unreadn1()
  1845. default:
  1846. z.bi.unreadn1()
  1847. }
  1848. }
  1849. func (z *decReaderSwitch) readx(n int) []byte {
  1850. switch z.typ {
  1851. case entryTypeBytes:
  1852. return z.rb.readx(n)
  1853. case entryTypeIo:
  1854. return z.ri.readx(n)
  1855. default:
  1856. return z.bi.readx(n)
  1857. }
  1858. }
  1859. func (z *decReaderSwitch) readb(s []byte) {
  1860. switch z.typ {
  1861. case entryTypeBytes:
  1862. z.rb.readb(s)
  1863. case entryTypeIo:
  1864. z.ri.readb(s)
  1865. default:
  1866. z.bi.readb(s)
  1867. }
  1868. }
  1869. func (z *decReaderSwitch) readn1() uint8 {
  1870. switch z.typ {
  1871. case entryTypeBytes:
  1872. return z.rb.readn1()
  1873. case entryTypeIo:
  1874. return z.ri.readn1()
  1875. default:
  1876. return z.bi.readn1()
  1877. }
  1878. }
  1879. func (z *decReaderSwitch) skip(accept *bitset256) (token byte) {
  1880. switch z.typ {
  1881. case entryTypeBytes:
  1882. return z.rb.skip(accept)
  1883. case entryTypeIo:
  1884. return z.ri.skip(accept)
  1885. default:
  1886. return z.bi.skip(accept)
  1887. }
  1888. }
  1889. func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) {
  1890. switch z.typ {
  1891. case entryTypeBytes:
  1892. return z.rb.readTo(in, accept)
  1893. case entryTypeIo:
  1894. return z.ri.readTo(in, accept)
  1895. default:
  1896. return z.bi.readTo(in, accept)
  1897. }
  1898. }
  1899. func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) {
  1900. switch z.typ {
  1901. case entryTypeBytes:
  1902. return z.rb.readUntil(in, stop)
  1903. case entryTypeIo:
  1904. return z.ri.readUntil(in, stop)
  1905. default:
  1906. return z.bi.readUntil(in, stop)
  1907. }
  1908. }
  1909. */
  1910. // the if/else-if/else block is expensive to inline.
  1911. // Each node of this construct costs a lot and dominates the budget.
  1912. // Best to only do an if fast-path else block (so fast-path is inlined).
  1913. // This is irrespective of inlineExtraCallCost set in $GOROOT/src/cmd/compile/internal/gc/inl.go
  1914. //
  1915. // In decReaderSwitch methods below, we delegate all IO functions into their own methods.
  1916. // This allows for the inlining of the common path when z.bytes=true.
  1917. // Go 1.12+ supports inlining methods with up to 1 inlined function (or 2 if no other constructs).
  1918. func (z *decReaderSwitch) numread() uint {
  1919. if z.bytes {
  1920. return z.rb.numread()
  1921. } else if z.bufio {
  1922. return z.bi.numread()
  1923. } else {
  1924. return z.ri.numread()
  1925. }
  1926. }
  1927. func (z *decReaderSwitch) track() {
  1928. if z.bytes {
  1929. z.rb.track()
  1930. } else if z.bufio {
  1931. z.bi.track()
  1932. } else {
  1933. z.ri.track()
  1934. }
  1935. }
  1936. func (z *decReaderSwitch) stopTrack() []byte {
  1937. if z.bytes {
  1938. return z.rb.stopTrack()
  1939. } else if z.bufio {
  1940. return z.bi.stopTrack()
  1941. } else {
  1942. return z.ri.stopTrack()
  1943. }
  1944. }
  1945. // func (z *decReaderSwitch) unreadn1() {
  1946. // if z.bytes {
  1947. // z.rb.unreadn1()
  1948. // } else {
  1949. // z.unreadn1IO()
  1950. // }
  1951. // }
  1952. // func (z *decReaderSwitch) unreadn1IO() {
  1953. // if z.bufio {
  1954. // z.bi.unreadn1()
  1955. // } else {
  1956. // z.ri.unreadn1()
  1957. // }
  1958. // }
  1959. func (z *decReaderSwitch) unreadn1() {
  1960. if z.bytes {
  1961. z.rb.unreadn1()
  1962. } else if z.bufio {
  1963. z.bi.unreadn1()
  1964. } else {
  1965. z.ri.unreadn1() // not inlined
  1966. }
  1967. }
  1968. func (z *decReaderSwitch) readx(n uint) []byte {
  1969. if z.bytes {
  1970. return z.rb.readx(n)
  1971. }
  1972. return z.readxIO(n)
  1973. }
  1974. func (z *decReaderSwitch) readxIO(n uint) []byte {
  1975. if z.bufio {
  1976. return z.bi.readx(n)
  1977. }
  1978. return z.ri.readx(n)
  1979. }
  1980. func (z *decReaderSwitch) readb(s []byte) {
  1981. if z.bytes {
  1982. z.rb.readb(s)
  1983. } else {
  1984. z.readbIO(s)
  1985. }
  1986. }
  1987. //go:noinline - fallback for io, ensures z.bytes path is inlined
  1988. func (z *decReaderSwitch) readbIO(s []byte) {
  1989. if z.bufio {
  1990. z.bi.readb(s)
  1991. } else {
  1992. z.ri.readb(s)
  1993. }
  1994. }
  1995. func (z *decReaderSwitch) readn1() uint8 {
  1996. if z.bytes {
  1997. return z.rb.readn1()
  1998. }
  1999. return z.readn1IO()
  2000. }
  2001. func (z *decReaderSwitch) readn1IO() uint8 {
  2002. if z.bufio {
  2003. return z.bi.readn1()
  2004. }
  2005. return z.ri.readn1()
  2006. }
  2007. func (z *decReaderSwitch) skip(accept *bitset256) (token byte) {
  2008. if z.bytes {
  2009. return z.rb.skip(accept)
  2010. }
  2011. return z.skipIO(accept)
  2012. }
  2013. func (z *decReaderSwitch) skipIO(accept *bitset256) (token byte) {
  2014. if z.bufio {
  2015. return z.bi.skip(accept)
  2016. }
  2017. return z.ri.skip(accept)
  2018. }
  2019. func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) {
  2020. if z.bytes {
  2021. return z.rb.readToNoInput(accept) // z.rb.readTo(in, accept)
  2022. }
  2023. return z.readToIO(in, accept)
  2024. }
  2025. //go:noinline - fallback for io, ensures z.bytes path is inlined
  2026. func (z *decReaderSwitch) readToIO(in []byte, accept *bitset256) (out []byte) {
  2027. if z.bufio {
  2028. return z.bi.readTo(in, accept)
  2029. }
  2030. return z.ri.readTo(in, accept)
  2031. }
  2032. func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) {
  2033. if z.bytes {
  2034. return z.rb.readUntilNoInput(stop)
  2035. }
  2036. return z.readUntilIO(in, stop)
  2037. }
  2038. func (z *decReaderSwitch) readUntilIO(in []byte, stop byte) (out []byte) {
  2039. if z.bufio {
  2040. return z.bi.readUntil(in, stop)
  2041. }
  2042. return z.ri.readUntil(in, stop)
  2043. }
  2044. // Decoder reads and decodes an object from an input stream in a supported format.
  2045. //
  2046. // Decoder is NOT safe for concurrent use i.e. a Decoder cannot be used
  2047. // concurrently in multiple goroutines.
  2048. //
  2049. // However, as Decoder could be allocation heavy to initialize, a Reset method is provided
  2050. // so its state can be reused to decode new input streams repeatedly.
  2051. // This is the idiomatic way to use.
  2052. type Decoder struct {
  2053. panicHdl
  2054. // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
  2055. // Try to put things that go together to fit within a cache line (8 words).
  2056. d decDriver
  2057. // NOTE: Decoder shouldn't call its read methods,
  2058. // as the handler MAY need to do some coordination.
  2059. // r *decReaderSwitch
  2060. // bi *bufioDecReader
  2061. // cache the mapTypeId and sliceTypeId for faster comparisons
  2062. mtid uintptr
  2063. stid uintptr
  2064. jdec *jsonDecDriver
  2065. h *BasicHandle
  2066. hh Handle
  2067. // ---- cpu cache line boundary?
  2068. decReaderSwitch
  2069. // ---- cpu cache line boundary?
  2070. n decNaked
  2071. // cr containerStateRecv
  2072. // _ [4]uint8 // padding
  2073. is map[string]string // used for interning strings
  2074. err error
  2075. // ---- cpu cache line boundary?
  2076. // ---- writable fields during execution --- *try* to keep in sep cache line
  2077. maxdepth int16
  2078. depth int16
  2079. c containerState
  2080. _ [3]byte // padding
  2081. b [decScratchByteArrayLen]byte // scratch buffer, used by Decoder and xxxDecDrivers
  2082. // padding - false sharing help // modify 232 if Decoder struct changes.
  2083. // _ [cacheLineSize - 232%cacheLineSize]byte
  2084. }
  2085. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  2086. //
  2087. // For efficiency, Users are encouraged to configure ReaderBufferSize on the handle
  2088. // OR pass in a memory buffered reader (eg bufio.Reader, bytes.Buffer).
  2089. func NewDecoder(r io.Reader, h Handle) *Decoder {
  2090. d := newDecoder(h)
  2091. d.Reset(r)
  2092. return d
  2093. }
  2094. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  2095. // from a byte slice with zero copying.
  2096. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  2097. d := newDecoder(h)
  2098. d.ResetBytes(in)
  2099. return d
  2100. }
  2101. // var defaultDecNaked decNaked
  2102. func newDecoder(h Handle) *Decoder {
  2103. d := &Decoder{h: basicHandle(h), err: errDecoderNotInitialized}
  2104. d.bytes = true
  2105. if useFinalizers {
  2106. runtime.SetFinalizer(d, (*Decoder).finalize)
  2107. }
  2108. // d.r = &d.decReaderSwitch
  2109. d.hh = h
  2110. d.be = h.isBinary()
  2111. // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
  2112. var jh *JsonHandle
  2113. jh, d.js = h.(*JsonHandle)
  2114. d.jdec = nil
  2115. if d.js {
  2116. d.jsms = jh.MapKeyAsString
  2117. }
  2118. d.esep = d.hh.hasElemSeparators()
  2119. if d.h.InternString {
  2120. d.is = make(map[string]string, 32)
  2121. }
  2122. d.d = h.newDecDriver(d)
  2123. if d.js {
  2124. d.jdec = d.d.(*jsonDecDriver)
  2125. }
  2126. // d.cr, _ = d.d.(containerStateRecv)
  2127. return d
  2128. }
  2129. func (d *Decoder) r() *decReaderSwitch {
  2130. return &d.decReaderSwitch
  2131. }
  2132. func (d *Decoder) resetCommon() {
  2133. // d.r = &d.decReaderSwitch
  2134. d.d.reset()
  2135. d.err = nil
  2136. d.depth = 0
  2137. d.maxdepth = d.h.MaxDepth
  2138. if d.maxdepth <= 0 {
  2139. d.maxdepth = decDefMaxDepth
  2140. }
  2141. // reset all things which were cached from the Handle, but could change
  2142. d.mtid, d.stid = 0, 0
  2143. d.mtr, d.str = false, false
  2144. if d.h.MapType != nil {
  2145. d.mtid = rt2id(d.h.MapType)
  2146. d.mtr = fastpathAV.index(d.mtid) != -1
  2147. }
  2148. if d.h.SliceType != nil {
  2149. d.stid = rt2id(d.h.SliceType)
  2150. d.str = fastpathAV.index(d.stid) != -1
  2151. }
  2152. }
  2153. // Reset the Decoder with a new Reader to decode from,
  2154. // clearing all state from last run(s).
  2155. func (d *Decoder) Reset(r io.Reader) {
  2156. if r == nil {
  2157. return
  2158. }
  2159. d.bytes = false
  2160. // d.typ = entryTypeUnset
  2161. if d.h.ReaderBufferSize > 0 {
  2162. if d.bi == nil {
  2163. d.bi = new(bufioDecReader)
  2164. }
  2165. d.bi.reset(r, d.h.ReaderBufferSize)
  2166. // d.r = d.bi
  2167. // d.typ = entryTypeBufio
  2168. d.bufio = true
  2169. } else {
  2170. // d.ri.x = &d.b
  2171. // d.s = d.sa[:0]
  2172. if d.ri == nil {
  2173. d.ri = new(ioDecReader)
  2174. }
  2175. d.ri.reset(r)
  2176. // d.r = d.ri
  2177. // d.typ = entryTypeIo
  2178. d.bufio = false
  2179. }
  2180. d.resetCommon()
  2181. }
  2182. // ResetBytes resets the Decoder with a new []byte to decode from,
  2183. // clearing all state from last run(s).
  2184. func (d *Decoder) ResetBytes(in []byte) {
  2185. if in == nil {
  2186. return
  2187. }
  2188. d.bytes = true
  2189. d.bufio = false
  2190. // d.typ = entryTypeBytes
  2191. d.rb.reset(in)
  2192. // d.r = &d.rb
  2193. d.resetCommon()
  2194. }
  2195. func (d *Decoder) naked() *decNaked {
  2196. return &d.n
  2197. }
  2198. // Decode decodes the stream from reader and stores the result in the
  2199. // value pointed to by v. v cannot be a nil pointer. v can also be
  2200. // a reflect.Value of a pointer.
  2201. //
  2202. // Note that a pointer to a nil interface is not a nil pointer.
  2203. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  2204. // We will decode and store a value in that nil interface.
  2205. //
  2206. // Sample usages:
  2207. // // Decoding into a non-nil typed value
  2208. // var f float32
  2209. // err = codec.NewDecoder(r, handle).Decode(&f)
  2210. //
  2211. // // Decoding into nil interface
  2212. // var v interface{}
  2213. // dec := codec.NewDecoder(r, handle)
  2214. // err = dec.Decode(&v)
  2215. //
  2216. // When decoding into a nil interface{}, we will decode into an appropriate value based
  2217. // on the contents of the stream:
  2218. // - Numbers are decoded as float64, int64 or uint64.
  2219. // - Other values are decoded appropriately depending on the type:
  2220. // bool, string, []byte, time.Time, etc
  2221. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  2222. // Configurations exist on the Handle to override defaults
  2223. // (e.g. for MapType, SliceType and how to decode raw bytes).
  2224. //
  2225. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  2226. // type of the value. When a value is seen:
  2227. // - If an extension is registered for it, call that extension function
  2228. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  2229. // - Else decode it based on its reflect.Kind
  2230. //
  2231. // There are some special rules when decoding into containers (slice/array/map/struct).
  2232. // Decode will typically use the stream contents to UPDATE the container i.e. the values
  2233. // in these containers will not be zero'ed before decoding.
  2234. // - A map can be decoded from a stream map, by updating matching keys.
  2235. // - A slice can be decoded from a stream array,
  2236. // by updating the first n elements, where n is length of the stream.
  2237. // - A slice can be decoded from a stream map, by decoding as if
  2238. // it contains a sequence of key-value pairs.
  2239. // - A struct can be decoded from a stream map, by updating matching fields.
  2240. // - A struct can be decoded from a stream array,
  2241. // by updating fields as they occur in the struct (by index).
  2242. //
  2243. // This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update
  2244. // in place by default). However, the consequence of this is that values in slices or maps
  2245. // which are not zero'ed before hand, will have part of the prior values in place after decode
  2246. // if the stream doesn't contain an update for those parts.
  2247. //
  2248. // This in-place update can be disabled by configuring the MapValueReset and SliceElementReset
  2249. // decode options available on every handle.
  2250. //
  2251. // Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice,
  2252. // we reset the destination map or slice to a zero-length value.
  2253. //
  2254. // However, when decoding a stream nil, we reset the destination container
  2255. // to its "zero" value (e.g. nil for slice/map, etc).
  2256. //
  2257. // Note: we allow nil values in the stream anywhere except for map keys.
  2258. // A nil value in the encoded stream where a map key is expected is treated as an error.
  2259. func (d *Decoder) Decode(v interface{}) (err error) {
  2260. // tried to use closure, as runtime optimizes defer with no params.
  2261. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  2262. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  2263. // defer func() { d.deferred(&err) }()
  2264. // { x, y := d, &err; defer func() { x.deferred(y) }() }
  2265. if d.err != nil {
  2266. return d.err
  2267. }
  2268. if recoverPanicToErr {
  2269. defer func() {
  2270. if x := recover(); x != nil {
  2271. panicValToErr(d, x, &d.err)
  2272. if d.err != err {
  2273. err = d.err
  2274. }
  2275. }
  2276. }()
  2277. }
  2278. // defer d.deferred(&err)
  2279. d.mustDecode(v)
  2280. return
  2281. }
  2282. // MustDecode is like Decode, but panics if unable to Decode.
  2283. // This provides insight to the code location that triggered the error.
  2284. func (d *Decoder) MustDecode(v interface{}) {
  2285. if d.err != nil {
  2286. panic(d.err)
  2287. }
  2288. d.mustDecode(v)
  2289. }
  2290. // MustDecode is like Decode, but panics if unable to Decode.
  2291. // This provides insight to the code location that triggered the error.
  2292. func (d *Decoder) mustDecode(v interface{}) {
  2293. // TODO: Top-level: ensure that v is a pointer and not nil.
  2294. if d.bi == nil {
  2295. if d.d.TryDecodeAsNil() {
  2296. setZero(v)
  2297. } else {
  2298. d.decode(v)
  2299. }
  2300. d.d.atEndOfDecode()
  2301. return
  2302. }
  2303. if d.d.TryDecodeAsNil() {
  2304. setZero(v)
  2305. } else {
  2306. d.bi.calls++
  2307. d.decode(v)
  2308. d.bi.calls--
  2309. }
  2310. if d.bi.calls == 0 {
  2311. d.d.atEndOfDecode()
  2312. if !d.h.ExplicitRelease {
  2313. d.bi.release()
  2314. }
  2315. }
  2316. }
  2317. // func (d *Decoder) deferred(err1 *error) {
  2318. // if recoverPanicToErr {
  2319. // if x := recover(); x != nil {
  2320. // panicValToErr(d, x, err1)
  2321. // panicValToErr(d, x, &d.err)
  2322. // }
  2323. // }
  2324. // }
  2325. //go:noinline -- as it is run by finalizer
  2326. func (d *Decoder) finalize() {
  2327. d.Release()
  2328. }
  2329. // Release releases shared (pooled) resources.
  2330. //
  2331. // It is important to call Release() when done with a Decoder, so those resources
  2332. // are released instantly for use by subsequently created Decoders.
  2333. //
  2334. // By default, Release() is automatically called unless the option ExplicitRelease is set.
  2335. func (d *Decoder) Release() {
  2336. if d.bi != nil {
  2337. d.bi.release()
  2338. }
  2339. // d.decNakedPooler.end()
  2340. }
  2341. // // this is not a smart swallow, as it allocates objects and does unnecessary work.
  2342. // func (d *Decoder) swallowViaHammer() {
  2343. // var blank interface{}
  2344. // d.decodeValueNoFn(reflect.ValueOf(&blank).Elem())
  2345. // }
  2346. func (d *Decoder) swallow() {
  2347. // smarter decode that just swallows the content
  2348. dd := d.d
  2349. if dd.TryDecodeAsNil() {
  2350. return
  2351. }
  2352. switch dd.ContainerType() {
  2353. case valueTypeMap:
  2354. containerLen := d.mapStart()
  2355. hasLen := containerLen >= 0
  2356. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  2357. // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break}
  2358. d.mapElemKey()
  2359. d.swallow()
  2360. d.mapElemValue()
  2361. d.swallow()
  2362. }
  2363. d.mapEnd()
  2364. case valueTypeArray:
  2365. containerLen := d.arrayStart()
  2366. hasLen := containerLen >= 0
  2367. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  2368. d.arrayElem()
  2369. d.swallow()
  2370. }
  2371. d.arrayEnd()
  2372. case valueTypeBytes:
  2373. dd.DecodeBytes(d.b[:], true)
  2374. case valueTypeString:
  2375. dd.DecodeStringAsBytes()
  2376. default:
  2377. // these are all primitives, which we can get from decodeNaked
  2378. // if RawExt using Value, complete the processing.
  2379. n := d.naked()
  2380. dd.DecodeNaked()
  2381. if n.v == valueTypeExt && n.l == nil {
  2382. var v2 interface{}
  2383. d.decode(&v2)
  2384. }
  2385. }
  2386. }
  2387. func setZero(iv interface{}) {
  2388. if iv == nil || definitelyNil(iv) {
  2389. return
  2390. }
  2391. var canDecode bool
  2392. switch v := iv.(type) {
  2393. case *string:
  2394. *v = ""
  2395. case *bool:
  2396. *v = false
  2397. case *int:
  2398. *v = 0
  2399. case *int8:
  2400. *v = 0
  2401. case *int16:
  2402. *v = 0
  2403. case *int32:
  2404. *v = 0
  2405. case *int64:
  2406. *v = 0
  2407. case *uint:
  2408. *v = 0
  2409. case *uint8:
  2410. *v = 0
  2411. case *uint16:
  2412. *v = 0
  2413. case *uint32:
  2414. *v = 0
  2415. case *uint64:
  2416. *v = 0
  2417. case *float32:
  2418. *v = 0
  2419. case *float64:
  2420. *v = 0
  2421. case *[]uint8:
  2422. *v = nil
  2423. case *Raw:
  2424. *v = nil
  2425. case *time.Time:
  2426. *v = time.Time{}
  2427. case reflect.Value:
  2428. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2429. v.Set(reflect.Zero(v.Type()))
  2430. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2431. default:
  2432. if !fastpathDecodeSetZeroTypeSwitch(iv) {
  2433. v := reflect.ValueOf(iv)
  2434. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2435. v.Set(reflect.Zero(v.Type()))
  2436. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2437. }
  2438. }
  2439. }
  2440. func (d *Decoder) decode(iv interface{}) {
  2441. // a switch with only concrete types can be optimized.
  2442. // consequently, we deal with nil and interfaces outside the switch.
  2443. if iv == nil {
  2444. d.errorstr(errstrCannotDecodeIntoNil)
  2445. return
  2446. }
  2447. switch v := iv.(type) {
  2448. // case nil:
  2449. // case Selfer:
  2450. case reflect.Value:
  2451. v = d.ensureDecodeable(v)
  2452. d.decodeValue(v, nil)
  2453. case *string:
  2454. *v = string(d.d.DecodeStringAsBytes())
  2455. case *bool:
  2456. *v = d.d.DecodeBool()
  2457. case *int:
  2458. *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))
  2459. case *int8:
  2460. *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8))
  2461. case *int16:
  2462. *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16))
  2463. case *int32:
  2464. *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32))
  2465. case *int64:
  2466. *v = d.d.DecodeInt64()
  2467. case *uint:
  2468. *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))
  2469. case *uint8:
  2470. *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))
  2471. case *uint16:
  2472. *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))
  2473. case *uint32:
  2474. *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))
  2475. case *uint64:
  2476. *v = d.d.DecodeUint64()
  2477. case *float32:
  2478. *v = float32(d.decodeFloat32())
  2479. case *float64:
  2480. *v = d.d.DecodeFloat64()
  2481. case *[]uint8:
  2482. *v = d.d.DecodeBytes(*v, false)
  2483. case []uint8:
  2484. b := d.d.DecodeBytes(v, false)
  2485. if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) {
  2486. copy(v, b)
  2487. }
  2488. case *time.Time:
  2489. *v = d.d.DecodeTime()
  2490. case *Raw:
  2491. *v = d.rawBytes()
  2492. case *interface{}:
  2493. d.decodeValue(reflect.ValueOf(iv).Elem(), nil)
  2494. // d.decodeValueNotNil(reflect.ValueOf(iv).Elem())
  2495. default:
  2496. if v, ok := iv.(Selfer); ok {
  2497. v.CodecDecodeSelf(d)
  2498. } else if !fastpathDecodeTypeSwitch(iv, d) {
  2499. v := reflect.ValueOf(iv)
  2500. v = d.ensureDecodeable(v)
  2501. d.decodeValue(v, nil) // TODO: find a way to say: no fast path??? Not necessary???
  2502. // d.decodeValueFallback(v)
  2503. }
  2504. }
  2505. }
  2506. func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn) {
  2507. // If stream is not containing a nil value, then we can deref to the base
  2508. // non-pointer value, and decode into that.
  2509. var rvp reflect.Value
  2510. var rvpValid bool
  2511. if rv.Kind() == reflect.Ptr {
  2512. rvpValid = true
  2513. for {
  2514. if rvisnil(rv) {
  2515. rv.Set(reflect.New(rv.Type().Elem()))
  2516. }
  2517. rvp = rv
  2518. rv = rv.Elem()
  2519. if rv.Kind() != reflect.Ptr {
  2520. break
  2521. }
  2522. }
  2523. }
  2524. if fn == nil {
  2525. fn = d.h.fn(rv.Type())
  2526. }
  2527. if fn.i.addrD {
  2528. if rvpValid {
  2529. fn.fd(d, &fn.i, rvp)
  2530. } else if rv.CanAddr() {
  2531. fn.fd(d, &fn.i, rv.Addr())
  2532. } else if !fn.i.addrF {
  2533. fn.fd(d, &fn.i, rv)
  2534. } else {
  2535. d.errorf("cannot decode into a non-pointer value")
  2536. }
  2537. } else {
  2538. fn.fd(d, &fn.i, rv)
  2539. }
  2540. // return rv
  2541. }
  2542. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  2543. // NOTE: rvkencname may be a stringView, so don't pass it to another function.
  2544. if d.h.ErrorIfNoField {
  2545. if index >= 0 {
  2546. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  2547. return
  2548. } else if rvkencname != "" {
  2549. d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
  2550. return
  2551. }
  2552. }
  2553. d.swallow()
  2554. }
  2555. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  2556. if d.h.ErrorIfNoArrayExpand {
  2557. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  2558. }
  2559. }
  2560. func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) {
  2561. switch rv.Kind() {
  2562. case reflect.Array:
  2563. return rv, rv.CanAddr()
  2564. case reflect.Ptr:
  2565. if !rvisnil(rv) {
  2566. return rv.Elem(), true
  2567. }
  2568. case reflect.Slice, reflect.Chan, reflect.Map:
  2569. if !rvisnil(rv) {
  2570. return rv, true
  2571. }
  2572. }
  2573. return
  2574. }
  2575. func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) {
  2576. // decode can take any reflect.Value that is a inherently addressable i.e.
  2577. // - array
  2578. // - non-nil chan (we will SEND to it)
  2579. // - non-nil slice (we will set its elements)
  2580. // - non-nil map (we will put into it)
  2581. // - non-nil pointer (we can "update" it)
  2582. rv2, canDecode := isDecodeable(rv)
  2583. if canDecode {
  2584. return
  2585. }
  2586. if !rv.IsValid() {
  2587. d.errorstr(errstrCannotDecodeIntoNil)
  2588. return
  2589. }
  2590. if !rv.CanInterface() {
  2591. d.errorf("cannot decode into a value without an interface: %v", rv)
  2592. return
  2593. }
  2594. rvi := rv2i(rv)
  2595. rvk := rv.Kind()
  2596. d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi)
  2597. return
  2598. }
  2599. func (d *Decoder) depthIncr() {
  2600. d.depth++
  2601. if d.depth >= d.maxdepth {
  2602. panic(errMaxDepthExceeded)
  2603. }
  2604. }
  2605. func (d *Decoder) depthDecr() {
  2606. d.depth--
  2607. }
  2608. // Possibly get an interned version of a string
  2609. //
  2610. // This should mostly be used for map keys, where the key type is string.
  2611. // This is because keys of a map/struct are typically reused across many objects.
  2612. func (d *Decoder) string(v []byte) (s string) {
  2613. if d.is == nil {
  2614. return string(v) // don't return stringView, as we need a real string here.
  2615. }
  2616. s, ok := d.is[string(v)] // no allocation here, per go implementation
  2617. if !ok {
  2618. s = string(v) // new allocation here
  2619. d.is[s] = s
  2620. }
  2621. return s
  2622. }
  2623. // nextValueBytes returns the next value in the stream as a set of bytes.
  2624. func (d *Decoder) nextValueBytes() (bs []byte) {
  2625. d.d.uncacheRead()
  2626. d.r().track()
  2627. d.swallow()
  2628. bs = d.r().stopTrack()
  2629. return
  2630. }
  2631. func (d *Decoder) rawBytes() []byte {
  2632. // ensure that this is not a view into the bytes
  2633. // i.e. make new copy always.
  2634. bs := d.nextValueBytes()
  2635. bs2 := make([]byte, len(bs))
  2636. copy(bs2, bs)
  2637. return bs2
  2638. }
  2639. func (d *Decoder) wrapErr(v interface{}, err *error) {
  2640. *err = decodeError{codecError: codecError{name: d.hh.Name(), err: v}, pos: int(d.r().numread())}
  2641. }
  2642. // NumBytesRead returns the number of bytes read
  2643. func (d *Decoder) NumBytesRead() int {
  2644. return int(d.r().numread())
  2645. }
  2646. // decodeFloat32 will delegate to an appropriate DecodeFloat32 implementation (if exists),
  2647. // else if will call DecodeFloat64 and ensure the value doesn't overflow.
  2648. //
  2649. // Note that we return float64 to reduce unnecessary conversions
  2650. func (d *Decoder) decodeFloat32() float32 {
  2651. if d.js {
  2652. return d.jdec.DecodeFloat32() // custom implementation for 32-bit
  2653. }
  2654. return float32(chkOvf.Float32V(d.d.DecodeFloat64()))
  2655. }
  2656. // ---- container tracking
  2657. // Note: We update the .c after calling the callback.
  2658. // This way, the callback can know what the last status was.
  2659. func (d *Decoder) mapStart() (v int) {
  2660. v = d.d.ReadMapStart()
  2661. d.depthIncr()
  2662. d.c = containerMapStart
  2663. return
  2664. }
  2665. func (d *Decoder) mapElemKey() {
  2666. if d.js {
  2667. d.jdec.ReadMapElemKey()
  2668. }
  2669. d.c = containerMapKey
  2670. }
  2671. func (d *Decoder) mapElemValue() {
  2672. if d.js {
  2673. d.jdec.ReadMapElemValue()
  2674. }
  2675. d.c = containerMapValue
  2676. }
  2677. func (d *Decoder) mapEnd() {
  2678. d.d.ReadMapEnd()
  2679. d.depthDecr()
  2680. d.c = containerMapEnd
  2681. d.c = 0
  2682. }
  2683. func (d *Decoder) arrayStart() (v int) {
  2684. v = d.d.ReadArrayStart()
  2685. d.depthIncr()
  2686. d.c = containerArrayStart
  2687. return
  2688. }
  2689. func (d *Decoder) arrayElem() {
  2690. if d.js {
  2691. d.jdec.ReadArrayElem()
  2692. }
  2693. d.c = containerArrayElem
  2694. }
  2695. func (d *Decoder) arrayEnd() {
  2696. d.d.ReadArrayEnd()
  2697. d.depthDecr()
  2698. d.c = containerArrayEnd
  2699. d.c = 0
  2700. }
  2701. func (d *Decoder) interfaceExtConvertAndDecode(v interface{}, ext Ext) {
  2702. // var v interface{} = ext.ConvertExt(rv)
  2703. // d.d.decode(&v)
  2704. // ext.UpdateExt(rv, v)
  2705. // assume v is a pointer:
  2706. // - if struct|array, pass as is to ConvertExt
  2707. // - else make it non-addressable and pass to ConvertExt
  2708. // - make return value from ConvertExt addressable
  2709. // - decode into it
  2710. // - return the interface for passing into UpdateExt.
  2711. // - interface should be a pointer if struct|array, else a value
  2712. var s interface{}
  2713. rv := reflect.ValueOf(v)
  2714. rv2 := rv.Elem()
  2715. rvk := rv2.Kind()
  2716. if rvk == reflect.Struct || rvk == reflect.Array {
  2717. s = ext.ConvertExt(v)
  2718. } else {
  2719. s = ext.ConvertExt(rv2i(rv2))
  2720. }
  2721. rv = reflect.ValueOf(s)
  2722. if !rv.CanAddr() {
  2723. if rv.Kind() == reflect.Ptr {
  2724. rv2 = reflect.New(rv.Type().Elem())
  2725. rv2.Set(rv)
  2726. } else {
  2727. rv2 = reflect.New(rv.Type()).Elem()
  2728. rv2.Set(rv)
  2729. }
  2730. rv = rv2
  2731. }
  2732. d.decodeValue(rv, nil)
  2733. ext.UpdateExt(v, rv2i(rv))
  2734. }
  2735. func (d *Decoder) sideDecode(v interface{}, bs []byte) {
  2736. rv := baseRV(v)
  2737. NewDecoderBytes(bs, d.hh).decodeValue(rv, d.h.fnNoExt(rv.Type()))
  2738. }
  2739. // --------------------------------------------------
  2740. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  2741. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  2742. type decSliceHelper struct {
  2743. d *Decoder
  2744. ct valueType
  2745. array bool
  2746. }
  2747. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  2748. x.ct = d.d.ContainerType()
  2749. x.d = d
  2750. switch x.ct {
  2751. case valueTypeArray:
  2752. x.array = true
  2753. clen = d.arrayStart()
  2754. case valueTypeMap:
  2755. clen = d.mapStart() * 2
  2756. default:
  2757. d.errorf("only encoded map or array can be decoded into a slice (%d)", x.ct)
  2758. }
  2759. return
  2760. }
  2761. func (x decSliceHelper) End() {
  2762. if x.array {
  2763. x.d.arrayEnd()
  2764. } else {
  2765. x.d.mapEnd()
  2766. }
  2767. }
  2768. func (x decSliceHelper) ElemContainerState(index int) {
  2769. if x.array {
  2770. x.d.arrayElem()
  2771. } else if index%2 == 0 {
  2772. x.d.mapElemKey()
  2773. } else {
  2774. x.d.mapElemValue()
  2775. }
  2776. }
  2777. func decByteSlice(r *decReaderSwitch, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2778. if clen == 0 {
  2779. return zeroByteSlice
  2780. }
  2781. if len(bs) == clen {
  2782. bsOut = bs
  2783. r.readb(bsOut)
  2784. } else if cap(bs) >= clen {
  2785. bsOut = bs[:clen]
  2786. r.readb(bsOut)
  2787. } else {
  2788. // bsOut = make([]byte, clen)
  2789. len2 := decInferLen(clen, maxInitLen, 1)
  2790. bsOut = make([]byte, len2)
  2791. r.readb(bsOut)
  2792. for len2 < clen {
  2793. len3 := decInferLen(clen-len2, maxInitLen, 1)
  2794. bs3 := bsOut
  2795. bsOut = make([]byte, len2+len3)
  2796. copy(bsOut, bs3)
  2797. r.readb(bsOut[len2:])
  2798. len2 += len3
  2799. }
  2800. }
  2801. return
  2802. }
  2803. // func decByteSliceZeroCopy(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2804. // if _, ok := r.(*bytesDecReader); ok && clen <= maxInitLen {
  2805. // return r.readx(clen)
  2806. // }
  2807. // return decByteSlice(r, clen, maxInitLen, bs)
  2808. // }
  2809. func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
  2810. if xlen := len(in); xlen > 0 {
  2811. if isBytesReader || xlen <= scratchByteArrayLen {
  2812. if cap(dest) >= xlen {
  2813. out = dest[:xlen]
  2814. } else {
  2815. out = make([]byte, xlen)
  2816. }
  2817. copy(out, in)
  2818. return
  2819. }
  2820. }
  2821. return in
  2822. }
  2823. // decInferLen will infer a sensible length, given the following:
  2824. // - clen: length wanted.
  2825. // - maxlen: max length to be returned.
  2826. // if <= 0, it is unset, and we infer it based on the unit size
  2827. // - unit: number of bytes for each element of the collection
  2828. func decInferLen(clen, maxlen, unit int) (rvlen int) {
  2829. const maxLenIfUnset = 8 // 64
  2830. // handle when maxlen is not set i.e. <= 0
  2831. // clen==0: use 0
  2832. // maxlen<=0, clen<0: use default
  2833. // maxlen> 0, clen<0: use default
  2834. // maxlen<=0, clen>0: infer maxlen, and cap on it
  2835. // maxlen> 0, clen>0: cap at maxlen
  2836. if clen == 0 {
  2837. return
  2838. }
  2839. if clen < 0 {
  2840. return maxLenIfUnset
  2841. }
  2842. if unit == 0 {
  2843. return clen
  2844. }
  2845. if maxlen <= 0 {
  2846. // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
  2847. // maxlen = 256 * 1024 / unit
  2848. // if maxlen < (4 * 1024) {
  2849. // maxlen = 4 * 1024
  2850. // }
  2851. if unit < (256 / 4) {
  2852. maxlen = 256 * 1024 / unit
  2853. } else {
  2854. maxlen = 4 * 1024
  2855. }
  2856. // if maxlen > maxLenIfUnset {
  2857. // maxlen = maxLenIfUnset
  2858. // }
  2859. }
  2860. if clen > maxlen {
  2861. rvlen = maxlen
  2862. } else {
  2863. rvlen = clen
  2864. }
  2865. return
  2866. }
  2867. func expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) (
  2868. s2 reflect.Value, scap2 int, changed bool, err string) {
  2869. l1 := slen + num // new slice length
  2870. if l1 < slen {
  2871. err = errmsgExpandSliceOverflow
  2872. return
  2873. }
  2874. if l1 <= scap {
  2875. if s.CanSet() {
  2876. rvssetlen(s, l1)
  2877. } else if canChange {
  2878. s2 = s.Slice(0, l1)
  2879. scap2 = scap
  2880. changed = true
  2881. } else {
  2882. err = errmsgExpandSliceCannotChange
  2883. return
  2884. }
  2885. return
  2886. }
  2887. if !canChange {
  2888. err = errmsgExpandSliceCannotChange
  2889. return
  2890. }
  2891. scap2 = growCap(scap, stElemSize, num)
  2892. s2 = reflect.MakeSlice(st, l1, scap2)
  2893. changed = true
  2894. reflect.Copy(s2, s)
  2895. return
  2896. }
  2897. func decReadFull(r io.Reader, bs []byte) (n uint, err error) {
  2898. var nn int
  2899. for n < uint(len(bs)) && err == nil {
  2900. nn, err = r.Read(bs[n:])
  2901. if nn > 0 {
  2902. if err == io.EOF {
  2903. // leave EOF for next time
  2904. err = nil
  2905. }
  2906. n += uint(nn)
  2907. }
  2908. }
  2909. // do not do this - it serves no purpose
  2910. // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
  2911. return
  2912. }
  2913. func decNakedReadRawBytes(dr decDriver, d *Decoder, n *decNaked, rawToString bool) {
  2914. if rawToString {
  2915. n.v = valueTypeString
  2916. n.s = string(dr.DecodeBytes(d.b[:], true))
  2917. } else {
  2918. n.v = valueTypeBytes
  2919. n.l = dr.DecodeBytes(nil, false)
  2920. }
  2921. }
  2922. // register these here, so that staticcheck stops barfing
  2923. var _ = (*bytesDecReader).readTo
  2924. var _ = (*bytesDecReader).readUntil