decode.go 72 KB

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