decode.go 55 KB

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