另客网go项目公用的代码库

decode.go 74KB

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