decode.go 62 KB

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