decode.go 53 KB

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