decode.go 52 KB

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