decode.go 61 KB

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