decode.go 75 KB

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