decode.go 76 KB

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