decode.go 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212
  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. // DecodeStringAsBytes returns the bytes representing a string.
  89. // By definition, it will return a view into a scratch buffer.
  90. //
  91. // Note: This can also decode symbols, if supported.
  92. //
  93. // Users should consume it right away and not store it for later use.
  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 && rtelem0Mut { // !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. ktypeKind := ktype.Kind()
  1596. var keyFn, valFn *codecFn
  1597. var ktypeLo, vtypeLo reflect.Type
  1598. for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
  1599. }
  1600. for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
  1601. }
  1602. rvvMut := !isImmutableKind(vtypeKind)
  1603. var mapGet, mapSet bool
  1604. if !d.h.MapValueReset {
  1605. if rvvMut {
  1606. if vtypeKind == reflect.Interface {
  1607. if !d.h.InterfaceReset {
  1608. mapGet = true
  1609. }
  1610. } else {
  1611. mapGet = true
  1612. }
  1613. }
  1614. }
  1615. var rvk, rvkn, rvv, rvvn, rvvz reflect.Value
  1616. rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk.
  1617. ktypeIsString := ktypeId == stringTypId
  1618. ktypeIsIntf := ktypeId == intfTypId
  1619. hasLen := containerLen > 0
  1620. var kstrbs []byte
  1621. vNew := func(t reflect.Type, k reflect.Kind) reflect.Value {
  1622. if k == reflect.Ptr {
  1623. return reflect.New(t.Elem())
  1624. }
  1625. return reflect.New(t).Elem()
  1626. }
  1627. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1628. if j == 0 {
  1629. // rvvz = reflect.Zero(vtype)
  1630. // rvkz = reflect.Zero(ktype)
  1631. if !rvkMut {
  1632. rvkn = vNew(ktype, ktypeKind)
  1633. }
  1634. if !rvvMut {
  1635. rvvn = vNew(vtype, vtypeKind)
  1636. }
  1637. }
  1638. if rvkMut {
  1639. rvk = vNew(ktype, ktypeKind)
  1640. } else {
  1641. rvk = rvkn
  1642. }
  1643. d.mapElemKey()
  1644. if ktypeIsString {
  1645. kstrbs = dd.DecodeStringAsBytes()
  1646. rvk.SetString(stringView(kstrbs)) // NOTE: if doing an insert, use real string (not stringview)
  1647. } else {
  1648. if keyFn == nil {
  1649. keyFn = d.h.fn(ktypeLo)
  1650. }
  1651. d.decodeValue(rvk, keyFn)
  1652. }
  1653. // special case if interface wrapping a byte array.
  1654. if ktypeIsIntf {
  1655. if rvk2 := rvk.Elem(); rvk2.IsValid() && rvk2.Type() == uint8SliceTyp {
  1656. rvk.Set(reflect.ValueOf(d.string(rvk2.Bytes())))
  1657. }
  1658. // NOTE: consider failing early if map/slice/func
  1659. }
  1660. d.mapElemValue()
  1661. // Brittle, but OK per TryDecodeAsNil() contract.
  1662. // i.e. TryDecodeAsNil never shares slices with other decDriver procedures
  1663. if dd.TryDecodeAsNil() {
  1664. if d.h.DeleteOnNilMapValue {
  1665. rv.SetMapIndex(rvk, reflect.Value{})
  1666. } else {
  1667. if ktypeIsString { // set to a real string (not string view)
  1668. rvk.SetString(d.string(kstrbs))
  1669. }
  1670. if !rvvz.IsValid() {
  1671. rvvz = reflect.Zero(vtype)
  1672. }
  1673. rv.SetMapIndex(rvk, rvvz)
  1674. }
  1675. continue
  1676. }
  1677. mapSet = true // set to false if u do a get, and its a non-nil pointer
  1678. if mapGet {
  1679. rvv = rv.MapIndex(rvk)
  1680. if vtypeKind == reflect.Ptr {
  1681. if rvv.IsValid() && !rvv.IsNil() {
  1682. mapSet = false
  1683. } else {
  1684. rvv = reflect.New(vtype.Elem())
  1685. }
  1686. } else if rvv.IsValid() && vtypeKind == reflect.Interface && !rvv.IsNil() {
  1687. rvvn = reflect.New(vtype).Elem()
  1688. rvvn.Set(rvv)
  1689. rvv = rvvn
  1690. } else if rvvMut {
  1691. rvv = reflect.New(vtype).Elem()
  1692. } else {
  1693. rvv = rvvn
  1694. }
  1695. } else if rvvMut {
  1696. rvv = vNew(vtype, vtypeKind)
  1697. } else {
  1698. rvv = rvvn
  1699. }
  1700. if valFn == nil {
  1701. valFn = d.h.fn(vtypeLo)
  1702. }
  1703. // We MUST be done with the stringview of the key, before decoding the value
  1704. // so that we don't bastardize the reused byte array.
  1705. if mapSet && ktypeIsString { // set to a real string (not string view)
  1706. rvk.SetString(d.string(kstrbs))
  1707. }
  1708. d.decodeValue(rvv, valFn)
  1709. if mapSet {
  1710. rv.SetMapIndex(rvk, rvv)
  1711. }
  1712. // if ktypeIsString {
  1713. // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop
  1714. // }
  1715. }
  1716. d.mapEnd()
  1717. }
  1718. // decNaked is used to keep track of the primitives decoded.
  1719. // Without it, we would have to decode each primitive and wrap it
  1720. // in an interface{}, causing an allocation.
  1721. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  1722. // so we can rest assured that no other decoding happens while these
  1723. // primitives are being decoded.
  1724. //
  1725. // maps and arrays are not handled by this mechanism.
  1726. // However, RawExt is, and we accommodate for extensions that decode
  1727. // RawExt from DecodeNaked, but need to decode the value subsequently.
  1728. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
  1729. //
  1730. // However, decNaked also keeps some arrays of default maps and slices
  1731. // used in DecodeNaked. This way, we can get a pointer to it
  1732. // without causing a new heap allocation.
  1733. //
  1734. // kInterfaceNaked will ensure that there is no allocation for the common
  1735. // uses.
  1736. type decNaked struct {
  1737. // r RawExt // used for RawExt, uint, []byte.
  1738. // primitives below
  1739. u uint64
  1740. i int64
  1741. f float64
  1742. l []byte
  1743. s string
  1744. // ---- cpu cache line boundary?
  1745. t time.Time
  1746. b bool
  1747. // state
  1748. v valueType
  1749. // _ [6]bool // padding
  1750. // ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above
  1751. //
  1752. // _ [3]uint64 // padding
  1753. }
  1754. // func (n *decNaked) init() {
  1755. // n.ru = reflect.ValueOf(&n.u).Elem()
  1756. // n.ri = reflect.ValueOf(&n.i).Elem()
  1757. // n.rf = reflect.ValueOf(&n.f).Elem()
  1758. // n.rl = reflect.ValueOf(&n.l).Elem()
  1759. // n.rs = reflect.ValueOf(&n.s).Elem()
  1760. // n.rt = reflect.ValueOf(&n.t).Elem()
  1761. // n.rb = reflect.ValueOf(&n.b).Elem()
  1762. // // n.rr[] = reflect.ValueOf(&n.)
  1763. // }
  1764. // type decNakedPooler struct {
  1765. // n *decNaked
  1766. // nsp *sync.Pool
  1767. // }
  1768. // // naked must be called before each call to .DecodeNaked, as they will use it.
  1769. // func (d *decNakedPooler) naked() *decNaked {
  1770. // if d.n == nil {
  1771. // // consider one of:
  1772. // // - get from sync.Pool (if GC is frequent, there's no value here)
  1773. // // - new alloc (safest. only init'ed if it a naked decode will be done)
  1774. // // - field in Decoder (makes the Decoder struct very big)
  1775. // // To support using a decoder where a DecodeNaked is not needed,
  1776. // // we prefer #1 or #2.
  1777. // // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool
  1778. // // d.n.init()
  1779. // var v interface{}
  1780. // d.nsp, v = pool.decNaked()
  1781. // d.n = v.(*decNaked)
  1782. // }
  1783. // return d.n
  1784. // }
  1785. // func (d *decNakedPooler) end() {
  1786. // if d.n != nil {
  1787. // // if n != nil, then nsp != nil (they are always set together)
  1788. // d.nsp.Put(d.n)
  1789. // d.n, d.nsp = nil, nil
  1790. // }
  1791. // }
  1792. // type rtid2rv struct {
  1793. // rtid uintptr
  1794. // rv reflect.Value
  1795. // }
  1796. // --------------
  1797. type decReaderSwitch struct {
  1798. esep bool // has elem separators
  1799. mtr, str bool // whether maptype or slicetype are known types
  1800. be bool // is binary encoding
  1801. js bool // is json handle
  1802. jsms bool // is json handle, and MapKeyAsString
  1803. // typ entryType
  1804. bytes bool // is bytes reader
  1805. bufio bool // is this a bufioDecReader?
  1806. rb bytesDecReader
  1807. ri *ioDecReader
  1808. bi *bufioDecReader
  1809. }
  1810. // numread, track and stopTrack are always inlined, as they just check int fields, etc.
  1811. /*
  1812. func (z *decReaderSwitch) numread() int {
  1813. switch z.typ {
  1814. case entryTypeBytes:
  1815. return z.rb.numread()
  1816. case entryTypeIo:
  1817. return z.ri.numread()
  1818. default:
  1819. return z.bi.numread()
  1820. }
  1821. }
  1822. func (z *decReaderSwitch) track() {
  1823. switch z.typ {
  1824. case entryTypeBytes:
  1825. z.rb.track()
  1826. case entryTypeIo:
  1827. z.ri.track()
  1828. default:
  1829. z.bi.track()
  1830. }
  1831. }
  1832. func (z *decReaderSwitch) stopTrack() []byte {
  1833. switch z.typ {
  1834. case entryTypeBytes:
  1835. return z.rb.stopTrack()
  1836. case entryTypeIo:
  1837. return z.ri.stopTrack()
  1838. default:
  1839. return z.bi.stopTrack()
  1840. }
  1841. }
  1842. func (z *decReaderSwitch) unreadn1() {
  1843. switch z.typ {
  1844. case entryTypeBytes:
  1845. z.rb.unreadn1()
  1846. case entryTypeIo:
  1847. z.ri.unreadn1()
  1848. default:
  1849. z.bi.unreadn1()
  1850. }
  1851. }
  1852. func (z *decReaderSwitch) readx(n int) []byte {
  1853. switch z.typ {
  1854. case entryTypeBytes:
  1855. return z.rb.readx(n)
  1856. case entryTypeIo:
  1857. return z.ri.readx(n)
  1858. default:
  1859. return z.bi.readx(n)
  1860. }
  1861. }
  1862. func (z *decReaderSwitch) readb(s []byte) {
  1863. switch z.typ {
  1864. case entryTypeBytes:
  1865. z.rb.readb(s)
  1866. case entryTypeIo:
  1867. z.ri.readb(s)
  1868. default:
  1869. z.bi.readb(s)
  1870. }
  1871. }
  1872. func (z *decReaderSwitch) readn1() uint8 {
  1873. switch z.typ {
  1874. case entryTypeBytes:
  1875. return z.rb.readn1()
  1876. case entryTypeIo:
  1877. return z.ri.readn1()
  1878. default:
  1879. return z.bi.readn1()
  1880. }
  1881. }
  1882. func (z *decReaderSwitch) skip(accept *bitset256) (token byte) {
  1883. switch z.typ {
  1884. case entryTypeBytes:
  1885. return z.rb.skip(accept)
  1886. case entryTypeIo:
  1887. return z.ri.skip(accept)
  1888. default:
  1889. return z.bi.skip(accept)
  1890. }
  1891. }
  1892. func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) {
  1893. switch z.typ {
  1894. case entryTypeBytes:
  1895. return z.rb.readTo(in, accept)
  1896. case entryTypeIo:
  1897. return z.ri.readTo(in, accept)
  1898. default:
  1899. return z.bi.readTo(in, accept)
  1900. }
  1901. }
  1902. func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) {
  1903. switch z.typ {
  1904. case entryTypeBytes:
  1905. return z.rb.readUntil(in, stop)
  1906. case entryTypeIo:
  1907. return z.ri.readUntil(in, stop)
  1908. default:
  1909. return z.bi.readUntil(in, stop)
  1910. }
  1911. }
  1912. */
  1913. // the if/else-if/else block is expensive to inline.
  1914. // Each node of this construct costs a lot and dominates the budget.
  1915. // Best to only do an if fast-path else block (so fast-path is inlined).
  1916. // This is irrespective of inlineExtraCallCost set in $GOROOT/src/cmd/compile/internal/gc/inl.go
  1917. //
  1918. // In decReaderSwitch methods below, we delegate all IO functions into their own methods.
  1919. // This allows for the inlining of the common path when z.bytes=true.
  1920. // Go 1.12+ supports inlining methods with up to 1 inlined function (or 2 if no other constructs).
  1921. func (z *decReaderSwitch) numread() uint {
  1922. if z.bytes {
  1923. return z.rb.numread()
  1924. } else if z.bufio {
  1925. return z.bi.numread()
  1926. } else {
  1927. return z.ri.numread()
  1928. }
  1929. }
  1930. func (z *decReaderSwitch) track() {
  1931. if z.bytes {
  1932. z.rb.track()
  1933. } else if z.bufio {
  1934. z.bi.track()
  1935. } else {
  1936. z.ri.track()
  1937. }
  1938. }
  1939. func (z *decReaderSwitch) stopTrack() []byte {
  1940. if z.bytes {
  1941. return z.rb.stopTrack()
  1942. } else if z.bufio {
  1943. return z.bi.stopTrack()
  1944. } else {
  1945. return z.ri.stopTrack()
  1946. }
  1947. }
  1948. // func (z *decReaderSwitch) unreadn1() {
  1949. // if z.bytes {
  1950. // z.rb.unreadn1()
  1951. // } else {
  1952. // z.unreadn1IO()
  1953. // }
  1954. // }
  1955. // func (z *decReaderSwitch) unreadn1IO() {
  1956. // if z.bufio {
  1957. // z.bi.unreadn1()
  1958. // } else {
  1959. // z.ri.unreadn1()
  1960. // }
  1961. // }
  1962. func (z *decReaderSwitch) unreadn1() {
  1963. if z.bytes {
  1964. z.rb.unreadn1()
  1965. } else if z.bufio {
  1966. z.bi.unreadn1()
  1967. } else {
  1968. z.ri.unreadn1() // not inlined
  1969. }
  1970. }
  1971. func (z *decReaderSwitch) readx(n uint) []byte {
  1972. if z.bytes {
  1973. return z.rb.readx(n)
  1974. }
  1975. return z.readxIO(n)
  1976. }
  1977. func (z *decReaderSwitch) readxIO(n uint) []byte {
  1978. if z.bufio {
  1979. return z.bi.readx(n)
  1980. }
  1981. return z.ri.readx(n)
  1982. }
  1983. func (z *decReaderSwitch) readb(s []byte) {
  1984. if z.bytes {
  1985. z.rb.readb(s)
  1986. } else {
  1987. z.readbIO(s)
  1988. }
  1989. }
  1990. //go:noinline - fallback for io, ensures z.bytes path is inlined
  1991. func (z *decReaderSwitch) readbIO(s []byte) {
  1992. if z.bufio {
  1993. z.bi.readb(s)
  1994. } else {
  1995. z.ri.readb(s)
  1996. }
  1997. }
  1998. func (z *decReaderSwitch) readn1() uint8 {
  1999. if z.bytes {
  2000. return z.rb.readn1()
  2001. }
  2002. return z.readn1IO()
  2003. }
  2004. func (z *decReaderSwitch) readn1IO() uint8 {
  2005. if z.bufio {
  2006. return z.bi.readn1()
  2007. }
  2008. return z.ri.readn1()
  2009. }
  2010. func (z *decReaderSwitch) skip(accept *bitset256) (token byte) {
  2011. if z.bytes {
  2012. return z.rb.skip(accept)
  2013. }
  2014. return z.skipIO(accept)
  2015. }
  2016. func (z *decReaderSwitch) skipIO(accept *bitset256) (token byte) {
  2017. if z.bufio {
  2018. return z.bi.skip(accept)
  2019. }
  2020. return z.ri.skip(accept)
  2021. }
  2022. func (z *decReaderSwitch) readTo(in []byte, accept *bitset256) (out []byte) {
  2023. if z.bytes {
  2024. return z.rb.readToNoInput(accept) // z.rb.readTo(in, accept)
  2025. }
  2026. return z.readToIO(in, accept)
  2027. }
  2028. //go:noinline - fallback for io, ensures z.bytes path is inlined
  2029. func (z *decReaderSwitch) readToIO(in []byte, accept *bitset256) (out []byte) {
  2030. if z.bufio {
  2031. return z.bi.readTo(in, accept)
  2032. }
  2033. return z.ri.readTo(in, accept)
  2034. }
  2035. func (z *decReaderSwitch) readUntil(in []byte, stop byte) (out []byte) {
  2036. if z.bytes {
  2037. return z.rb.readUntilNoInput(stop)
  2038. }
  2039. return z.readUntilIO(in, stop)
  2040. }
  2041. func (z *decReaderSwitch) readUntilIO(in []byte, stop byte) (out []byte) {
  2042. if z.bufio {
  2043. return z.bi.readUntil(in, stop)
  2044. }
  2045. return z.ri.readUntil(in, stop)
  2046. }
  2047. // Decoder reads and decodes an object from an input stream in a supported format.
  2048. //
  2049. // Decoder is NOT safe for concurrent use i.e. a Decoder cannot be used
  2050. // concurrently in multiple goroutines.
  2051. //
  2052. // However, as Decoder could be allocation heavy to initialize, a Reset method is provided
  2053. // so its state can be reused to decode new input streams repeatedly.
  2054. // This is the idiomatic way to use.
  2055. type Decoder struct {
  2056. panicHdl
  2057. // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
  2058. // Try to put things that go together to fit within a cache line (8 words).
  2059. d decDriver
  2060. // NOTE: Decoder shouldn't call its read methods,
  2061. // as the handler MAY need to do some coordination.
  2062. // r *decReaderSwitch
  2063. // bi *bufioDecReader
  2064. // cache the mapTypeId and sliceTypeId for faster comparisons
  2065. mtid uintptr
  2066. stid uintptr
  2067. jdec *jsonDecDriver
  2068. h *BasicHandle
  2069. hh Handle
  2070. // ---- cpu cache line boundary?
  2071. decReaderSwitch
  2072. // ---- cpu cache line boundary?
  2073. n decNaked
  2074. // cr containerStateRecv
  2075. // _ [4]uint8 // padding
  2076. is map[string]string // used for interning strings
  2077. err error
  2078. // ---- cpu cache line boundary?
  2079. // ---- writable fields during execution --- *try* to keep in sep cache line
  2080. maxdepth int16
  2081. depth int16
  2082. c containerState
  2083. _ [3]byte // padding
  2084. b [decScratchByteArrayLen]byte // scratch buffer, used by Decoder and xxxEncDrivers
  2085. // padding - false sharing help // modify 232 if Decoder struct changes.
  2086. // _ [cacheLineSize - 232%cacheLineSize]byte
  2087. }
  2088. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  2089. //
  2090. // For efficiency, Users are encouraged to configure ReaderBufferSize on the handle
  2091. // OR pass in a memory buffered reader (eg bufio.Reader, bytes.Buffer).
  2092. func NewDecoder(r io.Reader, h Handle) *Decoder {
  2093. d := newDecoder(h)
  2094. d.Reset(r)
  2095. return d
  2096. }
  2097. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  2098. // from a byte slice with zero copying.
  2099. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  2100. d := newDecoder(h)
  2101. d.ResetBytes(in)
  2102. return d
  2103. }
  2104. // var defaultDecNaked decNaked
  2105. func newDecoder(h Handle) *Decoder {
  2106. d := &Decoder{h: basicHandle(h), err: errDecoderNotInitialized}
  2107. d.bytes = true
  2108. if useFinalizers {
  2109. runtime.SetFinalizer(d, (*Decoder).finalize)
  2110. // xdebugf(">>>> new(Decoder) with finalizer")
  2111. }
  2112. // d.r = &d.decReaderSwitch
  2113. d.hh = h
  2114. d.be = h.isBinary()
  2115. // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
  2116. var jh *JsonHandle
  2117. jh, d.js = h.(*JsonHandle)
  2118. d.jdec = nil
  2119. if d.js {
  2120. d.jsms = jh.MapKeyAsString
  2121. }
  2122. d.esep = d.hh.hasElemSeparators()
  2123. if d.h.InternString {
  2124. d.is = make(map[string]string, 32)
  2125. }
  2126. d.d = h.newDecDriver(d)
  2127. if d.js {
  2128. d.jdec = d.d.(*jsonDecDriver)
  2129. }
  2130. // d.cr, _ = d.d.(containerStateRecv)
  2131. return d
  2132. }
  2133. func (d *Decoder) r() *decReaderSwitch {
  2134. return &d.decReaderSwitch
  2135. }
  2136. func (d *Decoder) resetCommon() {
  2137. // d.r = &d.decReaderSwitch
  2138. d.d.reset()
  2139. d.err = nil
  2140. d.depth = 0
  2141. d.maxdepth = d.h.MaxDepth
  2142. if d.maxdepth <= 0 {
  2143. d.maxdepth = decDefMaxDepth
  2144. }
  2145. // reset all things which were cached from the Handle, but could change
  2146. d.mtid, d.stid = 0, 0
  2147. d.mtr, d.str = false, false
  2148. if d.h.MapType != nil {
  2149. d.mtid = rt2id(d.h.MapType)
  2150. d.mtr = fastpathAV.index(d.mtid) != -1
  2151. }
  2152. if d.h.SliceType != nil {
  2153. d.stid = rt2id(d.h.SliceType)
  2154. d.str = fastpathAV.index(d.stid) != -1
  2155. }
  2156. }
  2157. // Reset the Decoder with a new Reader to decode from,
  2158. // clearing all state from last run(s).
  2159. func (d *Decoder) Reset(r io.Reader) {
  2160. if r == nil {
  2161. return
  2162. }
  2163. d.bytes = false
  2164. // d.typ = entryTypeUnset
  2165. if d.h.ReaderBufferSize > 0 {
  2166. if d.bi == nil {
  2167. d.bi = new(bufioDecReader)
  2168. }
  2169. d.bi.reset(r, d.h.ReaderBufferSize)
  2170. // d.r = d.bi
  2171. // d.typ = entryTypeBufio
  2172. d.bufio = true
  2173. } else {
  2174. // d.ri.x = &d.b
  2175. // d.s = d.sa[:0]
  2176. if d.ri == nil {
  2177. d.ri = new(ioDecReader)
  2178. }
  2179. d.ri.reset(r)
  2180. // d.r = d.ri
  2181. // d.typ = entryTypeIo
  2182. d.bufio = false
  2183. }
  2184. d.resetCommon()
  2185. }
  2186. // ResetBytes resets the Decoder with a new []byte to decode from,
  2187. // clearing all state from last run(s).
  2188. func (d *Decoder) ResetBytes(in []byte) {
  2189. if in == nil {
  2190. return
  2191. }
  2192. d.bytes = true
  2193. d.bufio = false
  2194. // d.typ = entryTypeBytes
  2195. d.rb.reset(in)
  2196. // d.r = &d.rb
  2197. d.resetCommon()
  2198. }
  2199. func (d *Decoder) naked() *decNaked {
  2200. return &d.n
  2201. }
  2202. // Decode decodes the stream from reader and stores the result in the
  2203. // value pointed to by v. v cannot be a nil pointer. v can also be
  2204. // a reflect.Value of a pointer.
  2205. //
  2206. // Note that a pointer to a nil interface is not a nil pointer.
  2207. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  2208. // We will decode and store a value in that nil interface.
  2209. //
  2210. // Sample usages:
  2211. // // Decoding into a non-nil typed value
  2212. // var f float32
  2213. // err = codec.NewDecoder(r, handle).Decode(&f)
  2214. //
  2215. // // Decoding into nil interface
  2216. // var v interface{}
  2217. // dec := codec.NewDecoder(r, handle)
  2218. // err = dec.Decode(&v)
  2219. //
  2220. // When decoding into a nil interface{}, we will decode into an appropriate value based
  2221. // on the contents of the stream:
  2222. // - Numbers are decoded as float64, int64 or uint64.
  2223. // - Other values are decoded appropriately depending on the type:
  2224. // bool, string, []byte, time.Time, etc
  2225. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  2226. // Configurations exist on the Handle to override defaults
  2227. // (e.g. for MapType, SliceType and how to decode raw bytes).
  2228. //
  2229. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  2230. // type of the value. When a value is seen:
  2231. // - If an extension is registered for it, call that extension function
  2232. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  2233. // - Else decode it based on its reflect.Kind
  2234. //
  2235. // There are some special rules when decoding into containers (slice/array/map/struct).
  2236. // Decode will typically use the stream contents to UPDATE the container i.e. the values
  2237. // in these containers will not be zero'ed before decoding.
  2238. // - A map can be decoded from a stream map, by updating matching keys.
  2239. // - A slice can be decoded from a stream array,
  2240. // by updating the first n elements, where n is length of the stream.
  2241. // - A slice can be decoded from a stream map, by decoding as if
  2242. // it contains a sequence of key-value pairs.
  2243. // - A struct can be decoded from a stream map, by updating matching fields.
  2244. // - A struct can be decoded from a stream array,
  2245. // by updating fields as they occur in the struct (by index).
  2246. //
  2247. // This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update
  2248. // in place by default). However, the consequence of this is that values in slices or maps
  2249. // which are not zero'ed before hand, will have part of the prior values in place after decode
  2250. // if the stream doesn't contain an update for those parts.
  2251. //
  2252. // This in-place update can be disabled by configuring the MapValueReset and SliceElementReset
  2253. // decode options available on every handle.
  2254. //
  2255. // Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice,
  2256. // we reset the destination map or slice to a zero-length value.
  2257. //
  2258. // However, when decoding a stream nil, we reset the destination container
  2259. // to its "zero" value (e.g. nil for slice/map, etc).
  2260. //
  2261. // Note: we allow nil values in the stream anywhere except for map keys.
  2262. // A nil value in the encoded stream where a map key is expected is treated as an error.
  2263. func (d *Decoder) Decode(v interface{}) (err error) {
  2264. // tried to use closure, as runtime optimizes defer with no params.
  2265. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  2266. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  2267. // defer func() { d.deferred(&err) }()
  2268. // { x, y := d, &err; defer func() { x.deferred(y) }() }
  2269. if d.err != nil {
  2270. return d.err
  2271. }
  2272. if recoverPanicToErr {
  2273. defer func() {
  2274. if x := recover(); x != nil {
  2275. panicValToErr(d, x, &d.err)
  2276. if d.err != err {
  2277. err = d.err
  2278. }
  2279. }
  2280. }()
  2281. }
  2282. // defer d.deferred(&err)
  2283. d.mustDecode(v)
  2284. return
  2285. }
  2286. // MustDecode is like Decode, but panics if unable to Decode.
  2287. // This provides insight to the code location that triggered the error.
  2288. func (d *Decoder) MustDecode(v interface{}) {
  2289. if d.err != nil {
  2290. panic(d.err)
  2291. }
  2292. d.mustDecode(v)
  2293. }
  2294. // MustDecode is like Decode, but panics if unable to Decode.
  2295. // This provides insight to the code location that triggered the error.
  2296. func (d *Decoder) mustDecode(v interface{}) {
  2297. // TODO: Top-level: ensure that v is a pointer and not nil.
  2298. if d.bi == nil {
  2299. if d.d.TryDecodeAsNil() {
  2300. setZero(v)
  2301. } else {
  2302. d.decode(v)
  2303. }
  2304. d.d.atEndOfDecode()
  2305. return
  2306. }
  2307. if d.d.TryDecodeAsNil() {
  2308. setZero(v)
  2309. } else {
  2310. d.bi.calls++
  2311. d.decode(v)
  2312. d.bi.calls--
  2313. }
  2314. if d.bi.calls == 0 {
  2315. d.d.atEndOfDecode()
  2316. if !d.h.ExplicitRelease {
  2317. d.bi.release()
  2318. }
  2319. }
  2320. }
  2321. // func (d *Decoder) deferred(err1 *error) {
  2322. // if recoverPanicToErr {
  2323. // if x := recover(); x != nil {
  2324. // panicValToErr(d, x, err1)
  2325. // panicValToErr(d, x, &d.err)
  2326. // }
  2327. // }
  2328. // }
  2329. //go:noinline -- as it is run by finalizer
  2330. func (d *Decoder) finalize() {
  2331. // xdebugf("finalizing Decoder")
  2332. d.Release()
  2333. }
  2334. // Release releases shared (pooled) resources.
  2335. //
  2336. // It is important to call Release() when done with a Decoder, so those resources
  2337. // are released instantly for use by subsequently created Decoders.
  2338. //
  2339. // By default, Release() is automatically called unless the option ExplicitRelease is set.
  2340. func (d *Decoder) Release() {
  2341. if d.bi != nil {
  2342. d.bi.release()
  2343. }
  2344. // d.decNakedPooler.end()
  2345. }
  2346. // // this is not a smart swallow, as it allocates objects and does unnecessary work.
  2347. // func (d *Decoder) swallowViaHammer() {
  2348. // var blank interface{}
  2349. // d.decodeValueNoFn(reflect.ValueOf(&blank).Elem())
  2350. // }
  2351. func (d *Decoder) swallow() {
  2352. // smarter decode that just swallows the content
  2353. dd := d.d
  2354. if dd.TryDecodeAsNil() {
  2355. return
  2356. }
  2357. switch dd.ContainerType() {
  2358. case valueTypeMap:
  2359. containerLen := d.mapStart()
  2360. hasLen := containerLen >= 0
  2361. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  2362. // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break}
  2363. d.mapElemKey()
  2364. d.swallow()
  2365. d.mapElemValue()
  2366. d.swallow()
  2367. }
  2368. d.mapEnd()
  2369. case valueTypeArray:
  2370. containerLen := d.arrayStart()
  2371. hasLen := containerLen >= 0
  2372. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  2373. d.arrayElem()
  2374. d.swallow()
  2375. }
  2376. d.arrayEnd()
  2377. case valueTypeBytes:
  2378. dd.DecodeBytes(d.b[:], true)
  2379. case valueTypeString:
  2380. dd.DecodeStringAsBytes()
  2381. default:
  2382. // these are all primitives, which we can get from decodeNaked
  2383. // if RawExt using Value, complete the processing.
  2384. n := d.naked()
  2385. dd.DecodeNaked()
  2386. if n.v == valueTypeExt && n.l == nil {
  2387. var v2 interface{}
  2388. d.decode(&v2)
  2389. }
  2390. }
  2391. }
  2392. func setZero(iv interface{}) {
  2393. if iv == nil || definitelyNil(iv) {
  2394. return
  2395. }
  2396. var canDecode bool
  2397. switch v := iv.(type) {
  2398. case *string:
  2399. *v = ""
  2400. case *bool:
  2401. *v = false
  2402. case *int:
  2403. *v = 0
  2404. case *int8:
  2405. *v = 0
  2406. case *int16:
  2407. *v = 0
  2408. case *int32:
  2409. *v = 0
  2410. case *int64:
  2411. *v = 0
  2412. case *uint:
  2413. *v = 0
  2414. case *uint8:
  2415. *v = 0
  2416. case *uint16:
  2417. *v = 0
  2418. case *uint32:
  2419. *v = 0
  2420. case *uint64:
  2421. *v = 0
  2422. case *float32:
  2423. *v = 0
  2424. case *float64:
  2425. *v = 0
  2426. case *[]uint8:
  2427. *v = nil
  2428. case *Raw:
  2429. *v = nil
  2430. case *time.Time:
  2431. *v = time.Time{}
  2432. case reflect.Value:
  2433. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2434. v.Set(reflect.Zero(v.Type()))
  2435. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2436. default:
  2437. if !fastpathDecodeSetZeroTypeSwitch(iv) {
  2438. v := reflect.ValueOf(iv)
  2439. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  2440. v.Set(reflect.Zero(v.Type()))
  2441. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  2442. }
  2443. }
  2444. }
  2445. func (d *Decoder) decode(iv interface{}) {
  2446. // a switch with only concrete types can be optimized.
  2447. // consequently, we deal with nil and interfaces outside the switch.
  2448. if iv == nil {
  2449. d.errorstr(errstrCannotDecodeIntoNil)
  2450. return
  2451. }
  2452. switch v := iv.(type) {
  2453. // case nil:
  2454. // case Selfer:
  2455. case reflect.Value:
  2456. v = d.ensureDecodeable(v)
  2457. d.decodeValue(v, nil)
  2458. case *string:
  2459. *v = string(d.d.DecodeStringAsBytes())
  2460. case *bool:
  2461. *v = d.d.DecodeBool()
  2462. case *int:
  2463. *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))
  2464. case *int8:
  2465. *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8))
  2466. case *int16:
  2467. *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16))
  2468. case *int32:
  2469. *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32))
  2470. case *int64:
  2471. *v = d.d.DecodeInt64()
  2472. case *uint:
  2473. *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))
  2474. case *uint8:
  2475. *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))
  2476. case *uint16:
  2477. *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))
  2478. case *uint32:
  2479. *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))
  2480. case *uint64:
  2481. *v = d.d.DecodeUint64()
  2482. case *float32:
  2483. *v = float32(d.decodeFloat32())
  2484. case *float64:
  2485. *v = d.d.DecodeFloat64()
  2486. case *[]uint8:
  2487. *v = d.d.DecodeBytes(*v, false)
  2488. case []uint8:
  2489. b := d.d.DecodeBytes(v, false)
  2490. if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) {
  2491. copy(v, b)
  2492. }
  2493. case *time.Time:
  2494. *v = d.d.DecodeTime()
  2495. case *Raw:
  2496. *v = d.rawBytes()
  2497. case *interface{}:
  2498. d.decodeValue(reflect.ValueOf(iv).Elem(), nil)
  2499. // d.decodeValueNotNil(reflect.ValueOf(iv).Elem())
  2500. default:
  2501. if v, ok := iv.(Selfer); ok {
  2502. v.CodecDecodeSelf(d)
  2503. } else if !fastpathDecodeTypeSwitch(iv, d) {
  2504. v := reflect.ValueOf(iv)
  2505. v = d.ensureDecodeable(v)
  2506. d.decodeValue(v, nil) // TODO: find a way to say: no fast path??? Not necessary???
  2507. // d.decodeValueFallback(v)
  2508. }
  2509. }
  2510. }
  2511. func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn) {
  2512. // If stream is not containing a nil value, then we can deref to the base
  2513. // non-pointer value, and decode into that.
  2514. var rvp reflect.Value
  2515. var rvpValid bool
  2516. if rv.Kind() == reflect.Ptr {
  2517. rvpValid = true
  2518. for {
  2519. if rv.IsNil() {
  2520. rv.Set(reflect.New(rv.Type().Elem()))
  2521. }
  2522. rvp = rv
  2523. rv = rv.Elem()
  2524. if rv.Kind() != reflect.Ptr {
  2525. break
  2526. }
  2527. }
  2528. }
  2529. if fn == nil {
  2530. fn = d.h.fn(rv.Type())
  2531. }
  2532. if fn.i.addrD {
  2533. if rvpValid {
  2534. fn.fd(d, &fn.i, rvp)
  2535. } else if rv.CanAddr() {
  2536. fn.fd(d, &fn.i, rv.Addr())
  2537. } else if !fn.i.addrF {
  2538. fn.fd(d, &fn.i, rv)
  2539. } else {
  2540. d.errorf("cannot decode into a non-pointer value")
  2541. }
  2542. } else {
  2543. fn.fd(d, &fn.i, rv)
  2544. }
  2545. // return rv
  2546. }
  2547. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  2548. // NOTE: rvkencname may be a stringView, so don't pass it to another function.
  2549. if d.h.ErrorIfNoField {
  2550. if index >= 0 {
  2551. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  2552. return
  2553. } else if rvkencname != "" {
  2554. d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
  2555. return
  2556. }
  2557. }
  2558. d.swallow()
  2559. }
  2560. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  2561. if d.h.ErrorIfNoArrayExpand {
  2562. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  2563. }
  2564. }
  2565. func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) {
  2566. switch rv.Kind() {
  2567. case reflect.Array:
  2568. return rv, rv.CanAddr()
  2569. case reflect.Ptr:
  2570. if !rv.IsNil() {
  2571. return rv.Elem(), true
  2572. }
  2573. case reflect.Slice, reflect.Chan, reflect.Map:
  2574. if !rv.IsNil() {
  2575. return rv, true
  2576. }
  2577. }
  2578. return
  2579. }
  2580. func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) {
  2581. // decode can take any reflect.Value that is a inherently addressable i.e.
  2582. // - array
  2583. // - non-nil chan (we will SEND to it)
  2584. // - non-nil slice (we will set its elements)
  2585. // - non-nil map (we will put into it)
  2586. // - non-nil pointer (we can "update" it)
  2587. rv2, canDecode := isDecodeable(rv)
  2588. if canDecode {
  2589. return
  2590. }
  2591. if !rv.IsValid() {
  2592. d.errorstr(errstrCannotDecodeIntoNil)
  2593. return
  2594. }
  2595. if !rv.CanInterface() {
  2596. d.errorf("cannot decode into a value without an interface: %v", rv)
  2597. return
  2598. }
  2599. rvi := rv2i(rv)
  2600. rvk := rv.Kind()
  2601. d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi)
  2602. return
  2603. }
  2604. func (d *Decoder) depthIncr() {
  2605. d.depth++
  2606. if d.depth >= d.maxdepth {
  2607. panic(errMaxDepthExceeded)
  2608. }
  2609. }
  2610. func (d *Decoder) depthDecr() {
  2611. d.depth--
  2612. }
  2613. // Possibly get an interned version of a string
  2614. //
  2615. // This should mostly be used for map keys, where the key type is string.
  2616. // This is because keys of a map/struct are typically reused across many objects.
  2617. func (d *Decoder) string(v []byte) (s string) {
  2618. if d.is == nil {
  2619. return string(v) // don't return stringView, as we need a real string here.
  2620. }
  2621. s, ok := d.is[string(v)] // no allocation here, per go implementation
  2622. if !ok {
  2623. s = string(v) // new allocation here
  2624. d.is[s] = s
  2625. }
  2626. return s
  2627. }
  2628. // nextValueBytes returns the next value in the stream as a set of bytes.
  2629. func (d *Decoder) nextValueBytes() (bs []byte) {
  2630. d.d.uncacheRead()
  2631. d.r().track()
  2632. d.swallow()
  2633. bs = d.r().stopTrack()
  2634. return
  2635. }
  2636. func (d *Decoder) rawBytes() []byte {
  2637. // ensure that this is not a view into the bytes
  2638. // i.e. make new copy always.
  2639. bs := d.nextValueBytes()
  2640. bs2 := make([]byte, len(bs))
  2641. copy(bs2, bs)
  2642. return bs2
  2643. }
  2644. func (d *Decoder) wrapErr(v interface{}, err *error) {
  2645. *err = decodeError{codecError: codecError{name: d.hh.Name(), err: v}, pos: int(d.r().numread())}
  2646. }
  2647. // NumBytesRead returns the number of bytes read
  2648. func (d *Decoder) NumBytesRead() int {
  2649. return int(d.r().numread())
  2650. }
  2651. // decodeFloat32 will delegate to an appropriate DecodeFloat32 implementation (if exists),
  2652. // else if will call DecodeFloat64 and ensure the value doesn't overflow.
  2653. //
  2654. // Note that we return float64 to reduce unnecessary conversions
  2655. func (d *Decoder) decodeFloat32() float32 {
  2656. if d.js {
  2657. return d.jdec.DecodeFloat32() // custom implementation for 32-bit
  2658. }
  2659. return float32(chkOvf.Float32V(d.d.DecodeFloat64()))
  2660. }
  2661. // ---- container tracking
  2662. // Note: We update the .c after calling the callback.
  2663. // This way, the callback can know what the last status was.
  2664. func (d *Decoder) mapStart() (v int) {
  2665. v = d.d.ReadMapStart()
  2666. d.depthIncr()
  2667. d.c = containerMapStart
  2668. return
  2669. }
  2670. func (d *Decoder) mapElemKey() {
  2671. if d.js {
  2672. d.jdec.ReadMapElemKey()
  2673. }
  2674. d.c = containerMapKey
  2675. }
  2676. func (d *Decoder) mapElemValue() {
  2677. if d.js {
  2678. d.jdec.ReadMapElemValue()
  2679. }
  2680. d.c = containerMapValue
  2681. }
  2682. func (d *Decoder) mapEnd() {
  2683. d.d.ReadMapEnd()
  2684. d.depthDecr()
  2685. d.c = containerMapEnd
  2686. d.c = 0
  2687. }
  2688. func (d *Decoder) arrayStart() (v int) {
  2689. v = d.d.ReadArrayStart()
  2690. d.depthIncr()
  2691. d.c = containerArrayStart
  2692. return
  2693. }
  2694. func (d *Decoder) arrayElem() {
  2695. if d.js {
  2696. d.jdec.ReadArrayElem()
  2697. }
  2698. d.c = containerArrayElem
  2699. }
  2700. func (d *Decoder) arrayEnd() {
  2701. d.d.ReadArrayEnd()
  2702. d.depthDecr()
  2703. d.c = containerArrayEnd
  2704. d.c = 0
  2705. }
  2706. func (d *Decoder) interfaceExtConvertAndDecode(v interface{}, ext Ext) {
  2707. // var v interface{} = ext.ConvertExt(rv)
  2708. // d.d.decode(&v)
  2709. // ext.UpdateExt(rv, v)
  2710. // assume v is a pointer:
  2711. // - if struct|array, pass as is to ConvertExt
  2712. // - else make it non-addressable and pass to ConvertExt
  2713. // - make return value from ConvertExt addressable
  2714. // - decode into it
  2715. // - return the interface for passing into UpdateExt.
  2716. // - interface should be a pointer if struct|array, else a value
  2717. var s interface{}
  2718. rv := reflect.ValueOf(v)
  2719. rv2 := rv.Elem()
  2720. rvk := rv2.Kind()
  2721. if rvk == reflect.Struct || rvk == reflect.Array {
  2722. s = ext.ConvertExt(v)
  2723. } else {
  2724. s = ext.ConvertExt(rv2i(rv2))
  2725. }
  2726. rv = reflect.ValueOf(s)
  2727. if !rv.CanAddr() {
  2728. if rv.Kind() == reflect.Ptr {
  2729. rv2 = reflect.New(rv.Type().Elem())
  2730. rv2.Set(rv)
  2731. } else {
  2732. rv2 = reflect.New(rv.Type()).Elem()
  2733. rv2.Set(rv)
  2734. }
  2735. rv = rv2
  2736. }
  2737. d.decodeValue(rv, nil)
  2738. ext.UpdateExt(v, rv2i(rv))
  2739. }
  2740. func (d *Decoder) sideDecode(v interface{}, bs []byte) {
  2741. rv := baseRV(v)
  2742. NewDecoderBytes(bs, d.hh).decodeValue(rv, d.h.fnNoExt(rv.Type()))
  2743. }
  2744. // --------------------------------------------------
  2745. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  2746. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  2747. type decSliceHelper struct {
  2748. d *Decoder
  2749. ct valueType
  2750. array bool
  2751. }
  2752. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  2753. x.ct = d.d.ContainerType()
  2754. x.d = d
  2755. switch x.ct {
  2756. case valueTypeArray:
  2757. x.array = true
  2758. clen = d.arrayStart()
  2759. case valueTypeMap:
  2760. clen = d.mapStart() * 2
  2761. default:
  2762. d.errorf("only encoded map or array can be decoded into a slice (%d)", x.ct)
  2763. }
  2764. return
  2765. }
  2766. func (x decSliceHelper) End() {
  2767. if x.array {
  2768. x.d.arrayEnd()
  2769. } else {
  2770. x.d.mapEnd()
  2771. }
  2772. }
  2773. func (x decSliceHelper) ElemContainerState(index int) {
  2774. if x.array {
  2775. x.d.arrayElem()
  2776. } else if index%2 == 0 {
  2777. x.d.mapElemKey()
  2778. } else {
  2779. x.d.mapElemValue()
  2780. }
  2781. }
  2782. func decByteSlice(r *decReaderSwitch, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2783. if clen == 0 {
  2784. return zeroByteSlice
  2785. }
  2786. if len(bs) == clen {
  2787. bsOut = bs
  2788. r.readb(bsOut)
  2789. } else if cap(bs) >= clen {
  2790. bsOut = bs[:clen]
  2791. r.readb(bsOut)
  2792. } else {
  2793. // bsOut = make([]byte, clen)
  2794. len2 := decInferLen(clen, maxInitLen, 1)
  2795. bsOut = make([]byte, len2)
  2796. r.readb(bsOut)
  2797. for len2 < clen {
  2798. len3 := decInferLen(clen-len2, maxInitLen, 1)
  2799. bs3 := bsOut
  2800. bsOut = make([]byte, len2+len3)
  2801. copy(bsOut, bs3)
  2802. r.readb(bsOut[len2:])
  2803. len2 += len3
  2804. }
  2805. }
  2806. return
  2807. }
  2808. // func decByteSliceZeroCopy(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2809. // if _, ok := r.(*bytesDecReader); ok && clen <= maxInitLen {
  2810. // return r.readx(clen)
  2811. // }
  2812. // return decByteSlice(r, clen, maxInitLen, bs)
  2813. // }
  2814. func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
  2815. if xlen := len(in); xlen > 0 {
  2816. if isBytesReader || xlen <= scratchByteArrayLen {
  2817. if cap(dest) >= xlen {
  2818. out = dest[:xlen]
  2819. } else {
  2820. out = make([]byte, xlen)
  2821. }
  2822. copy(out, in)
  2823. return
  2824. }
  2825. }
  2826. return in
  2827. }
  2828. // decInferLen will infer a sensible length, given the following:
  2829. // - clen: length wanted.
  2830. // - maxlen: max length to be returned.
  2831. // if <= 0, it is unset, and we infer it based on the unit size
  2832. // - unit: number of bytes for each element of the collection
  2833. func decInferLen(clen, maxlen, unit int) (rvlen int) {
  2834. // handle when maxlen is not set i.e. <= 0
  2835. if clen <= 0 {
  2836. return
  2837. }
  2838. if unit == 0 {
  2839. return clen
  2840. }
  2841. if maxlen <= 0 {
  2842. // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
  2843. // maxlen = 256 * 1024 / unit
  2844. // if maxlen < (4 * 1024) {
  2845. // maxlen = 4 * 1024
  2846. // }
  2847. if unit < (256 / 4) {
  2848. maxlen = 256 * 1024 / unit
  2849. } else {
  2850. maxlen = 4 * 1024
  2851. }
  2852. }
  2853. if clen > maxlen {
  2854. rvlen = maxlen
  2855. } else {
  2856. rvlen = clen
  2857. }
  2858. return
  2859. }
  2860. func expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) (
  2861. s2 reflect.Value, scap2 int, changed bool, err string) {
  2862. l1 := slen + num // new slice length
  2863. if l1 < slen {
  2864. err = errmsgExpandSliceOverflow
  2865. return
  2866. }
  2867. if l1 <= scap {
  2868. if s.CanSet() {
  2869. s.SetLen(l1)
  2870. } else if canChange {
  2871. s2 = s.Slice(0, l1)
  2872. scap2 = scap
  2873. changed = true
  2874. } else {
  2875. err = errmsgExpandSliceCannotChange
  2876. return
  2877. }
  2878. return
  2879. }
  2880. if !canChange {
  2881. err = errmsgExpandSliceCannotChange
  2882. return
  2883. }
  2884. scap2 = growCap(scap, stElemSize, num)
  2885. s2 = reflect.MakeSlice(st, l1, scap2)
  2886. changed = true
  2887. reflect.Copy(s2, s)
  2888. return
  2889. }
  2890. func decReadFull(r io.Reader, bs []byte) (n uint, err error) {
  2891. var nn int
  2892. for n < uint(len(bs)) && err == nil {
  2893. nn, err = r.Read(bs[n:])
  2894. if nn > 0 {
  2895. if err == io.EOF {
  2896. // leave EOF for next time
  2897. err = nil
  2898. }
  2899. n += uint(nn)
  2900. }
  2901. }
  2902. // xdebugf("decReadFull: len(bs): %v, n: %v, err: %v", len(bs), n, err)
  2903. // do not do this - it serves no purpose
  2904. // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
  2905. return
  2906. }
  2907. func decNakedReadRawBytes(dr decDriver, d *Decoder, n *decNaked, rawToString bool) {
  2908. if rawToString {
  2909. n.v = valueTypeString
  2910. n.s = string(dr.DecodeBytes(d.b[:], true))
  2911. } else {
  2912. n.v = valueTypeBytes
  2913. n.l = dr.DecodeBytes(nil, false)
  2914. }
  2915. }