decode.go 72 KB

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