decode.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  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. d.decode(&n.ms[l])
  506. rvn = reflect.ValueOf(&n.ms[l]).Elem()
  507. n.ms = n.ms[:l]
  508. } else if d.mtid == mapStrIntfTypId { // for json performance
  509. l := len(n.ns)
  510. n.ns = append(n.ns, nil)
  511. d.decode(&n.ns[l])
  512. rvn = reflect.ValueOf(&n.ns[l]).Elem()
  513. n.ns = n.ns[:l]
  514. } else {
  515. rvn = reflect.New(d.h.MapType).Elem()
  516. d.decodeValue(rvn, nil)
  517. }
  518. case valueTypeArray:
  519. // if d.h.SliceType == nil || d.h.SliceType == intfSliceTyp {
  520. if d.stid == 0 || d.stid == intfSliceTypId {
  521. l := len(n.ss)
  522. n.ss = append(n.ss, nil)
  523. d.decode(&n.ss[l])
  524. rvn = reflect.ValueOf(&n.ss[l]).Elem()
  525. n.ss = n.ss[:l]
  526. } else {
  527. rvn = reflect.New(d.h.SliceType).Elem()
  528. d.decodeValue(rvn, nil)
  529. }
  530. case valueTypeExt:
  531. var v interface{}
  532. tag, bytes := n.u, n.l // calling decode below might taint the values
  533. if bytes == nil {
  534. l := len(n.is)
  535. n.is = append(n.is, nil)
  536. v2 := &n.is[l]
  537. n.is = n.is[:l]
  538. d.decode(v2)
  539. v = *v2
  540. }
  541. bfn := d.h.getExtForTag(tag)
  542. if bfn == nil {
  543. var re RawExt
  544. re.Tag = tag
  545. re.Data = detachZeroCopyBytes(d.bytes, nil, bytes)
  546. rvn = reflect.ValueOf(re)
  547. } else {
  548. rvnA := reflect.New(bfn.rt)
  549. rvn = rvnA.Elem()
  550. if bytes != nil {
  551. bfn.ext.ReadExt(rvnA.Interface(), bytes)
  552. } else {
  553. bfn.ext.UpdateExt(rvnA.Interface(), v)
  554. }
  555. }
  556. case valueTypeNil:
  557. // no-op
  558. case valueTypeInt:
  559. rvn = reflect.ValueOf(&n.i).Elem()
  560. case valueTypeUint:
  561. rvn = reflect.ValueOf(&n.u).Elem()
  562. case valueTypeFloat:
  563. rvn = reflect.ValueOf(&n.f).Elem()
  564. case valueTypeBool:
  565. rvn = reflect.ValueOf(&n.b).Elem()
  566. case valueTypeString, valueTypeSymbol:
  567. rvn = reflect.ValueOf(&n.s).Elem()
  568. case valueTypeBytes:
  569. rvn = reflect.ValueOf(&n.l).Elem()
  570. case valueTypeTimestamp:
  571. rvn = reflect.ValueOf(&n.t).Elem()
  572. default:
  573. panic(fmt.Errorf("kInterfaceNaked: unexpected valueType: %d", n.v))
  574. }
  575. return
  576. }
  577. func (f *decFnInfo) kInterface(rv reflect.Value) {
  578. // debugf("\t===> kInterface")
  579. // Note:
  580. // A consequence of how kInterface works, is that
  581. // if an interface already contains something, we try
  582. // to decode into what was there before.
  583. // We do not replace with a generic value (as got from decodeNaked).
  584. var rvn reflect.Value
  585. if rv.IsNil() {
  586. rvn = f.kInterfaceNaked()
  587. if rvn.IsValid() {
  588. rv.Set(rvn)
  589. }
  590. } else if f.d.h.InterfaceReset {
  591. rvn = f.kInterfaceNaked()
  592. if rvn.IsValid() {
  593. rv.Set(rvn)
  594. } else {
  595. // reset to zero value based on current type in there.
  596. rv.Set(reflect.Zero(rv.Elem().Type()))
  597. }
  598. } else {
  599. rvn = rv.Elem()
  600. // Note: interface{} is settable, but underlying type may not be.
  601. // Consequently, we have to set the reflect.Value directly.
  602. // if underlying type is settable (e.g. ptr or interface),
  603. // we just decode into it.
  604. // Else we create a settable value, decode into it, and set on the interface.
  605. if rvn.CanSet() {
  606. f.d.decodeValue(rvn, nil)
  607. } else {
  608. rvn2 := reflect.New(rvn.Type()).Elem()
  609. rvn2.Set(rvn)
  610. f.d.decodeValue(rvn2, nil)
  611. rv.Set(rvn2)
  612. }
  613. }
  614. }
  615. func (f *decFnInfo) kStruct(rv reflect.Value) {
  616. fti := f.ti
  617. d := f.d
  618. dd := d.d
  619. cr := d.cr
  620. ctyp := dd.ContainerType()
  621. if ctyp == valueTypeMap {
  622. containerLen := dd.ReadMapStart()
  623. if containerLen == 0 {
  624. if cr != nil {
  625. cr.sendContainerState(containerMapEnd)
  626. }
  627. return
  628. }
  629. tisfi := fti.sfi
  630. hasLen := containerLen >= 0
  631. if hasLen {
  632. for j := 0; j < containerLen; j++ {
  633. // rvkencname := dd.DecodeString()
  634. if cr != nil {
  635. cr.sendContainerState(containerMapKey)
  636. }
  637. rvkencname := stringView(dd.DecodeBytes(f.d.b[:], true, true))
  638. // rvksi := ti.getForEncName(rvkencname)
  639. if cr != nil {
  640. cr.sendContainerState(containerMapValue)
  641. }
  642. if k := fti.indexForEncName(rvkencname); k > -1 {
  643. si := tisfi[k]
  644. if dd.TryDecodeAsNil() {
  645. si.setToZeroValue(rv)
  646. } else {
  647. d.decodeValue(si.field(rv, true), nil)
  648. }
  649. } else {
  650. d.structFieldNotFound(-1, rvkencname)
  651. }
  652. }
  653. } else {
  654. for j := 0; !dd.CheckBreak(); j++ {
  655. // rvkencname := dd.DecodeString()
  656. if cr != nil {
  657. cr.sendContainerState(containerMapKey)
  658. }
  659. rvkencname := stringView(dd.DecodeBytes(f.d.b[:], true, true))
  660. // rvksi := ti.getForEncName(rvkencname)
  661. if cr != nil {
  662. cr.sendContainerState(containerMapValue)
  663. }
  664. if k := fti.indexForEncName(rvkencname); k > -1 {
  665. si := tisfi[k]
  666. if dd.TryDecodeAsNil() {
  667. si.setToZeroValue(rv)
  668. } else {
  669. d.decodeValue(si.field(rv, true), nil)
  670. }
  671. } else {
  672. d.structFieldNotFound(-1, rvkencname)
  673. }
  674. }
  675. }
  676. if cr != nil {
  677. cr.sendContainerState(containerMapEnd)
  678. }
  679. } else if ctyp == valueTypeArray {
  680. containerLen := dd.ReadArrayStart()
  681. if containerLen == 0 {
  682. if cr != nil {
  683. cr.sendContainerState(containerArrayEnd)
  684. }
  685. return
  686. }
  687. // Not much gain from doing it two ways for array.
  688. // Arrays are not used as much for structs.
  689. hasLen := containerLen >= 0
  690. for j, si := range fti.sfip {
  691. if hasLen {
  692. if j == containerLen {
  693. break
  694. }
  695. } else if dd.CheckBreak() {
  696. break
  697. }
  698. if cr != nil {
  699. cr.sendContainerState(containerArrayElem)
  700. }
  701. if dd.TryDecodeAsNil() {
  702. si.setToZeroValue(rv)
  703. } else {
  704. d.decodeValue(si.field(rv, true), nil)
  705. }
  706. }
  707. if containerLen > len(fti.sfip) {
  708. // read remaining values and throw away
  709. for j := len(fti.sfip); j < containerLen; j++ {
  710. if cr != nil {
  711. cr.sendContainerState(containerArrayElem)
  712. }
  713. d.structFieldNotFound(j, "")
  714. }
  715. }
  716. if cr != nil {
  717. cr.sendContainerState(containerArrayEnd)
  718. }
  719. } else {
  720. f.d.error(onlyMapOrArrayCanDecodeIntoStructErr)
  721. return
  722. }
  723. }
  724. func (f *decFnInfo) kSlice(rv reflect.Value) {
  725. // A slice can be set from a map or array in stream.
  726. // This way, the order can be kept (as order is lost with map).
  727. ti := f.ti
  728. d := f.d
  729. dd := d.d
  730. rtelem0 := ti.rt.Elem()
  731. ctyp := dd.ContainerType()
  732. if ctyp == valueTypeBytes || ctyp == valueTypeString {
  733. // you can only decode bytes or string in the stream into a slice or array of bytes
  734. if !(ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) {
  735. f.d.errorf("bytes or string in the stream must be decoded into a slice or array of bytes, not %v", ti.rt)
  736. }
  737. if f.seq == seqTypeChan {
  738. bs2 := dd.DecodeBytes(nil, false, true)
  739. ch := rv.Interface().(chan<- byte)
  740. for _, b := range bs2 {
  741. ch <- b
  742. }
  743. } else {
  744. rvbs := rv.Bytes()
  745. bs2 := dd.DecodeBytes(rvbs, false, false)
  746. if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) {
  747. if rv.CanSet() {
  748. rv.SetBytes(bs2)
  749. } else {
  750. copy(rvbs, bs2)
  751. }
  752. }
  753. }
  754. return
  755. }
  756. // array := f.seq == seqTypeChan
  757. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map)
  758. // // an array can never return a nil slice. so no need to check f.array here.
  759. if containerLenS == 0 {
  760. if f.seq == seqTypeSlice {
  761. if rv.IsNil() {
  762. rv.Set(reflect.MakeSlice(ti.rt, 0, 0))
  763. } else {
  764. rv.SetLen(0)
  765. }
  766. } else if f.seq == seqTypeChan {
  767. if rv.IsNil() {
  768. rv.Set(reflect.MakeChan(ti.rt, 0))
  769. }
  770. }
  771. slh.End()
  772. return
  773. }
  774. rtelem := rtelem0
  775. for rtelem.Kind() == reflect.Ptr {
  776. rtelem = rtelem.Elem()
  777. }
  778. fn := d.getDecFn(rtelem, true, true)
  779. var rv0, rv9 reflect.Value
  780. rv0 = rv
  781. rvChanged := false
  782. // for j := 0; j < containerLenS; j++ {
  783. var rvlen int
  784. if containerLenS > 0 { // hasLen
  785. if f.seq == seqTypeChan {
  786. if rv.IsNil() {
  787. rvlen, _ = decInferLen(containerLenS, f.d.h.MaxInitLen, int(rtelem0.Size()))
  788. rv.Set(reflect.MakeChan(ti.rt, rvlen))
  789. }
  790. // handle chan specially:
  791. for j := 0; j < containerLenS; j++ {
  792. rv9 = reflect.New(rtelem0).Elem()
  793. slh.ElemContainerState(j)
  794. d.decodeValue(rv9, fn)
  795. rv.Send(rv9)
  796. }
  797. } else { // slice or array
  798. var truncated bool // says len of sequence is not same as expected number of elements
  799. numToRead := containerLenS // if truncated, reset numToRead
  800. rvcap := rv.Cap()
  801. rvlen = rv.Len()
  802. if containerLenS > rvcap {
  803. if f.seq == seqTypeArray {
  804. d.arrayCannotExpand(rvlen, containerLenS)
  805. } else {
  806. oldRvlenGtZero := rvlen > 0
  807. rvlen, truncated = decInferLen(containerLenS, f.d.h.MaxInitLen, int(rtelem0.Size()))
  808. if truncated {
  809. if rvlen <= rvcap {
  810. rv.SetLen(rvlen)
  811. } else {
  812. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  813. rvChanged = true
  814. }
  815. } else {
  816. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  817. rvChanged = true
  818. }
  819. if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) {
  820. reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
  821. }
  822. rvcap = rvlen
  823. }
  824. numToRead = rvlen
  825. } else if containerLenS != rvlen {
  826. if f.seq == seqTypeSlice {
  827. rv.SetLen(containerLenS)
  828. rvlen = containerLenS
  829. }
  830. }
  831. j := 0
  832. // we read up to the numToRead
  833. for ; j < numToRead; j++ {
  834. slh.ElemContainerState(j)
  835. d.decodeValue(rv.Index(j), fn)
  836. }
  837. // if slice, expand and read up to containerLenS (or EOF) iff truncated
  838. // if array, swallow all the rest.
  839. if f.seq == seqTypeArray {
  840. for ; j < containerLenS; j++ {
  841. slh.ElemContainerState(j)
  842. d.swallow()
  843. }
  844. } else if truncated { // slice was truncated, as chan NOT in this block
  845. for ; j < containerLenS; j++ {
  846. rv = expandSliceValue(rv, 1)
  847. rv9 = rv.Index(j)
  848. if resetSliceElemToZeroValue {
  849. rv9.Set(reflect.Zero(rtelem0))
  850. }
  851. slh.ElemContainerState(j)
  852. d.decodeValue(rv9, fn)
  853. }
  854. }
  855. }
  856. } else {
  857. rvlen = rv.Len()
  858. j := 0
  859. for ; !dd.CheckBreak(); j++ {
  860. if f.seq == seqTypeChan {
  861. slh.ElemContainerState(j)
  862. rv9 = reflect.New(rtelem0).Elem()
  863. d.decodeValue(rv9, fn)
  864. rv.Send(rv9)
  865. } else {
  866. // if indefinite, etc, then expand the slice if necessary
  867. var decodeIntoBlank bool
  868. if j >= rvlen {
  869. if f.seq == seqTypeArray {
  870. d.arrayCannotExpand(rvlen, j+1)
  871. decodeIntoBlank = true
  872. } else { // if f.seq == seqTypeSlice
  873. // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // uses append logic, plus varargs
  874. rv = expandSliceValue(rv, 1)
  875. rv9 = rv.Index(j)
  876. // rv.Index(rv.Len() - 1).Set(reflect.Zero(rtelem0))
  877. if resetSliceElemToZeroValue {
  878. rv9.Set(reflect.Zero(rtelem0))
  879. }
  880. rvlen++
  881. rvChanged = true
  882. }
  883. } else { // slice or array
  884. rv9 = rv.Index(j)
  885. }
  886. slh.ElemContainerState(j)
  887. if decodeIntoBlank {
  888. d.swallow()
  889. } else { // seqTypeSlice
  890. d.decodeValue(rv9, fn)
  891. }
  892. }
  893. }
  894. if f.seq == seqTypeSlice {
  895. if j < rvlen {
  896. rv.SetLen(j)
  897. } else if j == 0 && rv.IsNil() {
  898. rv = reflect.MakeSlice(ti.rt, 0, 0)
  899. rvChanged = true
  900. }
  901. }
  902. }
  903. slh.End()
  904. if rvChanged {
  905. rv0.Set(rv)
  906. }
  907. }
  908. func (f *decFnInfo) kArray(rv reflect.Value) {
  909. // f.d.decodeValue(rv.Slice(0, rv.Len()))
  910. f.kSlice(rv.Slice(0, rv.Len()))
  911. }
  912. func (f *decFnInfo) kMap(rv reflect.Value) {
  913. d := f.d
  914. dd := d.d
  915. containerLen := dd.ReadMapStart()
  916. cr := d.cr
  917. ti := f.ti
  918. if rv.IsNil() {
  919. rv.Set(reflect.MakeMap(ti.rt))
  920. }
  921. if containerLen == 0 {
  922. if cr != nil {
  923. cr.sendContainerState(containerMapEnd)
  924. }
  925. return
  926. }
  927. ktype, vtype := ti.rt.Key(), ti.rt.Elem()
  928. ktypeId := reflect.ValueOf(ktype).Pointer()
  929. vtypeKind := vtype.Kind()
  930. var keyFn, valFn *decFn
  931. var xtyp reflect.Type
  932. for xtyp = ktype; xtyp.Kind() == reflect.Ptr; xtyp = xtyp.Elem() {
  933. }
  934. keyFn = d.getDecFn(xtyp, true, true)
  935. for xtyp = vtype; xtyp.Kind() == reflect.Ptr; xtyp = xtyp.Elem() {
  936. }
  937. valFn = d.getDecFn(xtyp, true, true)
  938. var mapGet, mapSet bool
  939. if !f.d.h.MapValueReset {
  940. // if pointer, mapGet = true
  941. // if interface, mapGet = true if !DecodeNakedAlways (else false)
  942. // if builtin, mapGet = false
  943. // else mapGet = true
  944. if vtypeKind == reflect.Ptr {
  945. mapGet = true
  946. } else if vtypeKind == reflect.Interface {
  947. if !f.d.h.InterfaceReset {
  948. mapGet = true
  949. }
  950. } else if !isImmutableKind(vtypeKind) {
  951. mapGet = true
  952. }
  953. }
  954. var rvk, rvv, rvz reflect.Value
  955. // for j := 0; j < containerLen; j++ {
  956. if containerLen > 0 {
  957. for j := 0; j < containerLen; j++ {
  958. rvk = reflect.New(ktype).Elem()
  959. if cr != nil {
  960. cr.sendContainerState(containerMapKey)
  961. }
  962. d.decodeValue(rvk, keyFn)
  963. // special case if a byte array.
  964. if ktypeId == intfTypId {
  965. rvk = rvk.Elem()
  966. if rvk.Type() == uint8SliceTyp {
  967. rvk = reflect.ValueOf(d.string(rvk.Bytes()))
  968. }
  969. }
  970. mapSet = true // set to false if u do a get, and its a pointer, and exists
  971. if mapGet {
  972. rvv = rv.MapIndex(rvk)
  973. if rvv.IsValid() {
  974. if vtypeKind == reflect.Ptr {
  975. mapSet = false
  976. }
  977. } else {
  978. if rvz.IsValid() {
  979. rvz.Set(reflect.Zero(vtype))
  980. } else {
  981. rvz = reflect.New(vtype).Elem()
  982. }
  983. rvv = rvz
  984. }
  985. } else {
  986. if rvz.IsValid() {
  987. rvz.Set(reflect.Zero(vtype))
  988. } else {
  989. rvz = reflect.New(vtype).Elem()
  990. }
  991. rvv = rvz
  992. }
  993. if cr != nil {
  994. cr.sendContainerState(containerMapValue)
  995. }
  996. d.decodeValue(rvv, valFn)
  997. if mapSet {
  998. rv.SetMapIndex(rvk, rvv)
  999. }
  1000. }
  1001. } else {
  1002. for j := 0; !dd.CheckBreak(); j++ {
  1003. rvk = reflect.New(ktype).Elem()
  1004. if cr != nil {
  1005. cr.sendContainerState(containerMapKey)
  1006. }
  1007. d.decodeValue(rvk, keyFn)
  1008. // special case if a byte array.
  1009. if ktypeId == intfTypId {
  1010. rvk = rvk.Elem()
  1011. if rvk.Type() == uint8SliceTyp {
  1012. rvk = reflect.ValueOf(d.string(rvk.Bytes()))
  1013. }
  1014. }
  1015. mapSet = true // set to false if u do a get, and its a pointer, and exists
  1016. if mapGet {
  1017. rvv = rv.MapIndex(rvk)
  1018. if rvv.IsValid() {
  1019. if vtypeKind == reflect.Ptr {
  1020. mapSet = false
  1021. }
  1022. } else {
  1023. if rvz.IsValid() {
  1024. rvz.Set(reflect.Zero(vtype))
  1025. } else {
  1026. rvz = reflect.New(vtype).Elem()
  1027. }
  1028. rvv = rvz
  1029. }
  1030. } else {
  1031. if rvz.IsValid() {
  1032. rvz.Set(reflect.Zero(vtype))
  1033. } else {
  1034. rvz = reflect.New(vtype).Elem()
  1035. }
  1036. rvv = rvz
  1037. }
  1038. if cr != nil {
  1039. cr.sendContainerState(containerMapValue)
  1040. }
  1041. d.decodeValue(rvv, valFn)
  1042. if mapSet {
  1043. rv.SetMapIndex(rvk, rvv)
  1044. }
  1045. }
  1046. }
  1047. if cr != nil {
  1048. cr.sendContainerState(containerMapEnd)
  1049. }
  1050. }
  1051. type decRtidFn struct {
  1052. rtid uintptr
  1053. fn decFn
  1054. }
  1055. // decNaked is used to keep track of the primitives decoded.
  1056. // Without it, we would have to decode each primitive and wrap it
  1057. // in an interface{}, causing an allocation.
  1058. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  1059. // so we can rest assured that no other decoding happens while these
  1060. // primitives are being decoded.
  1061. //
  1062. // maps and arrays are not handled by this mechanism.
  1063. // However, RawExt is, and we accomodate for extensions that decode
  1064. // RawExt from DecodeNaked, but need to decode the value subsequently.
  1065. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
  1066. //
  1067. // However, decNaked also keeps some arrays of default maps and slices
  1068. // used in DecodeNaked. This way, we can get a pointer to it
  1069. // without causing a new heap allocation.
  1070. //
  1071. // kInterfaceNaked will ensure that there is no allocation for the common
  1072. // uses.
  1073. type decNaked struct {
  1074. // r RawExt // used for RawExt, uint, []byte.
  1075. u uint64
  1076. i int64
  1077. f float64
  1078. l []byte
  1079. s string
  1080. t time.Time
  1081. b bool
  1082. v valueType
  1083. // stacks for reducing allocation
  1084. is []interface{}
  1085. ms []map[interface{}]interface{}
  1086. ns []map[string]interface{}
  1087. ss [][]interface{}
  1088. // rs []RawExt
  1089. // keep arrays at the bottom? Chance is that they are not used much.
  1090. ia [4]interface{}
  1091. ma [4]map[interface{}]interface{}
  1092. na [4]map[string]interface{}
  1093. sa [4][]interface{}
  1094. // ra [2]RawExt
  1095. }
  1096. func (n *decNaked) reset() {
  1097. if n.ss != nil {
  1098. n.ss = n.ss[:0]
  1099. }
  1100. if n.is != nil {
  1101. n.is = n.is[:0]
  1102. }
  1103. if n.ms != nil {
  1104. n.ms = n.ms[:0]
  1105. }
  1106. if n.ns != nil {
  1107. n.ns = n.ns[:0]
  1108. }
  1109. }
  1110. // A Decoder reads and decodes an object from an input stream in the codec format.
  1111. type Decoder struct {
  1112. // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
  1113. // Try to put things that go together to fit within a cache line (8 words).
  1114. d decDriver
  1115. // NOTE: Decoder shouldn't call it's read methods,
  1116. // as the handler MAY need to do some coordination.
  1117. r decReader
  1118. // sa [initCollectionCap]decRtidFn
  1119. h *BasicHandle
  1120. hh Handle
  1121. be bool // is binary encoding
  1122. bytes bool // is bytes reader
  1123. js bool // is json handle
  1124. rb bytesDecReader
  1125. ri ioDecReader
  1126. cr containerStateRecv
  1127. s []decRtidFn
  1128. f map[uintptr]*decFn
  1129. // _ uintptr // for alignment purposes, so next one starts from a cache line
  1130. // cache the mapTypeId and sliceTypeId for faster comparisons
  1131. mtid uintptr
  1132. stid uintptr
  1133. n decNaked
  1134. b [scratchByteArrayLen]byte
  1135. is map[string]string // used for interning strings
  1136. }
  1137. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  1138. //
  1139. // For efficiency, Users are encouraged to pass in a memory buffered reader
  1140. // (eg bufio.Reader, bytes.Buffer).
  1141. func NewDecoder(r io.Reader, h Handle) *Decoder {
  1142. d := newDecoder(h)
  1143. d.Reset(r)
  1144. return d
  1145. }
  1146. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  1147. // from a byte slice with zero copying.
  1148. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  1149. d := newDecoder(h)
  1150. d.ResetBytes(in)
  1151. return d
  1152. }
  1153. func newDecoder(h Handle) *Decoder {
  1154. d := &Decoder{hh: h, h: h.getBasicHandle(), be: h.isBinary()}
  1155. n := &d.n
  1156. // n.rs = n.ra[:0]
  1157. n.ms = n.ma[:0]
  1158. n.is = n.ia[:0]
  1159. n.ns = n.na[:0]
  1160. n.ss = n.sa[:0]
  1161. _, d.js = h.(*JsonHandle)
  1162. if d.h.InternString {
  1163. d.is = make(map[string]string, 32)
  1164. }
  1165. d.d = h.newDecDriver(d)
  1166. d.cr, _ = d.d.(containerStateRecv)
  1167. // d.d = h.newDecDriver(decReaderT{true, &d.rb, &d.ri})
  1168. return d
  1169. }
  1170. func (d *Decoder) resetCommon() {
  1171. d.n.reset()
  1172. d.d.reset()
  1173. // reset all things which were cached from the Handle,
  1174. // but could be changed.
  1175. d.mtid, d.stid = 0, 0
  1176. if d.h.MapType != nil {
  1177. d.mtid = reflect.ValueOf(d.h.MapType).Pointer()
  1178. }
  1179. if d.h.SliceType != nil {
  1180. d.stid = reflect.ValueOf(d.h.SliceType).Pointer()
  1181. }
  1182. }
  1183. func (d *Decoder) Reset(r io.Reader) {
  1184. d.ri.x = &d.b
  1185. // d.s = d.sa[:0]
  1186. d.ri.bs.r = r
  1187. var ok bool
  1188. d.ri.br, ok = r.(decReaderByteScanner)
  1189. if !ok {
  1190. d.ri.br = &d.ri.bs
  1191. }
  1192. d.r = &d.ri
  1193. d.resetCommon()
  1194. }
  1195. func (d *Decoder) ResetBytes(in []byte) {
  1196. // d.s = d.sa[:0]
  1197. d.rb.reset(in)
  1198. d.r = &d.rb
  1199. d.resetCommon()
  1200. }
  1201. // func (d *Decoder) sendContainerState(c containerState) {
  1202. // if d.cr != nil {
  1203. // d.cr.sendContainerState(c)
  1204. // }
  1205. // }
  1206. // Decode decodes the stream from reader and stores the result in the
  1207. // value pointed to by v. v cannot be a nil pointer. v can also be
  1208. // a reflect.Value of a pointer.
  1209. //
  1210. // Note that a pointer to a nil interface is not a nil pointer.
  1211. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  1212. // We will decode and store a value in that nil interface.
  1213. //
  1214. // Sample usages:
  1215. // // Decoding into a non-nil typed value
  1216. // var f float32
  1217. // err = codec.NewDecoder(r, handle).Decode(&f)
  1218. //
  1219. // // Decoding into nil interface
  1220. // var v interface{}
  1221. // dec := codec.NewDecoder(r, handle)
  1222. // err = dec.Decode(&v)
  1223. //
  1224. // When decoding into a nil interface{}, we will decode into an appropriate value based
  1225. // on the contents of the stream:
  1226. // - Numbers are decoded as float64, int64 or uint64.
  1227. // - Other values are decoded appropriately depending on the type:
  1228. // bool, string, []byte, time.Time, etc
  1229. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  1230. // Configurations exist on the Handle to override defaults
  1231. // (e.g. for MapType, SliceType and how to decode raw bytes).
  1232. //
  1233. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  1234. // type of the value. When a value is seen:
  1235. // - If an extension is registered for it, call that extension function
  1236. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  1237. // - Else decode it based on its reflect.Kind
  1238. //
  1239. // There are some special rules when decoding into containers (slice/array/map/struct).
  1240. // Decode will typically use the stream contents to UPDATE the container.
  1241. // - A map can be decoded from a stream map, by updating matching keys.
  1242. // - A slice can be decoded from a stream array,
  1243. // by updating the first n elements, where n is length of the stream.
  1244. // - A slice can be decoded from a stream map, by decoding as if
  1245. // it contains a sequence of key-value pairs.
  1246. // - A struct can be decoded from a stream map, by updating matching fields.
  1247. // - A struct can be decoded from a stream array,
  1248. // by updating fields as they occur in the struct (by index).
  1249. //
  1250. // When decoding a stream map or array with length of 0 into a nil map or slice,
  1251. // we reset the destination map or slice to a zero-length value.
  1252. //
  1253. // However, when decoding a stream nil, we reset the destination container
  1254. // to its "zero" value (e.g. nil for slice/map, etc).
  1255. //
  1256. func (d *Decoder) Decode(v interface{}) (err error) {
  1257. defer panicToErr(&err)
  1258. d.decode(v)
  1259. return
  1260. }
  1261. // this is not a smart swallow, as it allocates objects and does unnecessary work.
  1262. func (d *Decoder) swallowViaHammer() {
  1263. var blank interface{}
  1264. d.decodeValue(reflect.ValueOf(&blank).Elem(), nil)
  1265. }
  1266. func (d *Decoder) swallow() {
  1267. // smarter decode that just swallows the content
  1268. dd := d.d
  1269. if dd.TryDecodeAsNil() {
  1270. return
  1271. }
  1272. cr := d.cr
  1273. switch dd.ContainerType() {
  1274. case valueTypeMap:
  1275. containerLen := dd.ReadMapStart()
  1276. clenGtEqualZero := containerLen >= 0
  1277. for j := 0; ; j++ {
  1278. if clenGtEqualZero {
  1279. if j >= containerLen {
  1280. break
  1281. }
  1282. } else if dd.CheckBreak() {
  1283. break
  1284. }
  1285. if cr != nil {
  1286. cr.sendContainerState(containerMapKey)
  1287. }
  1288. d.swallow()
  1289. if cr != nil {
  1290. cr.sendContainerState(containerMapValue)
  1291. }
  1292. d.swallow()
  1293. }
  1294. if cr != nil {
  1295. cr.sendContainerState(containerMapEnd)
  1296. }
  1297. case valueTypeArray:
  1298. containerLenS := dd.ReadArrayStart()
  1299. clenGtEqualZero := containerLenS >= 0
  1300. for j := 0; ; j++ {
  1301. if clenGtEqualZero {
  1302. if j >= containerLenS {
  1303. break
  1304. }
  1305. } else if dd.CheckBreak() {
  1306. break
  1307. }
  1308. if cr != nil {
  1309. cr.sendContainerState(containerArrayElem)
  1310. }
  1311. d.swallow()
  1312. }
  1313. if cr != nil {
  1314. cr.sendContainerState(containerArrayEnd)
  1315. }
  1316. case valueTypeBytes:
  1317. dd.DecodeBytes(d.b[:], false, true)
  1318. case valueTypeString:
  1319. dd.DecodeBytes(d.b[:], true, true)
  1320. // dd.DecodeStringAsBytes(d.b[:])
  1321. default:
  1322. // these are all primitives, which we can get from decodeNaked
  1323. // if RawExt using Value, complete the processing.
  1324. dd.DecodeNaked()
  1325. if n := &d.n; n.v == valueTypeExt && n.l == nil {
  1326. l := len(n.is)
  1327. n.is = append(n.is, nil)
  1328. v2 := &n.is[l]
  1329. n.is = n.is[:l]
  1330. d.decode(v2)
  1331. }
  1332. }
  1333. }
  1334. // MustDecode is like Decode, but panics if unable to Decode.
  1335. // This provides insight to the code location that triggered the error.
  1336. func (d *Decoder) MustDecode(v interface{}) {
  1337. d.decode(v)
  1338. }
  1339. func (d *Decoder) decode(iv interface{}) {
  1340. // if ics, ok := iv.(Selfer); ok {
  1341. // ics.CodecDecodeSelf(d)
  1342. // return
  1343. // }
  1344. if d.d.TryDecodeAsNil() {
  1345. switch v := iv.(type) {
  1346. case nil:
  1347. case *string:
  1348. *v = ""
  1349. case *bool:
  1350. *v = false
  1351. case *int:
  1352. *v = 0
  1353. case *int8:
  1354. *v = 0
  1355. case *int16:
  1356. *v = 0
  1357. case *int32:
  1358. *v = 0
  1359. case *int64:
  1360. *v = 0
  1361. case *uint:
  1362. *v = 0
  1363. case *uint8:
  1364. *v = 0
  1365. case *uint16:
  1366. *v = 0
  1367. case *uint32:
  1368. *v = 0
  1369. case *uint64:
  1370. *v = 0
  1371. case *float32:
  1372. *v = 0
  1373. case *float64:
  1374. *v = 0
  1375. case *[]uint8:
  1376. *v = nil
  1377. case reflect.Value:
  1378. if v.Kind() != reflect.Ptr || v.IsNil() {
  1379. d.errNotValidPtrValue(v)
  1380. }
  1381. // d.chkPtrValue(v)
  1382. v = v.Elem()
  1383. if v.IsValid() {
  1384. v.Set(reflect.Zero(v.Type()))
  1385. }
  1386. default:
  1387. rv := reflect.ValueOf(iv)
  1388. if rv.Kind() != reflect.Ptr || rv.IsNil() {
  1389. d.errNotValidPtrValue(rv)
  1390. }
  1391. // d.chkPtrValue(rv)
  1392. rv = rv.Elem()
  1393. if rv.IsValid() {
  1394. rv.Set(reflect.Zero(rv.Type()))
  1395. }
  1396. }
  1397. return
  1398. }
  1399. switch v := iv.(type) {
  1400. case nil:
  1401. d.error(cannotDecodeIntoNilErr)
  1402. return
  1403. case Selfer:
  1404. v.CodecDecodeSelf(d)
  1405. case reflect.Value:
  1406. if v.Kind() != reflect.Ptr || v.IsNil() {
  1407. d.errNotValidPtrValue(v)
  1408. }
  1409. // d.chkPtrValue(v)
  1410. d.decodeValueNotNil(v.Elem(), nil)
  1411. case *string:
  1412. *v = d.d.DecodeString()
  1413. case *bool:
  1414. *v = d.d.DecodeBool()
  1415. case *int:
  1416. *v = int(d.d.DecodeInt(intBitsize))
  1417. case *int8:
  1418. *v = int8(d.d.DecodeInt(8))
  1419. case *int16:
  1420. *v = int16(d.d.DecodeInt(16))
  1421. case *int32:
  1422. *v = int32(d.d.DecodeInt(32))
  1423. case *int64:
  1424. *v = d.d.DecodeInt(64)
  1425. case *uint:
  1426. *v = uint(d.d.DecodeUint(uintBitsize))
  1427. case *uint8:
  1428. *v = uint8(d.d.DecodeUint(8))
  1429. case *uint16:
  1430. *v = uint16(d.d.DecodeUint(16))
  1431. case *uint32:
  1432. *v = uint32(d.d.DecodeUint(32))
  1433. case *uint64:
  1434. *v = d.d.DecodeUint(64)
  1435. case *float32:
  1436. *v = float32(d.d.DecodeFloat(true))
  1437. case *float64:
  1438. *v = d.d.DecodeFloat(false)
  1439. case *[]uint8:
  1440. *v = d.d.DecodeBytes(*v, false, false)
  1441. case *interface{}:
  1442. d.decodeValueNotNil(reflect.ValueOf(iv).Elem(), nil)
  1443. default:
  1444. if !fastpathDecodeTypeSwitch(iv, d) {
  1445. d.decodeI(iv, true, false, false, false)
  1446. }
  1447. }
  1448. }
  1449. func (d *Decoder) preDecodeValue(rv reflect.Value, tryNil bool) (rv2 reflect.Value, proceed bool) {
  1450. if tryNil && d.d.TryDecodeAsNil() {
  1451. // No need to check if a ptr, recursively, to determine
  1452. // whether to set value to nil.
  1453. // Just always set value to its zero type.
  1454. if rv.IsValid() { // rv.CanSet() // always settable, except it's invalid
  1455. rv.Set(reflect.Zero(rv.Type()))
  1456. }
  1457. return
  1458. }
  1459. // If stream is not containing a nil value, then we can deref to the base
  1460. // non-pointer value, and decode into that.
  1461. for rv.Kind() == reflect.Ptr {
  1462. if rv.IsNil() {
  1463. rv.Set(reflect.New(rv.Type().Elem()))
  1464. }
  1465. rv = rv.Elem()
  1466. }
  1467. return rv, true
  1468. }
  1469. func (d *Decoder) decodeI(iv interface{}, checkPtr, tryNil, checkFastpath, checkCodecSelfer bool) {
  1470. rv := reflect.ValueOf(iv)
  1471. if checkPtr {
  1472. if rv.Kind() != reflect.Ptr || rv.IsNil() {
  1473. d.errNotValidPtrValue(rv)
  1474. }
  1475. // d.chkPtrValue(rv)
  1476. }
  1477. rv, proceed := d.preDecodeValue(rv, tryNil)
  1478. if proceed {
  1479. fn := d.getDecFn(rv.Type(), checkFastpath, checkCodecSelfer)
  1480. fn.f(&fn.i, rv)
  1481. }
  1482. }
  1483. func (d *Decoder) decodeValue(rv reflect.Value, fn *decFn) {
  1484. if rv, proceed := d.preDecodeValue(rv, true); proceed {
  1485. if fn == nil {
  1486. fn = d.getDecFn(rv.Type(), true, true)
  1487. }
  1488. fn.f(&fn.i, rv)
  1489. }
  1490. }
  1491. func (d *Decoder) decodeValueNotNil(rv reflect.Value, fn *decFn) {
  1492. if rv, proceed := d.preDecodeValue(rv, false); proceed {
  1493. if fn == nil {
  1494. fn = d.getDecFn(rv.Type(), true, true)
  1495. }
  1496. fn.f(&fn.i, rv)
  1497. }
  1498. }
  1499. func (d *Decoder) getDecFn(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *decFn) {
  1500. rtid := reflect.ValueOf(rt).Pointer()
  1501. // retrieve or register a focus'ed function for this type
  1502. // to eliminate need to do the retrieval multiple times
  1503. // if d.f == nil && d.s == nil { debugf("---->Creating new dec f map for type: %v\n", rt) }
  1504. var ok bool
  1505. if useMapForCodecCache {
  1506. fn, ok = d.f[rtid]
  1507. } else {
  1508. for i := range d.s {
  1509. v := &(d.s[i])
  1510. if v.rtid == rtid {
  1511. fn, ok = &(v.fn), true
  1512. break
  1513. }
  1514. }
  1515. }
  1516. if ok {
  1517. return
  1518. }
  1519. if useMapForCodecCache {
  1520. if d.f == nil {
  1521. d.f = make(map[uintptr]*decFn, initCollectionCap)
  1522. }
  1523. fn = new(decFn)
  1524. d.f[rtid] = fn
  1525. } else {
  1526. if d.s == nil {
  1527. d.s = make([]decRtidFn, 0, initCollectionCap)
  1528. }
  1529. d.s = append(d.s, decRtidFn{rtid: rtid})
  1530. fn = &(d.s[len(d.s)-1]).fn
  1531. }
  1532. // debugf("\tCreating new dec fn for type: %v\n", rt)
  1533. ti := d.h.getTypeInfo(rtid, rt)
  1534. fi := &(fn.i)
  1535. fi.d = d
  1536. fi.ti = ti
  1537. // An extension can be registered for any type, regardless of the Kind
  1538. // (e.g. type BitSet int64, type MyStruct { / * unexported fields * / }, type X []int, etc.
  1539. //
  1540. // We can't check if it's an extension byte here first, because the user may have
  1541. // registered a pointer or non-pointer type, meaning we may have to recurse first
  1542. // before matching a mapped type, even though the extension byte is already detected.
  1543. //
  1544. // NOTE: if decoding into a nil interface{}, we return a non-nil
  1545. // value except even if the container registers a length of 0.
  1546. if checkCodecSelfer && ti.cs {
  1547. fn.f = (*decFnInfo).selferUnmarshal
  1548. } else if rtid == rawExtTypId {
  1549. fn.f = (*decFnInfo).rawExt
  1550. } else if d.d.IsBuiltinType(rtid) {
  1551. fn.f = (*decFnInfo).builtin
  1552. } else if xfFn := d.h.getExt(rtid); xfFn != nil {
  1553. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  1554. fn.f = (*decFnInfo).ext
  1555. } else if supportMarshalInterfaces && d.be && ti.bunm {
  1556. fn.f = (*decFnInfo).binaryUnmarshal
  1557. } else if supportMarshalInterfaces && !d.be && d.js && ti.junm {
  1558. //If JSON, we should check JSONUnmarshal before textUnmarshal
  1559. fn.f = (*decFnInfo).jsonUnmarshal
  1560. } else if supportMarshalInterfaces && !d.be && ti.tunm {
  1561. fn.f = (*decFnInfo).textUnmarshal
  1562. } else {
  1563. rk := rt.Kind()
  1564. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  1565. if rt.PkgPath() == "" {
  1566. if idx := fastpathAV.index(rtid); idx != -1 {
  1567. fn.f = fastpathAV[idx].decfn
  1568. }
  1569. } else {
  1570. // use mapping for underlying type if there
  1571. ok = false
  1572. var rtu reflect.Type
  1573. if rk == reflect.Map {
  1574. rtu = reflect.MapOf(rt.Key(), rt.Elem())
  1575. } else {
  1576. rtu = reflect.SliceOf(rt.Elem())
  1577. }
  1578. rtuid := reflect.ValueOf(rtu).Pointer()
  1579. if idx := fastpathAV.index(rtuid); idx != -1 {
  1580. xfnf := fastpathAV[idx].decfn
  1581. xrt := fastpathAV[idx].rt
  1582. fn.f = func(xf *decFnInfo, xrv reflect.Value) {
  1583. // xfnf(xf, xrv.Convert(xrt))
  1584. xfnf(xf, xrv.Addr().Convert(reflect.PtrTo(xrt)).Elem())
  1585. }
  1586. }
  1587. }
  1588. }
  1589. if fn.f == nil {
  1590. switch rk {
  1591. case reflect.String:
  1592. fn.f = (*decFnInfo).kString
  1593. case reflect.Bool:
  1594. fn.f = (*decFnInfo).kBool
  1595. case reflect.Int:
  1596. fn.f = (*decFnInfo).kInt
  1597. case reflect.Int64:
  1598. fn.f = (*decFnInfo).kInt64
  1599. case reflect.Int32:
  1600. fn.f = (*decFnInfo).kInt32
  1601. case reflect.Int8:
  1602. fn.f = (*decFnInfo).kInt8
  1603. case reflect.Int16:
  1604. fn.f = (*decFnInfo).kInt16
  1605. case reflect.Float32:
  1606. fn.f = (*decFnInfo).kFloat32
  1607. case reflect.Float64:
  1608. fn.f = (*decFnInfo).kFloat64
  1609. case reflect.Uint8:
  1610. fn.f = (*decFnInfo).kUint8
  1611. case reflect.Uint64:
  1612. fn.f = (*decFnInfo).kUint64
  1613. case reflect.Uint:
  1614. fn.f = (*decFnInfo).kUint
  1615. case reflect.Uint32:
  1616. fn.f = (*decFnInfo).kUint32
  1617. case reflect.Uint16:
  1618. fn.f = (*decFnInfo).kUint16
  1619. // case reflect.Ptr:
  1620. // fn.f = (*decFnInfo).kPtr
  1621. case reflect.Uintptr:
  1622. fn.f = (*decFnInfo).kUintptr
  1623. case reflect.Interface:
  1624. fn.f = (*decFnInfo).kInterface
  1625. case reflect.Struct:
  1626. fn.f = (*decFnInfo).kStruct
  1627. case reflect.Chan:
  1628. fi.seq = seqTypeChan
  1629. fn.f = (*decFnInfo).kSlice
  1630. case reflect.Slice:
  1631. fi.seq = seqTypeSlice
  1632. fn.f = (*decFnInfo).kSlice
  1633. case reflect.Array:
  1634. fi.seq = seqTypeArray
  1635. fn.f = (*decFnInfo).kArray
  1636. case reflect.Map:
  1637. fn.f = (*decFnInfo).kMap
  1638. default:
  1639. fn.f = (*decFnInfo).kErr
  1640. }
  1641. }
  1642. }
  1643. return
  1644. }
  1645. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  1646. if d.h.ErrorIfNoField {
  1647. if index >= 0 {
  1648. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  1649. return
  1650. } else if rvkencname != "" {
  1651. d.errorf("no matching struct field found when decoding stream map with key %s", rvkencname)
  1652. return
  1653. }
  1654. }
  1655. d.swallow()
  1656. }
  1657. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  1658. if d.h.ErrorIfNoArrayExpand {
  1659. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  1660. }
  1661. }
  1662. func (d *Decoder) chkPtrValue(rv reflect.Value) {
  1663. // We can only decode into a non-nil pointer
  1664. if rv.Kind() == reflect.Ptr && !rv.IsNil() {
  1665. return
  1666. }
  1667. d.errNotValidPtrValue(rv)
  1668. }
  1669. func (d *Decoder) errNotValidPtrValue(rv reflect.Value) {
  1670. if !rv.IsValid() {
  1671. d.error(cannotDecodeIntoNilErr)
  1672. return
  1673. }
  1674. if !rv.CanInterface() {
  1675. d.errorf("cannot decode into a value without an interface: %v", rv)
  1676. return
  1677. }
  1678. rvi := rv.Interface()
  1679. d.errorf("cannot decode into non-pointer or nil pointer. Got: %v, %T, %v", rv.Kind(), rvi, rvi)
  1680. }
  1681. func (d *Decoder) error(err error) {
  1682. panic(err)
  1683. }
  1684. func (d *Decoder) errorf(format string, params ...interface{}) {
  1685. params2 := make([]interface{}, len(params)+1)
  1686. params2[0] = d.r.numread()
  1687. copy(params2[1:], params)
  1688. err := fmt.Errorf("[pos %d]: "+format, params2...)
  1689. panic(err)
  1690. }
  1691. func (d *Decoder) string(v []byte) (s string) {
  1692. if d.is != nil {
  1693. s, ok := d.is[string(v)] // no allocation here.
  1694. if !ok {
  1695. s = string(v)
  1696. d.is[s] = s
  1697. }
  1698. return s
  1699. }
  1700. return string(v) // don't return stringView, as we need a real string here.
  1701. }
  1702. func (d *Decoder) intern(s string) {
  1703. if d.is != nil {
  1704. d.is[s] = s
  1705. }
  1706. }
  1707. func (d *Decoder) nextValueBytes() []byte {
  1708. d.d.uncacheRead()
  1709. d.r.track()
  1710. d.swallow()
  1711. return d.r.stopTrack()
  1712. }
  1713. // --------------------------------------------------
  1714. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  1715. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  1716. type decSliceHelper struct {
  1717. d *Decoder
  1718. // ct valueType
  1719. array bool
  1720. }
  1721. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  1722. dd := d.d
  1723. ctyp := dd.ContainerType()
  1724. if ctyp == valueTypeArray {
  1725. x.array = true
  1726. clen = dd.ReadArrayStart()
  1727. } else if ctyp == valueTypeMap {
  1728. clen = dd.ReadMapStart() * 2
  1729. } else {
  1730. d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp)
  1731. }
  1732. // x.ct = ctyp
  1733. x.d = d
  1734. return
  1735. }
  1736. func (x decSliceHelper) End() {
  1737. cr := x.d.cr
  1738. if cr == nil {
  1739. return
  1740. }
  1741. if x.array {
  1742. cr.sendContainerState(containerArrayEnd)
  1743. } else {
  1744. cr.sendContainerState(containerMapEnd)
  1745. }
  1746. }
  1747. func (x decSliceHelper) ElemContainerState(index int) {
  1748. cr := x.d.cr
  1749. if cr == nil {
  1750. return
  1751. }
  1752. if x.array {
  1753. cr.sendContainerState(containerArrayElem)
  1754. } else {
  1755. if index%2 == 0 {
  1756. cr.sendContainerState(containerMapKey)
  1757. } else {
  1758. cr.sendContainerState(containerMapValue)
  1759. }
  1760. }
  1761. }
  1762. func decByteSlice(r decReader, clen int, bs []byte) (bsOut []byte) {
  1763. if clen == 0 {
  1764. return zeroByteSlice
  1765. }
  1766. if len(bs) == clen {
  1767. bsOut = bs
  1768. } else if cap(bs) >= clen {
  1769. bsOut = bs[:clen]
  1770. } else {
  1771. bsOut = make([]byte, clen)
  1772. }
  1773. r.readb(bsOut)
  1774. return
  1775. }
  1776. func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
  1777. if xlen := len(in); xlen > 0 {
  1778. if isBytesReader || xlen <= scratchByteArrayLen {
  1779. if cap(dest) >= xlen {
  1780. out = dest[:xlen]
  1781. } else {
  1782. out = make([]byte, xlen)
  1783. }
  1784. copy(out, in)
  1785. return
  1786. }
  1787. }
  1788. return in
  1789. }
  1790. // decInferLen will infer a sensible length, given the following:
  1791. // - clen: length wanted.
  1792. // - maxlen: max length to be returned.
  1793. // if <= 0, it is unset, and we infer it based on the unit size
  1794. // - unit: number of bytes for each element of the collection
  1795. func decInferLen(clen, maxlen, unit int) (rvlen int, truncated bool) {
  1796. // handle when maxlen is not set i.e. <= 0
  1797. if clen <= 0 {
  1798. return
  1799. }
  1800. if maxlen <= 0 {
  1801. // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
  1802. // maxlen = 256 * 1024 / unit
  1803. // if maxlen < (4 * 1024) {
  1804. // maxlen = 4 * 1024
  1805. // }
  1806. if unit < (256 / 4) {
  1807. maxlen = 256 * 1024 / unit
  1808. } else {
  1809. maxlen = 4 * 1024
  1810. }
  1811. }
  1812. if clen > maxlen {
  1813. rvlen = maxlen
  1814. truncated = true
  1815. } else {
  1816. rvlen = clen
  1817. }
  1818. return
  1819. // if clen <= 0 {
  1820. // rvlen = 0
  1821. // } else if maxlen > 0 && clen > maxlen {
  1822. // rvlen = maxlen
  1823. // truncated = true
  1824. // } else {
  1825. // rvlen = clen
  1826. // }
  1827. // return
  1828. }
  1829. // // implement overall decReader wrapping both, for possible use inline:
  1830. // type decReaderT struct {
  1831. // bytes bool
  1832. // rb *bytesDecReader
  1833. // ri *ioDecReader
  1834. // }
  1835. //
  1836. // // implement *Decoder as a decReader.
  1837. // // Using decReaderT (defined just above) caused performance degradation
  1838. // // possibly because of constant copying the value,
  1839. // // and some value->interface conversion causing allocation.
  1840. // func (d *Decoder) unreadn1() {
  1841. // if d.bytes {
  1842. // d.rb.unreadn1()
  1843. // } else {
  1844. // d.ri.unreadn1()
  1845. // }
  1846. // }
  1847. // ... for other methods of decReader.
  1848. // Testing showed that performance improvement was negligible.