decode.go 77 KB

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