decode.go 60 KB

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