decode.go 57 KB

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