decode.go 50 KB

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