http urls monitor.

decode.go 63KB

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