decode.go 62 KB

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