decode.go 61 KB

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