decode.go 62 KB

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