decode.go 50 KB

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