decode.go 62 KB

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