decode.go 43 KB

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