decode.go 61 KB

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