decode.go 65 KB

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