decode.go 59 KB

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