decode.go 59 KB

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