decode.go 60 KB

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