decode.go 64 KB

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