decode.go 62 KB

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