decode.go 64 KB

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