decode.go 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  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 !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
  1119. if rv.CanSet() {
  1120. rv.SetBytes(bs2)
  1121. } else if len(rvbs) > 0 && len(bs2) > 0 {
  1122. copy(rvbs, bs2)
  1123. }
  1124. }
  1125. }
  1126. return
  1127. }
  1128. // array := f.seq == seqTypeChan
  1129. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map)
  1130. // an array can never return a nil slice. so no need to check f.array here.
  1131. if containerLenS == 0 {
  1132. if rv.CanSet() {
  1133. if f.seq == seqTypeSlice {
  1134. if rv.IsNil() {
  1135. rv.Set(reflect.MakeSlice(ti.rt, 0, 0))
  1136. } else {
  1137. rv.SetLen(0)
  1138. }
  1139. } else if f.seq == seqTypeChan {
  1140. if rv.IsNil() {
  1141. rv.Set(reflect.MakeChan(ti.rt, 0))
  1142. }
  1143. }
  1144. }
  1145. slh.End()
  1146. return
  1147. }
  1148. rtelem0Size := int(rtelem0.Size())
  1149. rtElem0Kind := rtelem0.Kind()
  1150. rtelem0Mut := !isImmutableKind(rtElem0Kind)
  1151. rtelem := rtelem0
  1152. rtelemkind := rtelem.Kind()
  1153. for rtelemkind == reflect.Ptr {
  1154. rtelem = rtelem.Elem()
  1155. rtelemkind = rtelem.Kind()
  1156. }
  1157. var fn *codecFn
  1158. var rvCanset = rv.CanSet()
  1159. var rvChanged bool
  1160. var rv0 = rv
  1161. var rv9 reflect.Value
  1162. rvlen := rv.Len()
  1163. rvcap := rv.Cap()
  1164. hasLen := containerLenS > 0
  1165. if hasLen && f.seq == seqTypeSlice {
  1166. if containerLenS > rvcap {
  1167. oldRvlenGtZero := rvlen > 0
  1168. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(rtelem0.Size()))
  1169. if rvlen <= rvcap {
  1170. if rvCanset {
  1171. rv.SetLen(rvlen)
  1172. }
  1173. } else if rvCanset {
  1174. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  1175. rvcap = rvlen
  1176. rvChanged = true
  1177. } else {
  1178. d.errorf("cannot decode into non-settable slice")
  1179. }
  1180. if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) {
  1181. reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
  1182. }
  1183. } else if containerLenS != rvlen {
  1184. rvlen = containerLenS
  1185. if rvCanset {
  1186. rv.SetLen(rvlen)
  1187. }
  1188. // else {
  1189. // rv = rv.Slice(0, rvlen)
  1190. // rvChanged = true
  1191. // d.errorf("cannot decode into non-settable slice")
  1192. // }
  1193. }
  1194. }
  1195. // consider creating new element once, and just decoding into it.
  1196. var rtelem0Zero reflect.Value
  1197. var rtelem0ZeroValid bool
  1198. var decodeAsNil bool
  1199. var j int
  1200. for ; (hasLen && j < containerLenS) || !(hasLen || dd.CheckBreak()); j++ {
  1201. if j == 0 && (f.seq == seqTypeSlice || f.seq == seqTypeChan) && rv.IsNil() {
  1202. if hasLen {
  1203. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, rtelem0Size)
  1204. } else {
  1205. rvlen = 8
  1206. }
  1207. if rvCanset {
  1208. if f.seq == seqTypeSlice {
  1209. rv = reflect.MakeSlice(ti.rt, rvlen, rvlen)
  1210. rvChanged = true
  1211. } else { // chan
  1212. rv = reflect.MakeChan(ti.rt, rvlen)
  1213. rvChanged = true
  1214. }
  1215. } else {
  1216. d.errorf("cannot decode into non-settable slice")
  1217. }
  1218. }
  1219. slh.ElemContainerState(j)
  1220. decodeAsNil = dd.TryDecodeAsNil()
  1221. if f.seq == seqTypeChan {
  1222. if decodeAsNil {
  1223. rv.Send(reflect.Zero(rtelem0))
  1224. continue
  1225. }
  1226. if rtelem0Mut || !rv9.IsValid() { // || (rtElem0Kind == reflect.Ptr && rv9.IsNil()) {
  1227. rv9 = reflect.New(rtelem0).Elem()
  1228. }
  1229. if fn == nil {
  1230. fn = d.cf.get(rtelem, true, true)
  1231. }
  1232. d.decodeValue(rv9, fn, true)
  1233. rv.Send(rv9)
  1234. } else {
  1235. // if indefinite, etc, then expand the slice if necessary
  1236. var decodeIntoBlank bool
  1237. if j >= rvlen {
  1238. if f.seq == seqTypeArray {
  1239. d.arrayCannotExpand(rvlen, j+1)
  1240. decodeIntoBlank = true
  1241. } else { // if f.seq == seqTypeSlice
  1242. // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // uses append logic, plus varargs
  1243. var rvcap2 int
  1244. rv9, rvcap2, rvChanged = d.expandSliceRV(rv, ti.rt, rvCanset, rtelem0Size, 1, rvlen, rvcap)
  1245. rvlen++
  1246. if rvChanged {
  1247. rv = rv9
  1248. rvcap = rvcap2
  1249. }
  1250. }
  1251. }
  1252. if decodeIntoBlank {
  1253. if !decodeAsNil {
  1254. d.swallow()
  1255. }
  1256. } else {
  1257. rv9 = rv.Index(j)
  1258. if d.h.SliceElementReset || decodeAsNil {
  1259. if !rtelem0ZeroValid {
  1260. rtelem0ZeroValid = true
  1261. rtelem0Zero = reflect.Zero(rtelem0)
  1262. }
  1263. rv9.Set(rtelem0Zero)
  1264. }
  1265. if decodeAsNil {
  1266. continue
  1267. }
  1268. if fn == nil {
  1269. fn = d.cf.get(rtelem, true, true)
  1270. }
  1271. d.decodeValue(rv9, fn, true)
  1272. }
  1273. }
  1274. }
  1275. if f.seq == seqTypeSlice {
  1276. if j < rvlen {
  1277. if rv.CanSet() {
  1278. rv.SetLen(j)
  1279. } else if rvCanset {
  1280. rv = rv.Slice(0, j)
  1281. rvChanged = true
  1282. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1283. rvlen = j
  1284. } else if j == 0 && rv.IsNil() {
  1285. if rvCanset {
  1286. rv = reflect.MakeSlice(ti.rt, 0, 0)
  1287. rvChanged = true
  1288. } // else { d.errorf("kSlice: cannot change non-settable slice") }
  1289. }
  1290. }
  1291. slh.End()
  1292. if rvChanged { // infers rvCanset=true, so it can be reset
  1293. rv0.Set(rv)
  1294. }
  1295. }
  1296. // func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
  1297. // // d.decodeValueFn(rv.Slice(0, rv.Len()))
  1298. // f.kSlice(rv.Slice(0, rv.Len()))
  1299. // }
  1300. func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
  1301. dd := d.d
  1302. containerLen := dd.ReadMapStart()
  1303. elemsep := d.hh.hasElemSeparators()
  1304. ti := f.ti
  1305. if rv.IsNil() {
  1306. rv.Set(makeMapReflect(ti.rt, containerLen))
  1307. }
  1308. if containerLen == 0 {
  1309. dd.ReadMapEnd()
  1310. return
  1311. }
  1312. ktype, vtype := ti.rt.Key(), ti.rt.Elem()
  1313. ktypeId := rt2id(ktype)
  1314. vtypeKind := vtype.Kind()
  1315. var keyFn, valFn *codecFn
  1316. var ktypeLo, vtypeLo reflect.Type
  1317. for ktypeLo = ktype; ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
  1318. }
  1319. for vtypeLo = vtype; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
  1320. }
  1321. var mapGet, mapSet bool
  1322. rvvImmut := isImmutableKind(vtypeKind)
  1323. if !d.h.MapValueReset {
  1324. // if pointer, mapGet = true
  1325. // if interface, mapGet = true if !DecodeNakedAlways (else false)
  1326. // if builtin, mapGet = false
  1327. // else mapGet = true
  1328. if vtypeKind == reflect.Ptr {
  1329. mapGet = true
  1330. } else if vtypeKind == reflect.Interface {
  1331. if !d.h.InterfaceReset {
  1332. mapGet = true
  1333. }
  1334. } else if !rvvImmut {
  1335. mapGet = true
  1336. }
  1337. }
  1338. var rvk, rvkp, rvv, rvz reflect.Value
  1339. rvkMut := !isImmutableKind(ktype.Kind()) // if ktype is immutable, then re-use the same rvk.
  1340. ktypeIsString := ktypeId == stringTypId
  1341. ktypeIsIntf := ktypeId == intfTypId
  1342. hasLen := containerLen > 0
  1343. var kstrbs []byte
  1344. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1345. if rvkMut || !rvkp.IsValid() {
  1346. rvkp = reflect.New(ktype)
  1347. rvk = rvkp.Elem()
  1348. }
  1349. if elemsep {
  1350. dd.ReadMapElemKey()
  1351. }
  1352. if false && dd.TryDecodeAsNil() { // nil cannot be a map key, so disregard this block
  1353. // Previously, if a nil key, we just ignored the mapped value and continued.
  1354. // However, that makes the result of encoding and then decoding map[intf]intf{nil:nil}
  1355. // to be an empty map.
  1356. // Instead, we treat a nil key as the zero value of the type.
  1357. rvk.Set(reflect.Zero(ktype))
  1358. } else if ktypeIsString {
  1359. kstrbs = dd.DecodeStringAsBytes()
  1360. rvk.SetString(stringView(kstrbs))
  1361. // NOTE: if doing an insert, you MUST use a real string (not stringview)
  1362. } else {
  1363. if keyFn == nil {
  1364. keyFn = d.cf.get(ktypeLo, true, true)
  1365. }
  1366. d.decodeValue(rvk, keyFn, true)
  1367. }
  1368. // special case if a byte array.
  1369. if ktypeIsIntf {
  1370. if rvk2 := rvk.Elem(); rvk2.IsValid() {
  1371. if rvk2.Type() == uint8SliceTyp {
  1372. rvk = reflect.ValueOf(d.string(rvk2.Bytes()))
  1373. } else {
  1374. rvk = rvk2
  1375. }
  1376. }
  1377. }
  1378. if elemsep {
  1379. dd.ReadMapElemValue()
  1380. }
  1381. // Brittle, but OK per TryDecodeAsNil() contract.
  1382. // i.e. TryDecodeAsNil never shares slices with other decDriver procedures
  1383. if dd.TryDecodeAsNil() {
  1384. if ktypeIsString {
  1385. rvk.SetString(d.string(kstrbs))
  1386. }
  1387. if d.h.DeleteOnNilMapValue {
  1388. rv.SetMapIndex(rvk, reflect.Value{})
  1389. } else {
  1390. rv.SetMapIndex(rvk, reflect.Zero(vtype))
  1391. }
  1392. continue
  1393. }
  1394. mapSet = true // set to false if u do a get, and its a non-nil pointer
  1395. if mapGet {
  1396. // mapGet true only in case where kind=Ptr|Interface or kind is otherwise mutable.
  1397. rvv = rv.MapIndex(rvk)
  1398. if !rvv.IsValid() {
  1399. rvv = reflect.New(vtype).Elem()
  1400. } else if vtypeKind == reflect.Ptr {
  1401. if rvv.IsNil() {
  1402. rvv = reflect.New(vtype).Elem()
  1403. } else {
  1404. mapSet = false
  1405. }
  1406. } else if vtypeKind == reflect.Interface {
  1407. // not addressable, and thus not settable.
  1408. // e MUST create a settable/addressable variant
  1409. rvv2 := reflect.New(rvv.Type()).Elem()
  1410. if !rvv.IsNil() {
  1411. rvv2.Set(rvv)
  1412. }
  1413. rvv = rvv2
  1414. }
  1415. // else it is ~mutable, and we can just decode into it directly
  1416. } else if rvvImmut {
  1417. if !rvz.IsValid() {
  1418. rvz = reflect.New(vtype).Elem()
  1419. }
  1420. rvv = rvz
  1421. } else {
  1422. rvv = reflect.New(vtype).Elem()
  1423. }
  1424. // We MUST be done with the stringview of the key, before decoding the value
  1425. // so that we don't bastardize the reused byte array.
  1426. if mapSet && ktypeIsString {
  1427. rvk.SetString(d.string(kstrbs))
  1428. }
  1429. if valFn == nil {
  1430. valFn = d.cf.get(vtypeLo, true, true)
  1431. }
  1432. d.decodeValue(rvv, valFn, true)
  1433. // d.decodeValueFn(rvv, valFn)
  1434. if mapSet {
  1435. rv.SetMapIndex(rvk, rvv)
  1436. }
  1437. // if ktypeIsString {
  1438. // // keepAlive4StringView(kstrbs) // not needed, as reference is outside loop
  1439. // }
  1440. }
  1441. dd.ReadMapEnd()
  1442. }
  1443. // decNaked is used to keep track of the primitives decoded.
  1444. // Without it, we would have to decode each primitive and wrap it
  1445. // in an interface{}, causing an allocation.
  1446. // In this model, the primitives are decoded in a "pseudo-atomic" fashion,
  1447. // so we can rest assured that no other decoding happens while these
  1448. // primitives are being decoded.
  1449. //
  1450. // maps and arrays are not handled by this mechanism.
  1451. // However, RawExt is, and we accommodate for extensions that decode
  1452. // RawExt from DecodeNaked, but need to decode the value subsequently.
  1453. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat.
  1454. //
  1455. // However, decNaked also keeps some arrays of default maps and slices
  1456. // used in DecodeNaked. This way, we can get a pointer to it
  1457. // without causing a new heap allocation.
  1458. //
  1459. // kInterfaceNaked will ensure that there is no allocation for the common
  1460. // uses.
  1461. type decNaked struct {
  1462. // r RawExt // used for RawExt, uint, []byte.
  1463. u uint64
  1464. i int64
  1465. f float64
  1466. l []byte
  1467. s string
  1468. t time.Time
  1469. b bool
  1470. inited bool
  1471. v valueType
  1472. li, lm, ln, ls int8
  1473. // array/stacks for reducing allocation
  1474. // keep arrays at the bottom? Chance is that they are not used much.
  1475. ia [arrayCacheLen]interface{}
  1476. ma [arrayCacheLen]map[interface{}]interface{}
  1477. na [arrayCacheLen]map[string]interface{}
  1478. sa [arrayCacheLen][]interface{}
  1479. // ra [2]RawExt
  1480. rr [5 * arrayCacheLen]reflect.Value
  1481. }
  1482. const (
  1483. decNakedUintIdx = iota
  1484. decNakedIntIdx
  1485. decNakedFloatIdx
  1486. decNakedBytesIdx
  1487. decNakedStringIdx
  1488. decNakedTimeIdx
  1489. decNakedBoolIdx
  1490. )
  1491. const (
  1492. _ = iota // maps to the scalars above
  1493. decNakedIntfIdx
  1494. decNakedMapIntfIntfIdx
  1495. decNakedMapStrIntfIdx
  1496. decNakedSliceIntfIdx
  1497. )
  1498. func (n *decNaked) init() {
  1499. if n.inited {
  1500. return
  1501. }
  1502. // n.ms = n.ma[:0]
  1503. // n.is = n.ia[:0]
  1504. // n.ns = n.na[:0]
  1505. // n.ss = n.sa[:0]
  1506. n.rr[decNakedUintIdx] = reflect.ValueOf(&n.u).Elem()
  1507. n.rr[decNakedIntIdx] = reflect.ValueOf(&n.i).Elem()
  1508. n.rr[decNakedFloatIdx] = reflect.ValueOf(&n.f).Elem()
  1509. n.rr[decNakedBytesIdx] = reflect.ValueOf(&n.l).Elem()
  1510. n.rr[decNakedStringIdx] = reflect.ValueOf(&n.s).Elem()
  1511. n.rr[decNakedTimeIdx] = reflect.ValueOf(&n.t).Elem()
  1512. n.rr[decNakedBoolIdx] = reflect.ValueOf(&n.b).Elem()
  1513. for i := range [arrayCacheLen]struct{}{} {
  1514. n.rr[decNakedIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.ia[i])).Elem()
  1515. n.rr[decNakedMapIntfIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.ma[i])).Elem()
  1516. n.rr[decNakedMapStrIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.na[i])).Elem()
  1517. n.rr[decNakedSliceIntfIdx*arrayCacheLen+i] = reflect.ValueOf(&(n.sa[i])).Elem()
  1518. }
  1519. n.inited = true
  1520. // n.rr[] = reflect.ValueOf(&n.)
  1521. }
  1522. func (n *decNaked) reset() {
  1523. if n == nil {
  1524. return
  1525. }
  1526. n.li, n.lm, n.ln, n.ls = 0, 0, 0, 0
  1527. }
  1528. type rtid2rv struct {
  1529. rtid uintptr
  1530. rv reflect.Value
  1531. }
  1532. // A Decoder reads and decodes an object from an input stream in the codec format.
  1533. type Decoder struct {
  1534. // hopefully, reduce derefencing cost by laying the decReader inside the Decoder.
  1535. // Try to put things that go together to fit within a cache line (8 words).
  1536. d decDriver
  1537. // NOTE: Decoder shouldn't call it's read methods,
  1538. // as the handler MAY need to do some coordination.
  1539. r decReader
  1540. hh Handle
  1541. h *BasicHandle
  1542. mtr, str bool // whether maptype or slicetype are known types
  1543. be bool // is binary encoding
  1544. bytes bool // is bytes reader
  1545. js bool // is json handle
  1546. // ---- cpu cache line boundary?
  1547. rb bytesDecReader
  1548. ri ioDecReader
  1549. bi bufioDecReader
  1550. // cr containerStateRecv
  1551. n *decNaked
  1552. nsp *sync.Pool
  1553. // ---- cpu cache line boundary?
  1554. is map[string]string // used for interning strings
  1555. // cache the mapTypeId and sliceTypeId for faster comparisons
  1556. mtid uintptr
  1557. stid uintptr
  1558. b [scratchByteArrayLen]byte
  1559. // _ uintptr // for alignment purposes, so next one starts from a cache line
  1560. err error
  1561. // ---- cpu cache line boundary?
  1562. cf codecFner
  1563. // _ [64]byte // force alignment???
  1564. }
  1565. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  1566. //
  1567. // For efficiency, Users are encouraged to pass in a memory buffered reader
  1568. // (eg bufio.Reader, bytes.Buffer).
  1569. func NewDecoder(r io.Reader, h Handle) *Decoder {
  1570. d := newDecoder(h)
  1571. d.Reset(r)
  1572. return d
  1573. }
  1574. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  1575. // from a byte slice with zero copying.
  1576. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  1577. d := newDecoder(h)
  1578. d.ResetBytes(in)
  1579. return d
  1580. }
  1581. var defaultDecNaked decNaked
  1582. func newDecoder(h Handle) *Decoder {
  1583. d := &Decoder{hh: h, h: h.getBasicHandle(), be: h.isBinary()}
  1584. // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
  1585. _, d.js = h.(*JsonHandle)
  1586. if d.h.InternString {
  1587. d.is = make(map[string]string, 32)
  1588. }
  1589. d.d = h.newDecDriver(d)
  1590. // d.cr, _ = d.d.(containerStateRecv)
  1591. return d
  1592. }
  1593. // naked must be called before each call to .DecodeNaked,
  1594. // as they will use it.
  1595. func (d *Decoder) naked() *decNaked {
  1596. if d.n == nil {
  1597. // consider one of:
  1598. // - get from sync.Pool (if GC is frequent, there's no value here)
  1599. // - new alloc (safest. only init'ed if it a naked decode will be done)
  1600. // - field in Decoder (makes the Decoder struct very big)
  1601. // To support using a decoder where a DecodeNaked is not needed,
  1602. // we prefer #1 or #2.
  1603. // d.n = new(decNaked) // &d.nv // new(decNaked) // grab from a sync.Pool
  1604. // d.n.init()
  1605. var v interface{}
  1606. d.nsp, v = pool.decNaked()
  1607. d.n = v.(*decNaked)
  1608. }
  1609. return d.n
  1610. }
  1611. func (d *Decoder) resetCommon() {
  1612. d.n.reset()
  1613. d.d.reset()
  1614. d.cf.reset(d.hh)
  1615. d.err = nil
  1616. // reset all things which were cached from the Handle, but could change
  1617. d.mtid, d.stid = 0, 0
  1618. d.mtr, d.str = false, false
  1619. if d.h.MapType != nil {
  1620. d.mtid = rt2id(d.h.MapType)
  1621. d.mtr = fastpathAV.index(d.mtid) != -1
  1622. }
  1623. if d.h.SliceType != nil {
  1624. d.stid = rt2id(d.h.SliceType)
  1625. d.str = fastpathAV.index(d.stid) != -1
  1626. }
  1627. }
  1628. // Reset the Decoder with a new Reader to decode from,
  1629. // clearing all state from last run(s).
  1630. func (d *Decoder) Reset(r io.Reader) {
  1631. if d.h.ReaderBufferSize > 0 {
  1632. d.bi.buf = make([]byte, 0, d.h.ReaderBufferSize)
  1633. d.bi.reset(r)
  1634. d.r = &d.bi
  1635. } else {
  1636. d.ri.x = &d.b
  1637. // d.s = d.sa[:0]
  1638. d.ri.reset(r)
  1639. d.r = &d.ri
  1640. }
  1641. d.resetCommon()
  1642. }
  1643. // ResetBytes resets the Decoder with a new []byte to decode from,
  1644. // clearing all state from last run(s).
  1645. func (d *Decoder) ResetBytes(in []byte) {
  1646. d.bytes = true
  1647. d.rb.reset(in)
  1648. d.r = &d.rb
  1649. d.resetCommon()
  1650. }
  1651. // Decode decodes the stream from reader and stores the result in the
  1652. // value pointed to by v. v cannot be a nil pointer. v can also be
  1653. // a reflect.Value of a pointer.
  1654. //
  1655. // Note that a pointer to a nil interface is not a nil pointer.
  1656. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  1657. // We will decode and store a value in that nil interface.
  1658. //
  1659. // Sample usages:
  1660. // // Decoding into a non-nil typed value
  1661. // var f float32
  1662. // err = codec.NewDecoder(r, handle).Decode(&f)
  1663. //
  1664. // // Decoding into nil interface
  1665. // var v interface{}
  1666. // dec := codec.NewDecoder(r, handle)
  1667. // err = dec.Decode(&v)
  1668. //
  1669. // When decoding into a nil interface{}, we will decode into an appropriate value based
  1670. // on the contents of the stream:
  1671. // - Numbers are decoded as float64, int64 or uint64.
  1672. // - Other values are decoded appropriately depending on the type:
  1673. // bool, string, []byte, time.Time, etc
  1674. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  1675. // Configurations exist on the Handle to override defaults
  1676. // (e.g. for MapType, SliceType and how to decode raw bytes).
  1677. //
  1678. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  1679. // type of the value. When a value is seen:
  1680. // - If an extension is registered for it, call that extension function
  1681. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  1682. // - Else decode it based on its reflect.Kind
  1683. //
  1684. // There are some special rules when decoding into containers (slice/array/map/struct).
  1685. // Decode will typically use the stream contents to UPDATE the container.
  1686. // - A map can be decoded from a stream map, by updating matching keys.
  1687. // - A slice can be decoded from a stream array,
  1688. // by updating the first n elements, where n is length of the stream.
  1689. // - A slice can be decoded from a stream map, by decoding as if
  1690. // it contains a sequence of key-value pairs.
  1691. // - A struct can be decoded from a stream map, by updating matching fields.
  1692. // - A struct can be decoded from a stream array,
  1693. // by updating fields as they occur in the struct (by index).
  1694. //
  1695. // When decoding a stream map or array with length of 0 into a nil map or slice,
  1696. // we reset the destination map or slice to a zero-length value.
  1697. //
  1698. // However, when decoding a stream nil, we reset the destination container
  1699. // to its "zero" value (e.g. nil for slice/map, etc).
  1700. //
  1701. // Note: we allow nil values in the stream anywhere except for map keys.
  1702. // A nil value in the encoded stream where a map key is expected is treated as an error.
  1703. func (d *Decoder) Decode(v interface{}) (err error) {
  1704. defer panicToErrs2(&d.err, &err)
  1705. d.MustDecode(v)
  1706. return
  1707. }
  1708. // MustDecode is like Decode, but panics if unable to Decode.
  1709. // This provides insight to the code location that triggered the error.
  1710. func (d *Decoder) MustDecode(v interface{}) {
  1711. // TODO: Top-level: ensure that v is a pointer and not nil.
  1712. if d.err != nil {
  1713. panic(d.err)
  1714. }
  1715. if d.d.TryDecodeAsNil() {
  1716. setZero(v)
  1717. } else {
  1718. d.decode(v)
  1719. }
  1720. if d.nsp != nil {
  1721. if d.n != nil {
  1722. d.nsp.Put(d.n)
  1723. d.n = nil
  1724. }
  1725. d.nsp = nil
  1726. }
  1727. d.n = nil
  1728. // xprintf(">>>>>>>> >>>>>>>> num decFns: %v\n", d.cf.sn)
  1729. }
  1730. // // this is not a smart swallow, as it allocates objects and does unnecessary work.
  1731. // func (d *Decoder) swallowViaHammer() {
  1732. // var blank interface{}
  1733. // d.decodeValueNoFn(reflect.ValueOf(&blank).Elem())
  1734. // }
  1735. func (d *Decoder) swallow() {
  1736. // smarter decode that just swallows the content
  1737. dd := d.d
  1738. if dd.TryDecodeAsNil() {
  1739. return
  1740. }
  1741. elemsep := d.hh.hasElemSeparators()
  1742. switch dd.ContainerType() {
  1743. case valueTypeMap:
  1744. containerLen := dd.ReadMapStart()
  1745. hasLen := containerLen >= 0
  1746. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1747. // if clenGtEqualZero {if j >= containerLen {break} } else if dd.CheckBreak() {break}
  1748. if elemsep {
  1749. dd.ReadMapElemKey()
  1750. }
  1751. d.swallow()
  1752. if elemsep {
  1753. dd.ReadMapElemValue()
  1754. }
  1755. d.swallow()
  1756. }
  1757. dd.ReadMapEnd()
  1758. case valueTypeArray:
  1759. containerLen := dd.ReadArrayStart()
  1760. hasLen := containerLen >= 0
  1761. for j := 0; (hasLen && j < containerLen) || !(hasLen || dd.CheckBreak()); j++ {
  1762. if elemsep {
  1763. dd.ReadArrayElem()
  1764. }
  1765. d.swallow()
  1766. }
  1767. dd.ReadArrayEnd()
  1768. case valueTypeBytes:
  1769. dd.DecodeBytes(d.b[:], true)
  1770. case valueTypeString:
  1771. dd.DecodeStringAsBytes()
  1772. default:
  1773. // these are all primitives, which we can get from decodeNaked
  1774. // if RawExt using Value, complete the processing.
  1775. n := d.naked()
  1776. dd.DecodeNaked()
  1777. if n.v == valueTypeExt && n.l == nil {
  1778. if n.li < arrayCacheLen {
  1779. n.ia[n.li] = nil
  1780. n.li++
  1781. d.decode(&n.ia[n.li-1])
  1782. n.ia[n.li-1] = nil
  1783. n.li--
  1784. } else {
  1785. var v2 interface{}
  1786. d.decode(&v2)
  1787. }
  1788. }
  1789. }
  1790. }
  1791. func setZero(iv interface{}) {
  1792. if iv == nil || definitelyNil(iv) {
  1793. return
  1794. }
  1795. var canDecode bool
  1796. switch v := iv.(type) {
  1797. case *string:
  1798. *v = ""
  1799. case *bool:
  1800. *v = false
  1801. case *int:
  1802. *v = 0
  1803. case *int8:
  1804. *v = 0
  1805. case *int16:
  1806. *v = 0
  1807. case *int32:
  1808. *v = 0
  1809. case *int64:
  1810. *v = 0
  1811. case *uint:
  1812. *v = 0
  1813. case *uint8:
  1814. *v = 0
  1815. case *uint16:
  1816. *v = 0
  1817. case *uint32:
  1818. *v = 0
  1819. case *uint64:
  1820. *v = 0
  1821. case *float32:
  1822. *v = 0
  1823. case *float64:
  1824. *v = 0
  1825. case *[]uint8:
  1826. *v = nil
  1827. case *Raw:
  1828. *v = nil
  1829. case reflect.Value:
  1830. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  1831. v.Set(reflect.Zero(v.Type()))
  1832. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  1833. default:
  1834. if !fastpathDecodeSetZeroTypeSwitch(iv) {
  1835. v := reflect.ValueOf(iv)
  1836. if v, canDecode = isDecodeable(v); canDecode && v.CanSet() {
  1837. v.Set(reflect.Zero(v.Type()))
  1838. } // TODO: else drain if chan, clear if map, set all to nil if slice???
  1839. }
  1840. }
  1841. }
  1842. func (d *Decoder) decode(iv interface{}) {
  1843. // check nil and interfaces explicitly,
  1844. // so that type switches just have a run of constant non-interface types.
  1845. if iv == nil {
  1846. d.error(errCannotDecodeIntoNil)
  1847. return
  1848. }
  1849. if v, ok := iv.(Selfer); ok {
  1850. v.CodecDecodeSelf(d)
  1851. return
  1852. }
  1853. switch v := iv.(type) {
  1854. // case nil:
  1855. // case Selfer:
  1856. case reflect.Value:
  1857. v = d.ensureDecodeable(v)
  1858. d.decodeValue(v, nil, true)
  1859. case *string:
  1860. *v = d.d.DecodeString()
  1861. case *bool:
  1862. *v = d.d.DecodeBool()
  1863. case *int:
  1864. *v = int(d.d.DecodeInt(intBitsize))
  1865. case *int8:
  1866. *v = int8(d.d.DecodeInt(8))
  1867. case *int16:
  1868. *v = int16(d.d.DecodeInt(16))
  1869. case *int32:
  1870. *v = int32(d.d.DecodeInt(32))
  1871. case *int64:
  1872. *v = d.d.DecodeInt(64)
  1873. case *uint:
  1874. *v = uint(d.d.DecodeUint(uintBitsize))
  1875. case *uint8:
  1876. *v = uint8(d.d.DecodeUint(8))
  1877. case *uint16:
  1878. *v = uint16(d.d.DecodeUint(16))
  1879. case *uint32:
  1880. *v = uint32(d.d.DecodeUint(32))
  1881. case *uint64:
  1882. *v = d.d.DecodeUint(64)
  1883. case *float32:
  1884. *v = float32(d.d.DecodeFloat(true))
  1885. case *float64:
  1886. *v = d.d.DecodeFloat(false)
  1887. case *[]uint8:
  1888. *v = d.d.DecodeBytes(*v, false)
  1889. case []uint8:
  1890. b := d.d.DecodeBytes(v, false)
  1891. if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) {
  1892. copy(v, b)
  1893. }
  1894. case *time.Time:
  1895. *v = d.d.DecodeTime()
  1896. case *Raw:
  1897. *v = d.rawBytes()
  1898. case *interface{}:
  1899. d.decodeValue(reflect.ValueOf(iv).Elem(), nil, true) // TODO: consider recognize here
  1900. // d.decodeValueNotNil(reflect.ValueOf(iv).Elem())
  1901. default:
  1902. if !fastpathDecodeTypeSwitch(iv, d) {
  1903. v := reflect.ValueOf(iv)
  1904. v = d.ensureDecodeable(v)
  1905. d.decodeValue(v, nil, false)
  1906. // d.decodeValueFallback(v)
  1907. }
  1908. }
  1909. }
  1910. func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn, chkAll bool) {
  1911. // If stream is not containing a nil value, then we can deref to the base
  1912. // non-pointer value, and decode into that.
  1913. var rvp reflect.Value
  1914. var rvpValid bool
  1915. if rv.Kind() == reflect.Ptr {
  1916. rvpValid = true
  1917. for {
  1918. if rv.IsNil() {
  1919. rv.Set(reflect.New(rv.Type().Elem()))
  1920. }
  1921. rvp = rv
  1922. rv = rv.Elem()
  1923. if rv.Kind() != reflect.Ptr {
  1924. break
  1925. }
  1926. }
  1927. }
  1928. if fn == nil {
  1929. // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer
  1930. fn = d.cf.get(rv.Type(), chkAll, true) // chkAll, chkAll)
  1931. }
  1932. if fn.i.addrD {
  1933. if rvpValid {
  1934. fn.fd(d, &fn.i, rvp)
  1935. } else if rv.CanAddr() {
  1936. fn.fd(d, &fn.i, rv.Addr())
  1937. } else if !fn.i.addrF {
  1938. fn.fd(d, &fn.i, rv)
  1939. } else {
  1940. d.errorf("cannot decode into a non-pointer value")
  1941. }
  1942. } else {
  1943. fn.fd(d, &fn.i, rv)
  1944. }
  1945. // return rv
  1946. }
  1947. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  1948. // NOTE: rvkencname may be a stringView, so don't pass it to another function.
  1949. if d.h.ErrorIfNoField {
  1950. if index >= 0 {
  1951. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  1952. return
  1953. } else if rvkencname != "" {
  1954. d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
  1955. return
  1956. }
  1957. }
  1958. d.swallow()
  1959. }
  1960. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  1961. if d.h.ErrorIfNoArrayExpand {
  1962. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  1963. }
  1964. }
  1965. func isDecodeable(rv reflect.Value) (rv2 reflect.Value, canDecode bool) {
  1966. switch rv.Kind() {
  1967. case reflect.Array:
  1968. return rv, true
  1969. case reflect.Ptr:
  1970. if !rv.IsNil() {
  1971. return rv.Elem(), true
  1972. }
  1973. case reflect.Slice, reflect.Chan, reflect.Map:
  1974. if !rv.IsNil() {
  1975. return rv, true
  1976. }
  1977. }
  1978. return
  1979. }
  1980. func (d *Decoder) ensureDecodeable(rv reflect.Value) (rv2 reflect.Value) {
  1981. // decode can take any reflect.Value that is a inherently addressable i.e.
  1982. // - array
  1983. // - non-nil chan (we will SEND to it)
  1984. // - non-nil slice (we will set its elements)
  1985. // - non-nil map (we will put into it)
  1986. // - non-nil pointer (we can "update" it)
  1987. rv2, canDecode := isDecodeable(rv)
  1988. if canDecode {
  1989. return
  1990. }
  1991. if !rv.IsValid() {
  1992. d.error(errCannotDecodeIntoNil)
  1993. return
  1994. }
  1995. if !rv.CanInterface() {
  1996. d.errorf("cannot decode into a value without an interface: %v", rv)
  1997. return
  1998. }
  1999. rvi := rv2i(rv)
  2000. rvk := rv.Kind()
  2001. d.errorf("cannot decode into value of kind: %v, type: %T, %v", rvk, rvi, rvi)
  2002. return
  2003. }
  2004. // func (d *Decoder) chkPtrValue(rv reflect.Value) {
  2005. // // We can only decode into a non-nil pointer
  2006. // if rv.Kind() == reflect.Ptr && !rv.IsNil() {
  2007. // return
  2008. // }
  2009. // d.errNotValidPtrValue(rv)
  2010. // }
  2011. // func (d *Decoder) errNotValidPtrValue(rv reflect.Value) {
  2012. // if !rv.IsValid() {
  2013. // d.error(errCannotDecodeIntoNil)
  2014. // return
  2015. // }
  2016. // if !rv.CanInterface() {
  2017. // d.errorf("cannot decode into a value without an interface: %v", rv)
  2018. // return
  2019. // }
  2020. // rvi := rv2i(rv)
  2021. // d.errorf("cannot decode into non-pointer or nil pointer. Got: %v, %T, %v", rv.Kind(), rvi, rvi)
  2022. // }
  2023. func (d *Decoder) error(err error) {
  2024. panic(err)
  2025. }
  2026. func (d *Decoder) errorvf(format string, params ...interface{}) (err error) {
  2027. params2 := make([]interface{}, len(params)+1)
  2028. params2[0] = d.r.numread()
  2029. copy(params2[1:], params)
  2030. return fmt.Errorf("[pos %d]: "+format, params2...)
  2031. }
  2032. func (d *Decoder) errorf(format string, params ...interface{}) {
  2033. panic(d.errorvf(format, params...))
  2034. }
  2035. // Possibly get an interned version of a string
  2036. //
  2037. // This should mostly be used for map keys, where the key type is string.
  2038. // This is because keys of a map/struct are typically reused across many objects.
  2039. func (d *Decoder) string(v []byte) (s string) {
  2040. if d.is == nil {
  2041. return string(v) // don't return stringView, as we need a real string here.
  2042. }
  2043. s, ok := d.is[string(v)] // no allocation here, per go implementation
  2044. if !ok {
  2045. s = string(v) // new allocation here
  2046. d.is[s] = s
  2047. }
  2048. return s
  2049. }
  2050. // nextValueBytes returns the next value in the stream as a set of bytes.
  2051. func (d *Decoder) nextValueBytes() (bs []byte) {
  2052. d.d.uncacheRead()
  2053. d.r.track()
  2054. d.swallow()
  2055. bs = d.r.stopTrack()
  2056. return
  2057. }
  2058. func (d *Decoder) rawBytes() []byte {
  2059. // ensure that this is not a view into the bytes
  2060. // i.e. make new copy always.
  2061. bs := d.nextValueBytes()
  2062. bs2 := make([]byte, len(bs))
  2063. copy(bs2, bs)
  2064. return bs2
  2065. }
  2066. // --------------------------------------------------
  2067. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  2068. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  2069. type decSliceHelper struct {
  2070. d *Decoder
  2071. // ct valueType
  2072. array bool
  2073. }
  2074. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  2075. dd := d.d
  2076. ctyp := dd.ContainerType()
  2077. if ctyp == valueTypeArray {
  2078. x.array = true
  2079. clen = dd.ReadArrayStart()
  2080. } else if ctyp == valueTypeMap {
  2081. clen = dd.ReadMapStart() * 2
  2082. } else {
  2083. d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp)
  2084. }
  2085. // x.ct = ctyp
  2086. x.d = d
  2087. return
  2088. }
  2089. func (x decSliceHelper) End() {
  2090. if x.array {
  2091. x.d.d.ReadArrayEnd()
  2092. } else {
  2093. x.d.d.ReadMapEnd()
  2094. }
  2095. }
  2096. func (x decSliceHelper) ElemContainerState(index int) {
  2097. if x.array {
  2098. x.d.d.ReadArrayElem()
  2099. } else {
  2100. if index%2 == 0 {
  2101. x.d.d.ReadMapElemKey()
  2102. } else {
  2103. x.d.d.ReadMapElemValue()
  2104. }
  2105. }
  2106. }
  2107. func decByteSlice(r decReader, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2108. if clen == 0 {
  2109. return zeroByteSlice
  2110. }
  2111. if len(bs) == clen {
  2112. bsOut = bs
  2113. r.readb(bsOut)
  2114. } else if cap(bs) >= clen {
  2115. bsOut = bs[:clen]
  2116. r.readb(bsOut)
  2117. } else {
  2118. // bsOut = make([]byte, clen)
  2119. len2 := decInferLen(clen, maxInitLen, 1)
  2120. bsOut = make([]byte, len2)
  2121. r.readb(bsOut)
  2122. for len2 < clen {
  2123. len3 := decInferLen(clen-len2, maxInitLen, 1)
  2124. bs3 := bsOut
  2125. bsOut = make([]byte, len2+len3)
  2126. copy(bsOut, bs3)
  2127. r.readb(bsOut[len2:])
  2128. len2 += len3
  2129. }
  2130. }
  2131. return
  2132. }
  2133. func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
  2134. if xlen := len(in); xlen > 0 {
  2135. if isBytesReader || xlen <= scratchByteArrayLen {
  2136. if cap(dest) >= xlen {
  2137. out = dest[:xlen]
  2138. } else {
  2139. out = make([]byte, xlen)
  2140. }
  2141. copy(out, in)
  2142. return
  2143. }
  2144. }
  2145. return in
  2146. }
  2147. // decInferLen will infer a sensible length, given the following:
  2148. // - clen: length wanted.
  2149. // - maxlen: max length to be returned.
  2150. // if <= 0, it is unset, and we infer it based on the unit size
  2151. // - unit: number of bytes for each element of the collection
  2152. func decInferLen(clen, maxlen, unit int) (rvlen int) {
  2153. // handle when maxlen is not set i.e. <= 0
  2154. if clen <= 0 {
  2155. return
  2156. }
  2157. if unit == 0 {
  2158. return clen
  2159. }
  2160. if maxlen <= 0 {
  2161. // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items.
  2162. // maxlen = 256 * 1024 / unit
  2163. // if maxlen < (4 * 1024) {
  2164. // maxlen = 4 * 1024
  2165. // }
  2166. if unit < (256 / 4) {
  2167. maxlen = 256 * 1024 / unit
  2168. } else {
  2169. maxlen = 4 * 1024
  2170. }
  2171. }
  2172. if clen > maxlen {
  2173. rvlen = maxlen
  2174. } else {
  2175. rvlen = clen
  2176. }
  2177. return
  2178. }
  2179. func (d *Decoder) expandSliceRV(s reflect.Value, st reflect.Type, canChange bool, stElemSize, num, slen, scap int) (
  2180. s2 reflect.Value, scap2 int, changed bool) {
  2181. l1 := slen + num // new slice length
  2182. if l1 < slen {
  2183. d.errorf("expand slice: slice overflow")
  2184. }
  2185. if l1 <= scap {
  2186. if s.CanSet() {
  2187. s.SetLen(l1)
  2188. } else if canChange {
  2189. s2 = s.Slice(0, l1)
  2190. scap2 = scap
  2191. changed = true
  2192. } else {
  2193. d.errorf("expand slice: cannot change")
  2194. }
  2195. return
  2196. }
  2197. if !canChange {
  2198. d.errorf("expand slice: cannot change")
  2199. }
  2200. scap2 = growCap(scap, stElemSize, num)
  2201. s2 = reflect.MakeSlice(st, l1, scap2)
  2202. changed = true
  2203. reflect.Copy(s2, s)
  2204. return
  2205. }
  2206. func decReadFull(r io.Reader, bs []byte) (n int, err error) {
  2207. var nn int
  2208. for n < len(bs) && err == nil {
  2209. nn, err = r.Read(bs[n:])
  2210. if nn > 0 {
  2211. if err == io.EOF {
  2212. // leave EOF for next time
  2213. err = nil
  2214. }
  2215. n += nn
  2216. }
  2217. }
  2218. // do not do this - it serves no purpose
  2219. // if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
  2220. return
  2221. }