decode.go 51 KB

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