decode.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  1. // Copyright (c) 2012-2020 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. "io"
  8. "math"
  9. "reflect"
  10. "strconv"
  11. "time"
  12. )
  13. const msgBadDesc = "unrecognized descriptor byte"
  14. const (
  15. decDefMaxDepth = 1024 // maximum depth
  16. decDefChanCap = 64 // should be large, as cap cannot be expanded
  17. decScratchByteArrayLen = (8 + 2 + 2 + 1) * 8 // around cacheLineSize ie ~64, depending on Decoder size
  18. // MARKER: massage decScratchByteArrayLen to ensure xxxDecDriver structs fit within cacheLine*N
  19. // decFailNonEmptyIntf configures whether we error
  20. // when decoding naked into a non-empty interface.
  21. //
  22. // Typically, we cannot decode non-nil stream value into
  23. // nil interface with methods (e.g. io.Reader).
  24. // However, in some scenarios, this should be allowed:
  25. // - MapType
  26. // - SliceType
  27. // - Extensions
  28. //
  29. // Consequently, we should relax this. Put it behind a const flag for now.
  30. decFailNonEmptyIntf = false
  31. // decUseTransient says that we should not use the transient optimization.
  32. //
  33. // There's potential for GC corruption or memory overwrites if transient isn't
  34. // used carefully, so this flag helps turn it off quickly if needed.
  35. //
  36. // Use it everywhere needed so we can completely remove unused code blocks.
  37. decUseTransient = true
  38. )
  39. var (
  40. errNeedMapOrArrayDecodeToStruct = errors.New("only encoded map or array can decode into struct")
  41. errCannotDecodeIntoNil = errors.New("cannot decode into nil")
  42. errExpandSliceCannotChange = errors.New("expand slice: cannot change")
  43. errDecoderNotInitialized = errors.New("Decoder not initialized")
  44. errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read")
  45. errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read")
  46. errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown")
  47. errMaxDepthExceeded = errors.New("maximum decoding depth exceeded")
  48. )
  49. // decByteState tracks where the []byte returned by the last call
  50. // to DecodeBytes or DecodeStringAsByte came from
  51. type decByteState uint8
  52. const (
  53. decByteStateNone decByteState = iota
  54. decByteStateZerocopy // view into []byte that we are decoding from
  55. decByteStateReuseBuf // view into transient buffer used internally by decDriver
  56. // decByteStateNewAlloc
  57. )
  58. type decNotDecodeableReason uint8
  59. const (
  60. decNotDecodeableReasonUnknown decNotDecodeableReason = iota
  61. decNotDecodeableReasonBadKind
  62. decNotDecodeableReasonNonAddrValue
  63. decNotDecodeableReasonNilReference
  64. )
  65. type decDriver interface {
  66. // this will check if the next token is a break.
  67. CheckBreak() bool
  68. // TryNil tries to decode as nil.
  69. // If a nil is in the stream, it consumes it and returns true.
  70. //
  71. // Note: if TryNil returns true, that must be handled.
  72. TryNil() bool
  73. // ContainerType returns one of: Bytes, String, Nil, Slice or Map.
  74. //
  75. // Return unSet if not known.
  76. //
  77. // Note: Implementations MUST fully consume sentinel container types, specifically Nil.
  78. ContainerType() (vt valueType)
  79. // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt.
  80. // For maps and arrays, it will not do the decoding in-band, but will signal
  81. // the decoder, so that is done later, by setting the fauxUnion.valueType field.
  82. //
  83. // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
  84. // for extensions, DecodeNaked must read the tag and the []byte if it exists.
  85. // if the []byte is not read, then kInterfaceNaked will treat it as a Handle
  86. // that stores the subsequent value in-band, and complete reading the RawExt.
  87. //
  88. // extensions should also use readx to decode them, for efficiency.
  89. // kInterface will extract the detached byte slice if it has to pass it outside its realm.
  90. DecodeNaked()
  91. DecodeInt64() (i int64)
  92. DecodeUint64() (ui uint64)
  93. DecodeFloat64() (f float64)
  94. DecodeBool() (b bool)
  95. // DecodeStringAsBytes returns the bytes representing a string.
  96. // It will return a view into scratch buffer or input []byte (if applicable).
  97. //
  98. // Note: This can also decode symbols, if supported.
  99. //
  100. // Users should consume it right away and not store it for later use.
  101. DecodeStringAsBytes() (v []byte)
  102. // DecodeBytes returns the bytes representing a binary value.
  103. // It will return a view into scratch buffer or input []byte (if applicable).
  104. //
  105. // All implementations must honor the contract below:
  106. // if ZeroCopy and applicable, return a view into input []byte we are decoding from
  107. // else if in == nil, return a view into scratch buffer
  108. // else append decoded value to in[:0] and return that
  109. // (this can be simulated by passing []byte{} as in parameter)
  110. //
  111. // Implementations must also update Decoder.decByteState on each call to
  112. // DecodeBytes or DecodeStringAsBytes. Some callers may check that and work appropriately.
  113. //
  114. // Note: DecodeBytes may decode past the length of the passed byte slice, up to the cap.
  115. // Consequently, it is ok to pass a zero-len slice to DecodeBytes, as the returned
  116. // byte slice will have the appropriate length.
  117. DecodeBytes(in []byte) (out []byte)
  118. // DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
  119. // DecodeExt will decode into a *RawExt or into an extension.
  120. DecodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext)
  121. // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
  122. DecodeTime() (t time.Time)
  123. // ReadArrayStart will return the length of the array.
  124. // If the format doesn't prefix the length, it returns containerLenUnknown.
  125. // If the expected array was a nil in the stream, it returns containerLenNil.
  126. ReadArrayStart() int
  127. // ReadMapStart will return the length of the array.
  128. // If the format doesn't prefix the length, it returns containerLenUnknown.
  129. // If the expected array was a nil in the stream, it returns containerLenNil.
  130. ReadMapStart() int
  131. reset()
  132. // atEndOfDecode()
  133. // nextValueBytes will return the bytes representing the next value in the stream.
  134. //
  135. // if start is nil, then treat it as a request to discard the next set of bytes,
  136. // and the return response does not matter.
  137. // Typically, this means that the returned []byte is nil/empty/undefined.
  138. //
  139. // Optimize for decoding from a []byte, where the nextValueBytes will just be a sub-slice
  140. // of the input slice. Callers that need to use this to not be a view into the input bytes
  141. // should handle it appropriately.
  142. nextValueBytes(start []byte) []byte
  143. // descBd will describe the token descriptor that signifies what type was decoded
  144. descBd() string
  145. decoder() *Decoder
  146. driverStateManager
  147. decNegintPosintFloatNumber
  148. }
  149. type decDriverContainerTracker interface {
  150. ReadArrayElem()
  151. ReadMapElemKey()
  152. ReadMapElemValue()
  153. ReadArrayEnd()
  154. ReadMapEnd()
  155. }
  156. type decNegintPosintFloatNumber interface {
  157. decInteger() (ui uint64, neg, ok bool)
  158. decFloat() (f float64, ok bool)
  159. }
  160. type decDriverNoopNumberHelper struct{}
  161. func (x decDriverNoopNumberHelper) decInteger() (ui uint64, neg, ok bool) {
  162. panic("decInteger unsupported")
  163. }
  164. func (x decDriverNoopNumberHelper) decFloat() (f float64, ok bool) { panic("decFloat unsupported") }
  165. type decDriverNoopContainerReader struct{}
  166. // func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { panic("ReadArrayStart unsupported") }
  167. // func (x decDriverNoopContainerReader) ReadMapStart() (v int) { panic("ReadMapStart unsupported") }
  168. func (x decDriverNoopContainerReader) ReadArrayEnd() {}
  169. func (x decDriverNoopContainerReader) ReadMapEnd() {}
  170. func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return }
  171. // DecodeOptions captures configuration options during decode.
  172. type DecodeOptions struct {
  173. // MapType specifies type to use during schema-less decoding of a map in the stream.
  174. // If nil (unset), we default to map[string]interface{} iff json handle and MapKeyAsString=true,
  175. // else map[interface{}]interface{}.
  176. MapType reflect.Type
  177. // SliceType specifies type to use during schema-less decoding of an array in the stream.
  178. // If nil (unset), we default to []interface{} for all formats.
  179. SliceType reflect.Type
  180. // MaxInitLen defines the maxinum initial length that we "make" a collection
  181. // (string, slice, map, chan). If 0 or negative, we default to a sensible value
  182. // based on the size of an element in the collection.
  183. //
  184. // For example, when decoding, a stream may say that it has 2^64 elements.
  185. // We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash.
  186. // Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
  187. MaxInitLen int
  188. // ReaderBufferSize is the size of the buffer used when reading.
  189. //
  190. // if > 0, we use a smart buffer internally for performance purposes.
  191. ReaderBufferSize int
  192. // MaxDepth defines the maximum depth when decoding nested
  193. // maps and slices. If 0 or negative, we default to a suitably large number (currently 1024).
  194. MaxDepth int16
  195. // If ErrorIfNoField, return an error when decoding a map
  196. // from a codec stream into a struct, and no matching struct field is found.
  197. ErrorIfNoField bool
  198. // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
  199. // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
  200. // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
  201. ErrorIfNoArrayExpand bool
  202. // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
  203. SignedInteger bool
  204. // MapValueReset controls how we decode into a map value.
  205. //
  206. // By default, we MAY retrieve the mapping for a key, and then decode into that.
  207. // However, especially with big maps, that retrieval may be expensive and unnecessary
  208. // if the stream already contains all that is necessary to recreate the value.
  209. //
  210. // If true, we will never retrieve the previous mapping,
  211. // but rather decode into a new value and set that in the map.
  212. //
  213. // If false, we will retrieve the previous mapping if necessary e.g.
  214. // the previous mapping is a pointer, or is a struct or array with pre-set state,
  215. // or is an interface.
  216. MapValueReset bool
  217. // SliceElementReset: on decoding a slice, reset the element to a zero value first.
  218. //
  219. // concern: if the slice already contained some garbage, we will decode into that garbage.
  220. SliceElementReset bool
  221. // InterfaceReset controls how we decode into an interface.
  222. //
  223. // By default, when we see a field that is an interface{...},
  224. // or a map with interface{...} value, we will attempt decoding into the
  225. // "contained" value.
  226. //
  227. // However, this prevents us from reading a string into an interface{}
  228. // that formerly contained a number.
  229. //
  230. // If true, we will decode into a new "blank" value, and set that in the interface.
  231. // If false, we will decode into whatever is contained in the interface.
  232. InterfaceReset bool
  233. // InternString controls interning of strings during decoding.
  234. //
  235. // Some handles, e.g. json, typically will read map keys as strings.
  236. // If the set of keys are finite, it may help reduce allocation to
  237. // look them up from a map (than to allocate them afresh).
  238. //
  239. // Note: Handles will be smart when using the intern functionality.
  240. // Every string should not be interned.
  241. // An excellent use-case for interning is struct field names,
  242. // or map keys where key type is string.
  243. InternString bool
  244. // PreferArrayOverSlice controls whether to decode to an array or a slice.
  245. //
  246. // This only impacts decoding into a nil interface{}.
  247. //
  248. // Consequently, it has no effect on codecgen.
  249. //
  250. // *Note*: This only applies if using go1.5 and above,
  251. // as it requires reflect.ArrayOf support which was absent before go1.5.
  252. PreferArrayOverSlice bool
  253. // DeleteOnNilMapValue controls how to decode a nil value in the stream.
  254. //
  255. // If true, we will delete the mapping of the key.
  256. // Else, just set the mapping to the zero value of the type.
  257. //
  258. // Deprecated: This does NOTHING and is left behind for compiling compatibility.
  259. // This change is necessitated because 'nil' in a stream now consistently
  260. // means the zero value (ie reset the value to its zero state).
  261. DeleteOnNilMapValue bool
  262. // RawToString controls how raw bytes in a stream are decoded into a nil interface{}.
  263. // By default, they are decoded as []byte, but can be decoded as string (if configured).
  264. RawToString bool
  265. // ZeroCopy controls whether decoded values of []byte or string type
  266. // point into the input []byte parameter passed to a NewDecoderBytes/ResetBytes(...) call.
  267. //
  268. // To illustrate, if ZeroCopy and decoding from a []byte (not io.Writer),
  269. // then a []byte or string in the output result may just be a slice of (point into)
  270. // the input bytes.
  271. //
  272. // This optimization prevents unnecessary copying.
  273. //
  274. // However, it is made optional, as the caller MUST ensure that the input parameter []byte is
  275. // not modified after the Decode() happens, as any changes are mirrored in the decoded result.
  276. ZeroCopy bool
  277. // PreferPointerForStructOrArray controls whether a struct or array
  278. // is stored in a nil interface{}, or a pointer to it.
  279. //
  280. // This mostly impacts when we decode registered extensions.
  281. PreferPointerForStructOrArray bool
  282. // ValidateUnicode controls will cause decoding to fail if an expected unicode
  283. // string is well-formed but include invalid codepoints.
  284. //
  285. // This could have a performance impact.
  286. ValidateUnicode bool
  287. }
  288. // ----------------------------------------
  289. func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) {
  290. d.d.DecodeExt(rv2i(rv), f.ti.rt, 0, nil)
  291. }
  292. func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) {
  293. d.d.DecodeExt(rv2i(rv), f.ti.rt, f.xfTag, f.xfFn)
  294. }
  295. func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) {
  296. rv2i(rv).(Selfer).CodecDecodeSelf(d)
  297. }
  298. func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) {
  299. bm := rv2i(rv).(encoding.BinaryUnmarshaler)
  300. xbs := d.d.DecodeBytes(nil)
  301. fnerr := bm.UnmarshalBinary(xbs)
  302. d.onerror(fnerr)
  303. }
  304. func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) {
  305. tm := rv2i(rv).(encoding.TextUnmarshaler)
  306. fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes())
  307. d.onerror(fnerr)
  308. }
  309. func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) {
  310. d.jsonUnmarshalV(rv2i(rv).(jsonUnmarshaler))
  311. }
  312. func (d *Decoder) jsonUnmarshalV(tm jsonUnmarshaler) {
  313. // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
  314. var bs0 = []byte{}
  315. if !d.bytes {
  316. bs0 = d.blist.get(256)
  317. }
  318. bs := d.d.nextValueBytes(bs0)
  319. fnerr := tm.UnmarshalJSON(bs)
  320. if !d.bytes {
  321. d.blist.put(bs)
  322. if !byteSliceSameData(bs0, bs) {
  323. d.blist.put(bs0)
  324. }
  325. }
  326. d.onerror(fnerr)
  327. }
  328. func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) {
  329. d.errorf("no decoding function defined for kind %v", rv.Kind())
  330. }
  331. func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) {
  332. rvSetBytes(rv, d.rawBytes())
  333. }
  334. func (d *Decoder) kString(f *codecFnInfo, rv reflect.Value) {
  335. rvSetString(rv, d.stringZC(d.d.DecodeStringAsBytes()))
  336. }
  337. func (d *Decoder) kBool(f *codecFnInfo, rv reflect.Value) {
  338. rvSetBool(rv, d.d.DecodeBool())
  339. }
  340. func (d *Decoder) kTime(f *codecFnInfo, rv reflect.Value) {
  341. rvSetTime(rv, d.d.DecodeTime())
  342. }
  343. func (d *Decoder) kFloat32(f *codecFnInfo, rv reflect.Value) {
  344. rvSetFloat32(rv, d.decodeFloat32())
  345. }
  346. func (d *Decoder) kFloat64(f *codecFnInfo, rv reflect.Value) {
  347. rvSetFloat64(rv, d.d.DecodeFloat64())
  348. }
  349. func (d *Decoder) kComplex64(f *codecFnInfo, rv reflect.Value) {
  350. rvSetComplex64(rv, complex(d.decodeFloat32(), 0))
  351. }
  352. func (d *Decoder) kComplex128(f *codecFnInfo, rv reflect.Value) {
  353. rvSetComplex128(rv, complex(d.d.DecodeFloat64(), 0))
  354. }
  355. func (d *Decoder) kInt(f *codecFnInfo, rv reflect.Value) {
  356. rvSetInt(rv, int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)))
  357. }
  358. func (d *Decoder) kInt8(f *codecFnInfo, rv reflect.Value) {
  359. rvSetInt8(rv, int8(chkOvf.IntV(d.d.DecodeInt64(), 8)))
  360. }
  361. func (d *Decoder) kInt16(f *codecFnInfo, rv reflect.Value) {
  362. rvSetInt16(rv, int16(chkOvf.IntV(d.d.DecodeInt64(), 16)))
  363. }
  364. func (d *Decoder) kInt32(f *codecFnInfo, rv reflect.Value) {
  365. rvSetInt32(rv, int32(chkOvf.IntV(d.d.DecodeInt64(), 32)))
  366. }
  367. func (d *Decoder) kInt64(f *codecFnInfo, rv reflect.Value) {
  368. rvSetInt64(rv, d.d.DecodeInt64())
  369. }
  370. func (d *Decoder) kUint(f *codecFnInfo, rv reflect.Value) {
  371. rvSetUint(rv, uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)))
  372. }
  373. func (d *Decoder) kUintptr(f *codecFnInfo, rv reflect.Value) {
  374. rvSetUintptr(rv, uintptr(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)))
  375. }
  376. func (d *Decoder) kUint8(f *codecFnInfo, rv reflect.Value) {
  377. rvSetUint8(rv, uint8(chkOvf.UintV(d.d.DecodeUint64(), 8)))
  378. }
  379. func (d *Decoder) kUint16(f *codecFnInfo, rv reflect.Value) {
  380. rvSetUint16(rv, uint16(chkOvf.UintV(d.d.DecodeUint64(), 16)))
  381. }
  382. func (d *Decoder) kUint32(f *codecFnInfo, rv reflect.Value) {
  383. rvSetUint32(rv, uint32(chkOvf.UintV(d.d.DecodeUint64(), 32)))
  384. }
  385. func (d *Decoder) kUint64(f *codecFnInfo, rv reflect.Value) {
  386. rvSetUint64(rv, d.d.DecodeUint64())
  387. }
  388. func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) {
  389. // nil interface:
  390. // use some hieristics to decode it appropriately
  391. // based on the detected next value in the stream.
  392. n := d.naked()
  393. d.d.DecodeNaked()
  394. // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader).
  395. // Howver, it is possible that the user has ways to pass in a type for a given interface
  396. // - MapType
  397. // - SliceType
  398. // - Extensions
  399. //
  400. // Consequently, we should relax this. Put it behind a const flag for now.
  401. if decFailNonEmptyIntf && f.ti.numMeth > 0 {
  402. d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth)
  403. }
  404. switch n.v {
  405. case valueTypeMap:
  406. mtid := d.mtid
  407. if mtid == 0 {
  408. if d.jsms { // if json, default to a map type with string keys
  409. mtid = mapStrIntfTypId // for json performance
  410. } else {
  411. mtid = mapIntfIntfTypId
  412. }
  413. }
  414. if mtid == mapStrIntfTypId {
  415. var v2 map[string]interface{}
  416. d.decode(&v2)
  417. rvn = rv4iptr(&v2).Elem()
  418. } else if mtid == mapIntfIntfTypId {
  419. var v2 map[interface{}]interface{}
  420. d.decode(&v2)
  421. rvn = rv4iptr(&v2).Elem()
  422. } else if d.mtr {
  423. rvn = reflect.New(d.h.MapType)
  424. d.decode(rv2i(rvn))
  425. rvn = rvn.Elem()
  426. } else {
  427. rvn = rvZeroAddrK(d.h.MapType, reflect.Map)
  428. d.decodeValue(rvn, nil)
  429. }
  430. case valueTypeArray:
  431. if d.stid == 0 || d.stid == intfSliceTypId {
  432. var v2 []interface{}
  433. d.decode(&v2)
  434. rvn = rv4iptr(&v2).Elem()
  435. } else if d.str {
  436. rvn = reflect.New(d.h.SliceType)
  437. d.decode(rv2i(rvn))
  438. rvn = rvn.Elem()
  439. } else {
  440. rvn = rvZeroAddrK(d.h.SliceType, reflect.Slice)
  441. d.decodeValue(rvn, nil)
  442. }
  443. if reflectArrayOfSupported && d.h.PreferArrayOverSlice {
  444. rvn = rvGetArray4Slice(rvn)
  445. }
  446. case valueTypeExt:
  447. tag, bytes := n.u, n.l // calling decode below might taint the values
  448. bfn := d.h.getExtForTag(tag)
  449. var re = RawExt{Tag: tag}
  450. if bytes == nil {
  451. // it is one of the InterfaceExt ones: json and cbor.
  452. // most likely cbor, as json decoding never reveals valueTypeExt (no tagging support)
  453. if bfn == nil {
  454. d.decode(&re.Value)
  455. rvn = rv4iptr(&re).Elem()
  456. } else {
  457. if bfn.ext == SelfExt {
  458. rvn = rvZeroAddrK(bfn.rt, bfn.rt.Kind())
  459. d.decodeValue(rvn, d.h.fnNoExt(bfn.rt))
  460. } else {
  461. rvn = reflect.New(bfn.rt)
  462. d.interfaceExtConvertAndDecode(rv2i(rvn), bfn.ext)
  463. rvn = rvn.Elem()
  464. }
  465. }
  466. } else {
  467. // one of the BytesExt ones: binc, msgpack, simple
  468. if bfn == nil {
  469. re.setData(bytes, false)
  470. rvn = rv4iptr(&re).Elem()
  471. } else {
  472. rvn = reflect.New(bfn.rt)
  473. if bfn.ext == SelfExt {
  474. d.sideDecode(rv2i(rvn), bfn.rt, bytes)
  475. } else {
  476. bfn.ext.ReadExt(rv2i(rvn), bytes)
  477. }
  478. rvn = rvn.Elem()
  479. }
  480. }
  481. // if struct/array, directly store pointer into the interface
  482. if d.h.PreferPointerForStructOrArray && rvn.CanAddr() {
  483. if rk := rvn.Kind(); rk == reflect.Array || rk == reflect.Struct {
  484. rvn = rvn.Addr()
  485. }
  486. }
  487. case valueTypeNil:
  488. // rvn = reflect.Zero(f.ti.rt)
  489. // no-op
  490. case valueTypeInt:
  491. rvn = n.ri()
  492. case valueTypeUint:
  493. rvn = n.ru()
  494. case valueTypeFloat:
  495. rvn = n.rf()
  496. case valueTypeBool:
  497. rvn = n.rb()
  498. case valueTypeString, valueTypeSymbol:
  499. rvn = n.rs()
  500. case valueTypeBytes:
  501. rvn = n.rl()
  502. case valueTypeTime:
  503. rvn = n.rt()
  504. default:
  505. halt.errorf("kInterfaceNaked: unexpected valueType: %d", n.v)
  506. }
  507. return
  508. }
  509. func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
  510. // Note: A consequence of how kInterface works, is that
  511. // if an interface already contains something, we try
  512. // to decode into what was there before.
  513. // We do not replace with a generic value (as got from decodeNaked).
  514. //
  515. // every interface passed here MUST be settable.
  516. //
  517. // ensure you call rvSetIntf(...) before returning.
  518. isnilrv := rvIsNil(rv)
  519. var rvn reflect.Value
  520. if d.h.InterfaceReset {
  521. // check if mapping to a type: if so, initialize it and move on
  522. rvn = d.h.intf2impl(f.ti.rtid)
  523. if !rvn.IsValid() {
  524. rvn = d.kInterfaceNaked(f)
  525. if rvn.IsValid() {
  526. rvSetIntf(rv, rvn)
  527. } else if !isnilrv {
  528. decSetNonNilRV2Zero4Intf(rv)
  529. }
  530. return
  531. }
  532. } else if isnilrv {
  533. // check if mapping to a type: if so, initialize it and move on
  534. rvn = d.h.intf2impl(f.ti.rtid)
  535. if !rvn.IsValid() {
  536. rvn = d.kInterfaceNaked(f)
  537. if rvn.IsValid() {
  538. rvSetIntf(rv, rvn)
  539. }
  540. return
  541. }
  542. } else {
  543. // now we have a non-nil interface value, meaning it contains a type
  544. rvn = rv.Elem()
  545. }
  546. // rvn is now a non-interface type
  547. canDecode, _ := isDecodeable(rvn)
  548. // Note: interface{} is settable, but underlying type may not be.
  549. // Consequently, we MAY have to allocate a value (containing the underlying value),
  550. // decode into it, and reset the interface to that new value.
  551. if !canDecode {
  552. rvn2 := d.oneShotAddrRV(rvn.Type(), rvn.Kind())
  553. rvSetDirect(rvn2, rvn)
  554. rvn = rvn2
  555. }
  556. d.decodeValue(rvn, nil)
  557. rvSetIntf(rv, rvn)
  558. }
  559. func decStructFieldKeyNotString(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) {
  560. if keyType == valueTypeInt {
  561. rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10)
  562. } else if keyType == valueTypeUint {
  563. rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10)
  564. } else if keyType == valueTypeFloat {
  565. rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64)
  566. } else {
  567. halt.errorf("invalid struct key type: %v", keyType)
  568. }
  569. return
  570. }
  571. func (d *Decoder) kStructField(si *structFieldInfo, rv reflect.Value) {
  572. if d.d.TryNil() {
  573. if rv = si.path.field(rv); rv.IsValid() {
  574. decSetNonNilRV2Zero(rv)
  575. }
  576. return
  577. }
  578. d.decodeValueNoCheckNil(si.path.fieldAlloc(rv), nil)
  579. }
  580. func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  581. ctyp := d.d.ContainerType()
  582. ti := f.ti
  583. var mf MissingFielder
  584. if ti.flagMissingFielder {
  585. mf = rv2i(rv).(MissingFielder)
  586. } else if ti.flagMissingFielderPtr {
  587. mf = rv2i(rvAddr(rv, ti.ptr)).(MissingFielder)
  588. }
  589. if ctyp == valueTypeMap {
  590. containerLen := d.mapStart(d.d.ReadMapStart())
  591. if containerLen == 0 {
  592. d.mapEnd()
  593. return
  594. }
  595. hasLen := containerLen >= 0
  596. var name2 []byte
  597. if mf != nil {
  598. var namearr2 [16]byte
  599. name2 = namearr2[:0]
  600. }
  601. var rvkencname []byte
  602. for j := 0; d.containerNext(j, containerLen, hasLen); j++ {
  603. d.mapElemKey()
  604. if ti.keyType == valueTypeString {
  605. rvkencname = d.d.DecodeStringAsBytes()
  606. } else {
  607. rvkencname = decStructFieldKeyNotString(d.d, ti.keyType, &d.b)
  608. }
  609. d.mapElemValue()
  610. if si := ti.siForEncName(rvkencname); si != nil {
  611. d.kStructField(si, rv)
  612. } else if mf != nil {
  613. // store rvkencname in new []byte, as it previously shares Decoder.b, which is used in decode
  614. name2 = append(name2[:0], rvkencname...)
  615. var f interface{}
  616. d.decode(&f)
  617. if !mf.CodecMissingField(name2, f) && d.h.ErrorIfNoField {
  618. d.errorf("no matching struct field when decoding stream map with key: %s ", stringView(name2))
  619. }
  620. } else {
  621. d.structFieldNotFound(-1, stringView(rvkencname))
  622. }
  623. }
  624. d.mapEnd()
  625. } else if ctyp == valueTypeArray {
  626. containerLen := d.arrayStart(d.d.ReadArrayStart())
  627. if containerLen == 0 {
  628. d.arrayEnd()
  629. return
  630. }
  631. // Not much gain from doing it two ways for array.
  632. // Arrays are not used as much for structs.
  633. tisfi := ti.sfi.source()
  634. hasLen := containerLen >= 0
  635. // iterate all the items in the stream
  636. // if mapped elem-wise to a field, handle it
  637. // if more stream items than can be mapped, error it
  638. for j := 0; d.containerNext(j, containerLen, hasLen); j++ {
  639. d.arrayElem()
  640. if j < len(tisfi) {
  641. d.kStructField(tisfi[j], rv)
  642. } else {
  643. d.structFieldNotFound(j, "")
  644. }
  645. }
  646. d.arrayEnd()
  647. } else {
  648. d.onerror(errNeedMapOrArrayDecodeToStruct)
  649. }
  650. }
  651. func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
  652. // A slice can be set from a map or array in stream.
  653. // This way, the order can be kept (as order is lost with map).
  654. // Note: rv is a slice type here - guaranteed
  655. ti := f.ti
  656. rvCanset := rv.CanSet()
  657. ctyp := d.d.ContainerType()
  658. if ctyp == valueTypeBytes || ctyp == valueTypeString {
  659. // you can only decode bytes or string in the stream into a slice or array of bytes
  660. if !(ti.rtid == uint8SliceTypId || ti.elemkind == uint8(reflect.Uint8)) {
  661. d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
  662. }
  663. rvbs := rvGetBytes(rv)
  664. if !rvCanset {
  665. // not addressable byte slice, so do not decode into it past the length
  666. rvbs = rvbs[:len(rvbs):len(rvbs)]
  667. }
  668. bs2 := d.decodeBytesInto(rvbs)
  669. // if !(len(bs2) == len(rvbs) && byteSliceSameData(rvbs, bs2)) {
  670. if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
  671. if rvCanset {
  672. rvSetBytes(rv, bs2)
  673. } else if len(rvbs) > 0 && len(bs2) > 0 {
  674. copy(rvbs, bs2)
  675. }
  676. }
  677. return
  678. }
  679. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - never Nil
  680. // an array can never return a nil slice. so no need to check f.array here.
  681. if containerLenS == 0 {
  682. if rvCanset {
  683. if rvIsNil(rv) {
  684. rvSetDirect(rv, rvSliceZeroCap(ti.rt))
  685. } else {
  686. rvSetSliceLen(rv, 0)
  687. }
  688. }
  689. slh.End()
  690. return
  691. }
  692. rtelem0Mut := !scalarBitset.isset(ti.elemkind)
  693. rtelem := ti.elem
  694. for k := reflect.Kind(ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
  695. rtelem = rtelem.Elem()
  696. }
  697. var fn *codecFn
  698. var rvChanged bool
  699. var rv0 = rv
  700. var rv9 reflect.Value
  701. rvlen := rvLenSlice(rv)
  702. rvcap := rvCapSlice(rv)
  703. hasLen := containerLenS > 0
  704. if hasLen {
  705. if containerLenS > rvcap {
  706. oldRvlenGtZero := rvlen > 0
  707. rvlen1 := decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
  708. if rvlen1 == rvlen {
  709. } else if rvlen1 <= rvcap {
  710. if rvCanset {
  711. rvlen = rvlen1
  712. rvSetSliceLen(rv, rvlen)
  713. }
  714. } else if rvCanset { // rvlen1 > rvcap
  715. rvlen = rvlen1
  716. rv, rvCanset = rvMakeSlice(rv, f.ti, rvlen, rvlen)
  717. rvcap = rvlen
  718. rvChanged = !rvCanset
  719. } else { // rvlen1 > rvcap && !canSet
  720. d.errorf("cannot decode into non-settable slice")
  721. }
  722. if rvChanged && oldRvlenGtZero && rtelem0Mut {
  723. rvCopySlice(rv, rv0, rtelem) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
  724. }
  725. } else if containerLenS != rvlen {
  726. if rvCanset {
  727. rvlen = containerLenS
  728. rvSetSliceLen(rv, rvlen)
  729. }
  730. }
  731. }
  732. // consider creating new element once, and just decoding into it.
  733. var elemReset = d.h.SliceElementReset
  734. var j int
  735. for ; d.containerNext(j, containerLenS, hasLen); j++ {
  736. if j == 0 {
  737. if rvIsNil(rv) { // means hasLen = false
  738. if rvCanset {
  739. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
  740. rv, rvCanset = rvMakeSlice(rv, f.ti, rvlen, rvlen)
  741. rvcap = rvlen
  742. rvChanged = !rvCanset
  743. } else {
  744. d.errorf("cannot decode into non-settable slice")
  745. }
  746. }
  747. if fn == nil {
  748. fn = d.h.fn(rtelem)
  749. }
  750. }
  751. // if indefinite, etc, then expand the slice if necessary
  752. if j >= rvlen {
  753. slh.ElemContainerState(j)
  754. // expand the slice up to the cap.
  755. // Note that we did, so we have to reset it later.
  756. if rvlen < rvcap {
  757. rvlen = rvcap
  758. if rvCanset {
  759. rvSetSliceLen(rv, rvlen)
  760. } else if rvChanged {
  761. rv = rvSlice(rv, rvlen)
  762. } else {
  763. d.onerror(errExpandSliceCannotChange)
  764. }
  765. } else {
  766. if !(rvCanset || rvChanged) {
  767. d.onerror(errExpandSliceCannotChange)
  768. }
  769. rv, rvcap, rvCanset = rvGrowSlice(rv, f.ti, rvcap, 1)
  770. rvlen = rvcap
  771. rvChanged = !rvCanset
  772. }
  773. } else {
  774. slh.ElemContainerState(j)
  775. }
  776. rv9 = rvSliceIndex(rv, j, f.ti)
  777. if elemReset {
  778. rvSetZero(rv9)
  779. }
  780. d.decodeValue(rv9, fn)
  781. }
  782. if j < rvlen {
  783. if rvCanset {
  784. rvSetSliceLen(rv, j)
  785. } else if rvChanged {
  786. rv = rvSlice(rv, j)
  787. }
  788. // rvlen = j
  789. } else if j == 0 && rvIsNil(rv) {
  790. if rvCanset {
  791. rv = rvSliceZeroCap(ti.rt)
  792. rvCanset = false
  793. rvChanged = true
  794. }
  795. }
  796. slh.End()
  797. if rvChanged { // infers rvCanset=true, so it can be reset
  798. rvSetDirect(rv0, rv)
  799. }
  800. }
  801. func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
  802. // An array can be set from a map or array in stream.
  803. ctyp := d.d.ContainerType()
  804. if handleBytesWithinKArray && (ctyp == valueTypeBytes || ctyp == valueTypeString) {
  805. // you can only decode bytes or string in the stream into a slice or array of bytes
  806. if f.ti.elemkind != uint8(reflect.Uint8) {
  807. d.errorf("bytes/string in stream can decode into array of bytes, but not %v", f.ti.rt)
  808. }
  809. rvbs := rvGetArrayBytes(rv, nil)
  810. bs2 := d.decodeBytesInto(rvbs)
  811. if !byteSliceSameData(rvbs, bs2) && len(rvbs) > 0 && len(bs2) > 0 {
  812. copy(rvbs, bs2)
  813. }
  814. return
  815. }
  816. slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - never Nil
  817. // an array can never return a nil slice. so no need to check f.array here.
  818. if containerLenS == 0 {
  819. slh.End()
  820. return
  821. }
  822. rtelem := f.ti.elem
  823. for k := reflect.Kind(f.ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
  824. rtelem = rtelem.Elem()
  825. }
  826. var fn *codecFn
  827. var rv9 reflect.Value
  828. rvlen := rv.Len() // same as cap
  829. hasLen := containerLenS > 0
  830. if hasLen && containerLenS > rvlen {
  831. d.errorf("cannot decode into array with length: %v, less than container length: %v", rvlen, containerLenS)
  832. }
  833. // consider creating new element once, and just decoding into it.
  834. var elemReset = d.h.SliceElementReset
  835. for j := 0; d.containerNext(j, containerLenS, hasLen); j++ {
  836. // note that you cannot expand the array if indefinite and we go past array length
  837. if j >= rvlen {
  838. slh.arrayCannotExpand(hasLen, rvlen, j, containerLenS)
  839. return
  840. }
  841. slh.ElemContainerState(j)
  842. rv9 = rvArrayIndex(rv, j, f.ti)
  843. if elemReset {
  844. rvSetZero(rv9)
  845. }
  846. if fn == nil {
  847. fn = d.h.fn(rtelem)
  848. }
  849. d.decodeValue(rv9, fn)
  850. }
  851. slh.End()
  852. }
  853. func (d *Decoder) kChan(f *codecFnInfo, rv reflect.Value) {
  854. // A slice can be set from a map or array in stream.
  855. // This way, the order can be kept (as order is lost with map).
  856. ti := f.ti
  857. if ti.chandir&uint8(reflect.SendDir) == 0 {
  858. d.errorf("receive-only channel cannot be decoded")
  859. }
  860. ctyp := d.d.ContainerType()
  861. if ctyp == valueTypeBytes || ctyp == valueTypeString {
  862. // you can only decode bytes or string in the stream into a slice or array of bytes
  863. if !(ti.rtid == uint8SliceTypId || ti.elemkind == uint8(reflect.Uint8)) {
  864. d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
  865. }
  866. bs2 := d.d.DecodeBytes(nil)
  867. irv := rv2i(rv)
  868. ch, ok := irv.(chan<- byte)
  869. if !ok {
  870. ch = irv.(chan byte)
  871. }
  872. for _, b := range bs2 {
  873. ch <- b
  874. }
  875. return
  876. }
  877. var rvCanset = rv.CanSet()
  878. // only expects valueType(Array|Map - nil handled above)
  879. slh, containerLenS := d.decSliceHelperStart()
  880. // an array can never return a nil slice. so no need to check f.array here.
  881. if containerLenS == 0 {
  882. if rvCanset && rvIsNil(rv) {
  883. rvSetDirect(rv, reflect.MakeChan(ti.rt, 0))
  884. }
  885. slh.End()
  886. return
  887. }
  888. rtelem := ti.elem
  889. useTransient := decUseTransient && ti.elemkind != byte(reflect.Ptr) && ti.tielem.flagCanTransient
  890. for k := reflect.Kind(ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
  891. rtelem = rtelem.Elem()
  892. }
  893. var fn *codecFn
  894. var rvChanged bool
  895. var rv0 = rv
  896. var rv9 reflect.Value
  897. var rvlen int // = rv.Len()
  898. hasLen := containerLenS > 0
  899. for j := 0; d.containerNext(j, containerLenS, hasLen); j++ {
  900. if j == 0 {
  901. if rvIsNil(rv) {
  902. if hasLen {
  903. rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
  904. } else {
  905. rvlen = decDefChanCap
  906. }
  907. if rvCanset {
  908. rv = reflect.MakeChan(ti.rt, rvlen)
  909. rvChanged = true
  910. } else {
  911. d.errorf("cannot decode into non-settable chan")
  912. }
  913. }
  914. if fn == nil {
  915. fn = d.h.fn(rtelem)
  916. }
  917. }
  918. slh.ElemContainerState(j)
  919. if rv9.IsValid() {
  920. rvSetZero(rv9)
  921. } else if decUseTransient && useTransient {
  922. rv9 = d.perType.TransientAddrK(ti.elem, reflect.Kind(ti.elemkind))
  923. } else {
  924. rv9 = rvZeroAddrK(ti.elem, reflect.Kind(ti.elemkind))
  925. }
  926. if !d.d.TryNil() {
  927. d.decodeValueNoCheckNil(rv9, fn)
  928. }
  929. rv.Send(rv9)
  930. }
  931. slh.End()
  932. if rvChanged { // infers rvCanset=true, so it can be reset
  933. rvSetDirect(rv0, rv)
  934. }
  935. }
  936. func (d *Decoder) kMap(f *codecFnInfo, rv reflect.Value) {
  937. containerLen := d.mapStart(d.d.ReadMapStart())
  938. ti := f.ti
  939. if rvIsNil(rv) {
  940. rvlen := decInferLen(containerLen, d.h.MaxInitLen, int(ti.keysize+ti.elemsize))
  941. rvSetDirect(rv, makeMapReflect(ti.rt, rvlen))
  942. }
  943. if containerLen == 0 {
  944. d.mapEnd()
  945. return
  946. }
  947. ktype, vtype := ti.key, ti.elem
  948. ktypeId := rt2id(ktype)
  949. vtypeKind := reflect.Kind(ti.elemkind)
  950. ktypeKind := reflect.Kind(ti.keykind)
  951. kfast := mapKeyFastKindFor(ktypeKind)
  952. visindirect := mapStoresElemIndirect(uintptr(ti.elemsize))
  953. visref := refBitset.isset(ti.elemkind)
  954. vtypePtr := vtypeKind == reflect.Ptr
  955. ktypePtr := ktypeKind == reflect.Ptr
  956. vTransient := decUseTransient && !vtypePtr && ti.tielem.flagCanTransient
  957. kTransient := decUseTransient && !ktypePtr && ti.tikey.flagCanTransient
  958. var vtypeElem reflect.Type
  959. var keyFn, valFn *codecFn
  960. var ktypeLo, vtypeLo = ktype, vtype
  961. if ktypeKind == reflect.Ptr {
  962. for ktypeLo = ktype.Elem(); ktypeLo.Kind() == reflect.Ptr; ktypeLo = ktypeLo.Elem() {
  963. }
  964. }
  965. if vtypePtr {
  966. vtypeElem = vtype.Elem()
  967. for vtypeLo = vtypeElem; vtypeLo.Kind() == reflect.Ptr; vtypeLo = vtypeLo.Elem() {
  968. }
  969. }
  970. rvkMut := !scalarBitset.isset(ti.keykind) // if ktype is immutable, then re-use the same rvk.
  971. rvvMut := !scalarBitset.isset(ti.elemkind)
  972. rvvCanNil := isnilBitset.isset(ti.elemkind)
  973. // rvk: key
  974. // rvkn: if non-mutable, on each iteration of loop, set rvk to this
  975. // rvv: value
  976. // rvvn: if non-mutable, on each iteration of loop, set rvv to this
  977. // if mutable, may be used as a temporary value for local-scoped operations
  978. // rvva: if mutable, used as transient value for use for key lookup
  979. // rvvz: zero value of map value type, used to do a map set when nil is found in stream
  980. var rvk, rvkn, rvv, rvvn, rvva, rvvz reflect.Value
  981. // we do a doMapGet if kind is mutable, and InterfaceReset=true if interface
  982. var doMapGet, doMapSet bool
  983. if !d.h.MapValueReset {
  984. if rvvMut && (vtypeKind != reflect.Interface || !d.h.InterfaceReset) {
  985. doMapGet = true
  986. rvva = mapAddrLoopvarRV(vtype, vtypeKind)
  987. }
  988. }
  989. ktypeIsString := ktypeId == stringTypId
  990. ktypeIsIntf := ktypeId == intfTypId
  991. hasLen := containerLen > 0
  992. // kstrbs is used locally for the key bytes, so we can reduce allocation.
  993. // When we read keys, we copy to this local bytes array, and use a stringView for lookup.
  994. // We only convert it into a true string if we have to do a set on the map.
  995. // Since kstr2bs will usually escape to the heap, declaring a [64]byte array may be wasteful.
  996. // It is only valuable if we are sure that it is declared on the stack.
  997. // var kstrarr [64]byte // most keys are less than 32 bytes, and even more less than 64
  998. // var kstrbs = kstrarr[:0]
  999. var kstrbs []byte
  1000. var kstr2bs []byte
  1001. var s string
  1002. var callFnRvk bool
  1003. fnRvk2 := func() (s string) {
  1004. callFnRvk = false
  1005. if len(kstr2bs) < 2 {
  1006. return string(kstr2bs)
  1007. }
  1008. return d.mapKeyString(&callFnRvk, &kstrbs, &kstr2bs)
  1009. }
  1010. // Use a possibly transient (map) value (and key), to reduce allocation
  1011. for j := 0; d.containerNext(j, containerLen, hasLen); j++ {
  1012. callFnRvk = false
  1013. if j == 0 {
  1014. // if vtypekind is a scalar and thus value will be decoded using TransientAddrK,
  1015. // then it is ok to use TransientAddr2K for the map key.
  1016. if decUseTransient && vTransient && kTransient {
  1017. rvk = d.perType.TransientAddr2K(ktype, ktypeKind)
  1018. } else {
  1019. rvk = rvZeroAddrK(ktype, ktypeKind)
  1020. }
  1021. if !rvkMut {
  1022. rvkn = rvk
  1023. }
  1024. if !rvvMut {
  1025. if decUseTransient && vTransient {
  1026. rvvn = d.perType.TransientAddrK(vtype, vtypeKind)
  1027. } else {
  1028. rvvn = rvZeroAddrK(vtype, vtypeKind)
  1029. }
  1030. }
  1031. if !ktypeIsString && keyFn == nil {
  1032. keyFn = d.h.fn(ktypeLo)
  1033. }
  1034. if valFn == nil {
  1035. valFn = d.h.fn(vtypeLo)
  1036. }
  1037. } else if rvkMut {
  1038. rvSetZero(rvk)
  1039. } else {
  1040. rvk = rvkn
  1041. }
  1042. d.mapElemKey()
  1043. if ktypeIsString {
  1044. kstr2bs = d.d.DecodeStringAsBytes()
  1045. rvSetString(rvk, fnRvk2())
  1046. } else {
  1047. d.decByteState = decByteStateNone
  1048. d.decodeValue(rvk, keyFn)
  1049. // special case if interface wrapping a byte slice
  1050. if ktypeIsIntf {
  1051. if rvk2 := rvk.Elem(); rvk2.IsValid() && rvk2.Type() == uint8SliceTyp {
  1052. kstr2bs = rvGetBytes(rvk2)
  1053. rvSetIntf(rvk, rv4istr(fnRvk2()))
  1054. }
  1055. // NOTE: consider failing early if map/slice/func
  1056. }
  1057. }
  1058. d.mapElemValue()
  1059. if d.d.TryNil() {
  1060. // since a map, we have to set zero value if needed
  1061. if !rvvz.IsValid() {
  1062. rvvz = rvZeroK(vtype, vtypeKind)
  1063. }
  1064. if callFnRvk {
  1065. s = d.string(kstr2bs)
  1066. if ktypeIsString {
  1067. rvSetString(rvk, s)
  1068. } else { // ktypeIsIntf
  1069. rvSetIntf(rvk, rv4istr(s))
  1070. }
  1071. }
  1072. mapSet(rv, rvk, rvvz, kfast, visindirect, visref)
  1073. continue
  1074. }
  1075. // there is non-nil content in the stream to decode ...
  1076. // consequently, it's ok to just directly create new value to the pointer (if vtypePtr)
  1077. // set doMapSet to false iff u do a get, and the return value is a non-nil pointer
  1078. doMapSet = true
  1079. if !rvvMut {
  1080. rvv = rvvn
  1081. } else if !doMapGet {
  1082. goto NEW_RVV
  1083. } else {
  1084. rvv = mapGet(rv, rvk, rvva, kfast, visindirect, visref)
  1085. if !rvv.IsValid() || (rvvCanNil && rvIsNil(rvv)) {
  1086. goto NEW_RVV
  1087. }
  1088. switch vtypeKind {
  1089. case reflect.Ptr, reflect.Map: // ok to decode directly into map
  1090. doMapSet = false
  1091. case reflect.Interface:
  1092. // if an interface{}, just decode into it iff a non-nil ptr/map, else allocate afresh
  1093. rvvn = rvv.Elem()
  1094. if k := rvvn.Kind(); (k == reflect.Ptr || k == reflect.Map) && !rvIsNil(rvvn) {
  1095. d.decodeValueNoCheckNil(rvvn, nil) // valFn is incorrect here
  1096. continue
  1097. }
  1098. // make addressable (so we can set the interface)
  1099. rvvn = rvZeroAddrK(vtype, vtypeKind)
  1100. rvSetIntf(rvvn, rvv)
  1101. rvv = rvvn
  1102. default:
  1103. // make addressable (so you can set the slice/array elements, etc)
  1104. if decUseTransient && vTransient {
  1105. rvvn = d.perType.TransientAddrK(vtype, vtypeKind)
  1106. } else {
  1107. rvvn = rvZeroAddrK(vtype, vtypeKind)
  1108. }
  1109. rvSetDirect(rvvn, rvv)
  1110. rvv = rvvn
  1111. }
  1112. }
  1113. goto DECODE_VALUE_NO_CHECK_NIL
  1114. NEW_RVV:
  1115. if vtypePtr {
  1116. rvv = reflect.New(vtypeElem) // non-nil in stream, so allocate value
  1117. } else if decUseTransient && vTransient {
  1118. rvv = d.perType.TransientAddrK(vtype, vtypeKind)
  1119. } else {
  1120. rvv = rvZeroAddrK(vtype, vtypeKind)
  1121. }
  1122. DECODE_VALUE_NO_CHECK_NIL:
  1123. d.decodeValueNoCheckNil(rvv, valFn)
  1124. if doMapSet {
  1125. if callFnRvk {
  1126. s = d.string(kstr2bs)
  1127. if ktypeIsString {
  1128. rvSetString(rvk, s)
  1129. } else { // ktypeIsIntf
  1130. rvSetIntf(rvk, rv4istr(s))
  1131. }
  1132. }
  1133. mapSet(rv, rvk, rvv, kfast, visindirect, visref)
  1134. }
  1135. }
  1136. d.mapEnd()
  1137. }
  1138. // Decoder reads and decodes an object from an input stream in a supported format.
  1139. //
  1140. // Decoder is NOT safe for concurrent use i.e. a Decoder cannot be used
  1141. // concurrently in multiple goroutines.
  1142. //
  1143. // However, as Decoder could be allocation heavy to initialize, a Reset method is provided
  1144. // so its state can be reused to decode new input streams repeatedly.
  1145. // This is the idiomatic way to use.
  1146. type Decoder struct {
  1147. panicHdl
  1148. d decDriver
  1149. // cache the mapTypeId and sliceTypeId for faster comparisons
  1150. mtid uintptr
  1151. stid uintptr
  1152. h *BasicHandle
  1153. blist bytesFreelist
  1154. // ---- cpu cache line boundary?
  1155. decRd
  1156. // ---- cpu cache line boundary?
  1157. n fauxUnion
  1158. hh Handle
  1159. err error
  1160. perType decPerType
  1161. // used for interning strings
  1162. is internerMap
  1163. // ---- cpu cache line boundary?
  1164. // ---- writable fields during execution --- *try* to keep in sep cache line
  1165. maxdepth int16
  1166. depth int16
  1167. // Extensions can call Decode() within a current Decode() call.
  1168. // We need to know when the top level Decode() call returns,
  1169. // so we can decide whether to Release() or not.
  1170. calls uint16 // what depth in mustDecode are we in now.
  1171. c containerState
  1172. decByteState
  1173. // b is an always-available scratch buffer used by Decoder and decDrivers.
  1174. // By being always-available, it can be used for one-off things without
  1175. // having to get from freelist, use, and return back to freelist.
  1176. b [decScratchByteArrayLen]byte
  1177. }
  1178. // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader.
  1179. //
  1180. // For efficiency, Users are encouraged to configure ReaderBufferSize on the handle
  1181. // OR pass in a memory buffered reader (eg bufio.Reader, bytes.Buffer).
  1182. func NewDecoder(r io.Reader, h Handle) *Decoder {
  1183. d := h.newDecDriver().decoder()
  1184. if r != nil {
  1185. d.Reset(r)
  1186. }
  1187. return d
  1188. }
  1189. // NewDecoderBytes returns a Decoder which efficiently decodes directly
  1190. // from a byte slice with zero copying.
  1191. func NewDecoderBytes(in []byte, h Handle) *Decoder {
  1192. d := h.newDecDriver().decoder()
  1193. if in != nil {
  1194. d.ResetBytes(in)
  1195. }
  1196. return d
  1197. }
  1198. // NewDecoderString returns a Decoder which efficiently decodes directly
  1199. // from a string with zero copying.
  1200. //
  1201. // It is a convenience function that calls NewDecoderBytes with a
  1202. // []byte view into the string.
  1203. //
  1204. // This can be an efficient zero-copy if using default mode i.e. without codec.safe tag.
  1205. func NewDecoderString(s string, h Handle) *Decoder {
  1206. return NewDecoderBytes(bytesView(s), h)
  1207. }
  1208. func (d *Decoder) r() *decRd {
  1209. return &d.decRd
  1210. }
  1211. func (d *Decoder) init(h Handle) {
  1212. initHandle(h)
  1213. d.cbreak = d.js || d.cbor
  1214. d.bytes = true
  1215. d.err = errDecoderNotInitialized
  1216. d.h = h.getBasicHandle()
  1217. d.hh = h
  1218. d.be = h.isBinary()
  1219. if d.h.InternString && d.is == nil {
  1220. d.is.init()
  1221. }
  1222. // NOTE: do not initialize d.n here. It is lazily initialized in d.naked()
  1223. }
  1224. func (d *Decoder) resetCommon() {
  1225. d.d.reset()
  1226. d.err = nil
  1227. d.c = 0
  1228. d.decByteState = decByteStateNone
  1229. d.depth = 0
  1230. d.calls = 0
  1231. // reset all things which were cached from the Handle, but could change
  1232. d.maxdepth = decDefMaxDepth
  1233. if d.h.MaxDepth > 0 {
  1234. d.maxdepth = d.h.MaxDepth
  1235. }
  1236. d.mtid = 0
  1237. d.stid = 0
  1238. d.mtr = false
  1239. d.str = false
  1240. if d.h.MapType != nil {
  1241. d.mtid = rt2id(d.h.MapType)
  1242. d.mtr = fastpathAvIndex(d.mtid) != -1
  1243. }
  1244. if d.h.SliceType != nil {
  1245. d.stid = rt2id(d.h.SliceType)
  1246. d.str = fastpathAvIndex(d.stid) != -1
  1247. }
  1248. }
  1249. // Reset the Decoder with a new Reader to decode from,
  1250. // clearing all state from last run(s).
  1251. func (d *Decoder) Reset(r io.Reader) {
  1252. if r == nil {
  1253. r = &eofReader
  1254. }
  1255. d.bytes = false
  1256. if d.ri == nil {
  1257. d.ri = new(ioDecReader)
  1258. }
  1259. d.ri.reset(r, d.h.ReaderBufferSize, &d.blist)
  1260. d.decReader = d.ri
  1261. d.resetCommon()
  1262. }
  1263. // ResetBytes resets the Decoder with a new []byte to decode from,
  1264. // clearing all state from last run(s).
  1265. func (d *Decoder) ResetBytes(in []byte) {
  1266. if in == nil {
  1267. in = []byte{}
  1268. }
  1269. d.bytes = true
  1270. d.decReader = &d.rb
  1271. d.rb.reset(in)
  1272. d.resetCommon()
  1273. }
  1274. // ResetString resets the Decoder with a new string to decode from,
  1275. // clearing all state from last run(s).
  1276. //
  1277. // It is a convenience function that calls ResetBytes with a
  1278. // []byte view into the string.
  1279. //
  1280. // This can be an efficient zero-copy if using default mode i.e. without codec.safe tag.
  1281. func (d *Decoder) ResetString(s string) {
  1282. d.ResetBytes(bytesView(s))
  1283. }
  1284. func (d *Decoder) naked() *fauxUnion {
  1285. return &d.n
  1286. }
  1287. // Decode decodes the stream from reader and stores the result in the
  1288. // value pointed to by v. v cannot be a nil pointer. v can also be
  1289. // a reflect.Value of a pointer.
  1290. //
  1291. // Note that a pointer to a nil interface is not a nil pointer.
  1292. // If you do not know what type of stream it is, pass in a pointer to a nil interface.
  1293. // We will decode and store a value in that nil interface.
  1294. //
  1295. // Sample usages:
  1296. //
  1297. // // Decoding into a non-nil typed value
  1298. // var f float32
  1299. // err = codec.NewDecoder(r, handle).Decode(&f)
  1300. //
  1301. // // Decoding into nil interface
  1302. // var v interface{}
  1303. // dec := codec.NewDecoder(r, handle)
  1304. // err = dec.Decode(&v)
  1305. //
  1306. // When decoding into a nil interface{}, we will decode into an appropriate value based
  1307. // on the contents of the stream:
  1308. // - Numbers are decoded as float64, int64 or uint64.
  1309. // - Other values are decoded appropriately depending on the type:
  1310. // bool, string, []byte, time.Time, etc
  1311. // - Extensions are decoded as RawExt (if no ext function registered for the tag)
  1312. //
  1313. // Configurations exist on the Handle to override defaults
  1314. // (e.g. for MapType, SliceType and how to decode raw bytes).
  1315. //
  1316. // When decoding into a non-nil interface{} value, the mode of encoding is based on the
  1317. // type of the value. When a value is seen:
  1318. // - If an extension is registered for it, call that extension function
  1319. // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error
  1320. // - Else decode it based on its reflect.Kind
  1321. //
  1322. // There are some special rules when decoding into containers (slice/array/map/struct).
  1323. // Decode will typically use the stream contents to UPDATE the container i.e. the values
  1324. // in these containers will not be zero'ed before decoding.
  1325. // - A map can be decoded from a stream map, by updating matching keys.
  1326. // - A slice can be decoded from a stream array,
  1327. // by updating the first n elements, where n is length of the stream.
  1328. // - A slice can be decoded from a stream map, by decoding as if
  1329. // it contains a sequence of key-value pairs.
  1330. // - A struct can be decoded from a stream map, by updating matching fields.
  1331. // - A struct can be decoded from a stream array,
  1332. // by updating fields as they occur in the struct (by index).
  1333. //
  1334. // This in-place update maintains consistency in the decoding philosophy (i.e. we ALWAYS update
  1335. // in place by default). However, the consequence of this is that values in slices or maps
  1336. // which are not zero'ed before hand, will have part of the prior values in place after decode
  1337. // if the stream doesn't contain an update for those parts.
  1338. //
  1339. // This in-place update can be disabled by configuring the MapValueReset and SliceElementReset
  1340. // decode options available on every handle.
  1341. //
  1342. // Furthermore, when decoding a stream map or array with length of 0 into a nil map or slice,
  1343. // we reset the destination map or slice to a zero-length value.
  1344. //
  1345. // However, when decoding a stream nil, we reset the destination container
  1346. // to its "zero" value (e.g. nil for slice/map, etc).
  1347. //
  1348. // Note: we allow nil values in the stream anywhere except for map keys.
  1349. // A nil value in the encoded stream where a map key is expected is treated as an error.
  1350. func (d *Decoder) Decode(v interface{}) (err error) {
  1351. // tried to use closure, as runtime optimizes defer with no params.
  1352. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  1353. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  1354. if !debugging {
  1355. defer func() {
  1356. if x := recover(); x != nil {
  1357. panicValToErr(d, x, &d.err)
  1358. err = d.err
  1359. }
  1360. }()
  1361. }
  1362. d.MustDecode(v)
  1363. return
  1364. }
  1365. // MustDecode is like Decode, but panics if unable to Decode.
  1366. //
  1367. // Note: This provides insight to the code location that triggered the error.
  1368. func (d *Decoder) MustDecode(v interface{}) {
  1369. halt.onerror(d.err)
  1370. if d.hh == nil {
  1371. halt.onerror(errNoFormatHandle)
  1372. }
  1373. // Top-level: v is a pointer and not nil.
  1374. d.calls++
  1375. d.decode(v)
  1376. d.calls--
  1377. }
  1378. // Release releases shared (pooled) resources.
  1379. //
  1380. // It is important to call Release() when done with a Decoder, so those resources
  1381. // are released instantly for use by subsequently created Decoders.
  1382. //
  1383. // By default, Release() is automatically called unless the option ExplicitRelease is set.
  1384. //
  1385. // Deprecated: Release is a no-op as pooled resources are not used with an Decoder.
  1386. // This method is kept for compatibility reasons only.
  1387. func (d *Decoder) Release() {
  1388. }
  1389. func (d *Decoder) swallow() {
  1390. d.d.nextValueBytes(nil)
  1391. }
  1392. func (d *Decoder) swallowErr() (err error) {
  1393. if !debugging {
  1394. defer func() {
  1395. if x := recover(); x != nil {
  1396. panicValToErr(d, x, &err)
  1397. }
  1398. }()
  1399. }
  1400. d.swallow()
  1401. return
  1402. }
  1403. func setZero(iv interface{}) {
  1404. if iv == nil {
  1405. return
  1406. }
  1407. rv, ok := isNil(iv)
  1408. if ok {
  1409. return
  1410. }
  1411. // var canDecode bool
  1412. switch v := iv.(type) {
  1413. case *string:
  1414. *v = ""
  1415. case *bool:
  1416. *v = false
  1417. case *int:
  1418. *v = 0
  1419. case *int8:
  1420. *v = 0
  1421. case *int16:
  1422. *v = 0
  1423. case *int32:
  1424. *v = 0
  1425. case *int64:
  1426. *v = 0
  1427. case *uint:
  1428. *v = 0
  1429. case *uint8:
  1430. *v = 0
  1431. case *uint16:
  1432. *v = 0
  1433. case *uint32:
  1434. *v = 0
  1435. case *uint64:
  1436. *v = 0
  1437. case *float32:
  1438. *v = 0
  1439. case *float64:
  1440. *v = 0
  1441. case *complex64:
  1442. *v = 0
  1443. case *complex128:
  1444. *v = 0
  1445. case *[]byte:
  1446. *v = nil
  1447. case *Raw:
  1448. *v = nil
  1449. case *time.Time:
  1450. *v = time.Time{}
  1451. case reflect.Value:
  1452. decSetNonNilRV2Zero(v)
  1453. default:
  1454. if !fastpathDecodeSetZeroTypeSwitch(iv) {
  1455. decSetNonNilRV2Zero(rv)
  1456. }
  1457. }
  1458. }
  1459. // decSetNonNilRV2Zero will set the non-nil value to its zero value.
  1460. func decSetNonNilRV2Zero(v reflect.Value) {
  1461. // If not decodeable (settable), we do not touch it.
  1462. // We considered empty'ing it if not decodeable e.g.
  1463. // - if chan, drain it
  1464. // - if map, clear it
  1465. // - if slice or array, zero all elements up to len
  1466. //
  1467. // However, we decided instead that we either will set the
  1468. // whole value to the zero value, or leave AS IS.
  1469. k := v.Kind()
  1470. if k == reflect.Interface {
  1471. decSetNonNilRV2Zero4Intf(v)
  1472. } else if k == reflect.Ptr {
  1473. decSetNonNilRV2Zero4Ptr(v)
  1474. } else if v.CanSet() {
  1475. rvSetDirectZero(v)
  1476. }
  1477. }
  1478. func decSetNonNilRV2Zero4Ptr(v reflect.Value) {
  1479. ve := v.Elem()
  1480. if ve.CanSet() {
  1481. rvSetZero(ve) // we can have a pointer to an interface
  1482. } else if v.CanSet() {
  1483. rvSetZero(v)
  1484. }
  1485. }
  1486. func decSetNonNilRV2Zero4Intf(v reflect.Value) {
  1487. ve := v.Elem()
  1488. if ve.CanSet() {
  1489. rvSetDirectZero(ve) // interfaces always have element as a non-interface
  1490. } else if v.CanSet() {
  1491. rvSetZero(v)
  1492. }
  1493. }
  1494. func (d *Decoder) decode(iv interface{}) {
  1495. // a switch with only concrete types can be optimized.
  1496. // consequently, we deal with nil and interfaces outside the switch.
  1497. if iv == nil {
  1498. d.onerror(errCannotDecodeIntoNil)
  1499. }
  1500. switch v := iv.(type) {
  1501. // case nil:
  1502. // case Selfer:
  1503. case reflect.Value:
  1504. if x, _ := isDecodeable(v); !x {
  1505. d.haltAsNotDecodeable(v)
  1506. }
  1507. d.decodeValue(v, nil)
  1508. case *string:
  1509. *v = d.stringZC(d.d.DecodeStringAsBytes())
  1510. case *bool:
  1511. *v = d.d.DecodeBool()
  1512. case *int:
  1513. *v = int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize))
  1514. case *int8:
  1515. *v = int8(chkOvf.IntV(d.d.DecodeInt64(), 8))
  1516. case *int16:
  1517. *v = int16(chkOvf.IntV(d.d.DecodeInt64(), 16))
  1518. case *int32:
  1519. *v = int32(chkOvf.IntV(d.d.DecodeInt64(), 32))
  1520. case *int64:
  1521. *v = d.d.DecodeInt64()
  1522. case *uint:
  1523. *v = uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize))
  1524. case *uint8:
  1525. *v = uint8(chkOvf.UintV(d.d.DecodeUint64(), 8))
  1526. case *uint16:
  1527. *v = uint16(chkOvf.UintV(d.d.DecodeUint64(), 16))
  1528. case *uint32:
  1529. *v = uint32(chkOvf.UintV(d.d.DecodeUint64(), 32))
  1530. case *uint64:
  1531. *v = d.d.DecodeUint64()
  1532. case *float32:
  1533. *v = d.decodeFloat32()
  1534. case *float64:
  1535. *v = d.d.DecodeFloat64()
  1536. case *complex64:
  1537. *v = complex(d.decodeFloat32(), 0)
  1538. case *complex128:
  1539. *v = complex(d.d.DecodeFloat64(), 0)
  1540. case *[]byte:
  1541. *v = d.decodeBytesInto(*v)
  1542. case []byte:
  1543. // not addressable byte slice, so do not decode into it past the length
  1544. b := d.decodeBytesInto(v[:len(v):len(v)])
  1545. if !(len(b) > 0 && len(b) == len(v) && &b[0] == &v[0]) { // not same slice
  1546. copy(v, b)
  1547. }
  1548. case *time.Time:
  1549. *v = d.d.DecodeTime()
  1550. case *Raw:
  1551. *v = d.rawBytes()
  1552. case *interface{}:
  1553. d.decodeValue(rv4iptr(v), nil)
  1554. default:
  1555. // we can't check non-predefined types, as they might be a Selfer or extension.
  1556. if skipFastpathTypeSwitchInDirectCall || !fastpathDecodeTypeSwitch(iv, d) {
  1557. v := reflect.ValueOf(iv)
  1558. if x, _ := isDecodeable(v); !x {
  1559. d.haltAsNotDecodeable(v)
  1560. }
  1561. d.decodeValue(v, nil)
  1562. }
  1563. }
  1564. }
  1565. // decodeValue MUST be called by the actual value we want to decode into,
  1566. // not its addr or a reference to it.
  1567. //
  1568. // This way, we know if it is itself a pointer, and can handle nil in
  1569. // the stream effectively.
  1570. //
  1571. // Note that decodeValue will handle nil in the stream early, so that the
  1572. // subsequent calls i.e. kXXX methods, etc do not have to handle it themselves.
  1573. func (d *Decoder) decodeValue(rv reflect.Value, fn *codecFn) {
  1574. if d.d.TryNil() {
  1575. decSetNonNilRV2Zero(rv)
  1576. return
  1577. }
  1578. d.decodeValueNoCheckNil(rv, fn)
  1579. }
  1580. func (d *Decoder) decodeValueNoCheckNil(rv reflect.Value, fn *codecFn) {
  1581. // If stream is not containing a nil value, then we can deref to the base
  1582. // non-pointer value, and decode into that.
  1583. var rvp reflect.Value
  1584. var rvpValid bool
  1585. PTR:
  1586. if rv.Kind() == reflect.Ptr {
  1587. rvpValid = true
  1588. if rvIsNil(rv) {
  1589. rvSetDirect(rv, reflect.New(rv.Type().Elem()))
  1590. }
  1591. rvp = rv
  1592. rv = rv.Elem()
  1593. goto PTR
  1594. }
  1595. if fn == nil {
  1596. fn = d.h.fn(rv.Type())
  1597. }
  1598. if fn.i.addrD {
  1599. if rvpValid {
  1600. rv = rvp
  1601. } else if rv.CanAddr() {
  1602. rv = rvAddr(rv, fn.i.ti.ptr)
  1603. } else if fn.i.addrDf {
  1604. d.errorf("cannot decode into a non-pointer value")
  1605. }
  1606. }
  1607. fn.fd(d, &fn.i, rv)
  1608. }
  1609. func (d *Decoder) structFieldNotFound(index int, rvkencname string) {
  1610. // Note: rvkencname is used only if there is an error, to pass into d.errorf.
  1611. // Consequently, it is ok to pass in a stringView
  1612. // Since rvkencname may be a stringView, do NOT pass it to another function.
  1613. if d.h.ErrorIfNoField {
  1614. if index >= 0 {
  1615. d.errorf("no matching struct field found when decoding stream array at index %v", index)
  1616. } else if rvkencname != "" {
  1617. d.errorf("no matching struct field found when decoding stream map with key " + rvkencname)
  1618. }
  1619. }
  1620. d.swallow()
  1621. }
  1622. func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) {
  1623. if d.h.ErrorIfNoArrayExpand {
  1624. d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen)
  1625. }
  1626. }
  1627. func (d *Decoder) haltAsNotDecodeable(rv reflect.Value) {
  1628. if !rv.IsValid() {
  1629. d.onerror(errCannotDecodeIntoNil)
  1630. }
  1631. // check if an interface can be retrieved, before grabbing an interface
  1632. if !rv.CanInterface() {
  1633. d.errorf("cannot decode into a value without an interface: %v", rv)
  1634. }
  1635. d.errorf("cannot decode into value of kind: %v, %#v", rv.Kind(), rv2i(rv))
  1636. }
  1637. func (d *Decoder) depthIncr() {
  1638. d.depth++
  1639. if d.depth >= d.maxdepth {
  1640. d.onerror(errMaxDepthExceeded)
  1641. }
  1642. }
  1643. func (d *Decoder) depthDecr() {
  1644. d.depth--
  1645. }
  1646. // Possibly get an interned version of a string, iff InternString=true and decoding a map key.
  1647. //
  1648. // This should mostly be used for map keys, where the key type is string.
  1649. // This is because keys of a map/struct are typically reused across many objects.
  1650. func (d *Decoder) string(v []byte) (s string) {
  1651. if d.is == nil || d.c != containerMapKey || len(v) < 2 || len(v) > internMaxStrLen {
  1652. return string(v)
  1653. }
  1654. return d.is.string(v)
  1655. }
  1656. func (d *Decoder) zerocopy() bool {
  1657. return d.bytes && d.h.ZeroCopy
  1658. }
  1659. // decodeBytesInto is a convenience delegate function to decDriver.DecodeBytes.
  1660. // It ensures that `in` is not a nil byte, before calling decDriver.DecodeBytes,
  1661. // as decDriver.DecodeBytes treats a nil as a hint to use its internal scratch buffer.
  1662. func (d *Decoder) decodeBytesInto(in []byte) (v []byte) {
  1663. if in == nil {
  1664. in = []byte{}
  1665. }
  1666. return d.d.DecodeBytes(in)
  1667. }
  1668. func (d *Decoder) rawBytes() (v []byte) {
  1669. // ensure that this is not a view into the bytes
  1670. // i.e. if necessary, make new copy always.
  1671. v = d.d.nextValueBytes([]byte{})
  1672. if d.bytes && !d.h.ZeroCopy {
  1673. vv := make([]byte, len(v))
  1674. copy(vv, v) // using copy here triggers make+copy optimization eliding memclr
  1675. v = vv
  1676. }
  1677. return
  1678. }
  1679. func (d *Decoder) wrapErr(v error, err *error) {
  1680. *err = wrapCodecErr(v, d.hh.Name(), d.NumBytesRead(), false)
  1681. }
  1682. // NumBytesRead returns the number of bytes read
  1683. func (d *Decoder) NumBytesRead() int {
  1684. return int(d.r().numread())
  1685. }
  1686. // decodeFloat32 will delegate to an appropriate DecodeFloat32 implementation (if exists),
  1687. // else if will call DecodeFloat64 and ensure the value doesn't overflow.
  1688. //
  1689. // Note that we return float64 to reduce unnecessary conversions
  1690. func (d *Decoder) decodeFloat32() float32 {
  1691. if d.js {
  1692. return d.jsondriver().DecodeFloat32() // custom implementation for 32-bit
  1693. }
  1694. return float32(chkOvf.Float32V(d.d.DecodeFloat64()))
  1695. }
  1696. // ---- container tracking
  1697. // Note: We update the .c after calling the callback.
  1698. // This way, the callback can know what the last status was.
  1699. // MARKER: do not call mapEnd if mapStart returns containerLenNil.
  1700. // MARKER: optimize decoding since all formats do not truly support all decDriver'ish operations.
  1701. // - Read(Map|Array)Start is only supported by all formats.
  1702. // - CheckBreak is only supported by json and cbor.
  1703. // - Read(Map|Array)End is only supported by json.
  1704. // - Read(Map|Array)Elem(Kay|Value) is only supported by json.
  1705. // Honor these in the code, to reduce the number of interface calls (even if empty).
  1706. func (d *Decoder) checkBreak() (v bool) {
  1707. // MARKER: jsonDecDriver.CheckBreak() cannot be inlined (over budget inlining cost).
  1708. // Consequently, there's no benefit in incurring the cost of this wrapping function.
  1709. // It is faster to just call the interface method directly.
  1710. // if d.js {
  1711. // return d.jsondriver().CheckBreak()
  1712. // }
  1713. // if d.cbor {
  1714. // return d.cbordriver().CheckBreak()
  1715. // }
  1716. if d.cbreak {
  1717. v = d.d.CheckBreak()
  1718. }
  1719. return
  1720. }
  1721. func (d *Decoder) containerNext(j, containerLen int, hasLen bool) bool {
  1722. // MARKER: keep in sync with gen-helper.go.tmpl
  1723. // return (hasLen && j < containerLen) || !(hasLen || slh.d.checkBreak())
  1724. if hasLen {
  1725. return j < containerLen
  1726. }
  1727. return !d.checkBreak()
  1728. }
  1729. func (d *Decoder) mapStart(v int) int {
  1730. if v != containerLenNil {
  1731. d.depthIncr()
  1732. d.c = containerMapStart
  1733. }
  1734. return v
  1735. }
  1736. func (d *Decoder) mapElemKey() {
  1737. if d.js {
  1738. d.jsondriver().ReadMapElemKey()
  1739. }
  1740. d.c = containerMapKey
  1741. }
  1742. func (d *Decoder) mapElemValue() {
  1743. if d.js {
  1744. d.jsondriver().ReadMapElemValue()
  1745. }
  1746. d.c = containerMapValue
  1747. }
  1748. func (d *Decoder) mapEnd() {
  1749. if d.js {
  1750. d.jsondriver().ReadMapEnd()
  1751. }
  1752. // d.d.ReadMapEnd()
  1753. d.depthDecr()
  1754. d.c = 0
  1755. }
  1756. func (d *Decoder) arrayStart(v int) int {
  1757. if v != containerLenNil {
  1758. d.depthIncr()
  1759. d.c = containerArrayStart
  1760. }
  1761. return v
  1762. }
  1763. func (d *Decoder) arrayElem() {
  1764. if d.js {
  1765. d.jsondriver().ReadArrayElem()
  1766. }
  1767. d.c = containerArrayElem
  1768. }
  1769. func (d *Decoder) arrayEnd() {
  1770. if d.js {
  1771. d.jsondriver().ReadArrayEnd()
  1772. }
  1773. // d.d.ReadArrayEnd()
  1774. d.depthDecr()
  1775. d.c = 0
  1776. }
  1777. func (d *Decoder) interfaceExtConvertAndDecode(v interface{}, ext InterfaceExt) {
  1778. // var v interface{} = ext.ConvertExt(rv)
  1779. // d.d.decode(&v)
  1780. // ext.UpdateExt(rv, v)
  1781. // assume v is a pointer:
  1782. // - if struct|array, pass as is to ConvertExt
  1783. // - else make it non-addressable and pass to ConvertExt
  1784. // - make return value from ConvertExt addressable
  1785. // - decode into it
  1786. // - return the interface for passing into UpdateExt.
  1787. // - interface should be a pointer if struct|array, else a value
  1788. var s interface{}
  1789. rv := reflect.ValueOf(v)
  1790. rv2 := rv.Elem()
  1791. rvk := rv2.Kind()
  1792. if rvk == reflect.Struct || rvk == reflect.Array {
  1793. s = ext.ConvertExt(v)
  1794. } else {
  1795. s = ext.ConvertExt(rv2i(rv2))
  1796. }
  1797. rv = reflect.ValueOf(s)
  1798. // We cannot use isDecodeable here, as the value converted may be nil,
  1799. // or it may not be nil but is not addressable and thus we cannot extend it, etc.
  1800. // Instead, we just ensure that the value is addressable.
  1801. if !rv.CanAddr() {
  1802. rvk = rv.Kind()
  1803. rv2 = d.oneShotAddrRV(rv.Type(), rvk)
  1804. if rvk == reflect.Interface {
  1805. rvSetIntf(rv2, rv)
  1806. } else {
  1807. rvSetDirect(rv2, rv)
  1808. }
  1809. rv = rv2
  1810. }
  1811. d.decodeValue(rv, nil)
  1812. ext.UpdateExt(v, rv2i(rv))
  1813. }
  1814. func (d *Decoder) sideDecode(v interface{}, basetype reflect.Type, bs []byte) {
  1815. // NewDecoderBytes(bs, d.hh).decodeValue(baseRV(v), d.h.fnNoExt(basetype))
  1816. defer func(rb bytesDecReader, bytes bool,
  1817. c containerState, dbs decByteState, depth int16, r decReader, state interface{}) {
  1818. d.rb = rb
  1819. d.bytes = bytes
  1820. d.c = c
  1821. d.decByteState = dbs
  1822. d.depth = depth
  1823. d.decReader = r
  1824. d.d.restoreState(state)
  1825. }(d.rb, d.bytes, d.c, d.decByteState, d.depth, d.decReader, d.d.captureState())
  1826. // d.rb.reset(in)
  1827. d.rb = bytesDecReader{bs[:len(bs):len(bs)], 0}
  1828. d.bytes = true
  1829. d.decReader = &d.rb
  1830. d.d.resetState()
  1831. d.c = 0
  1832. d.decByteState = decByteStateNone
  1833. d.depth = 0
  1834. // must call using fnNoExt
  1835. d.decodeValue(baseRV(v), d.h.fnNoExt(basetype))
  1836. }
  1837. func (d *Decoder) fauxUnionReadRawBytes(asString bool) {
  1838. if asString || d.h.RawToString {
  1839. d.n.v = valueTypeString
  1840. // fauxUnion is only used within DecodeNaked calls; consequently, we should try to intern.
  1841. d.n.s = d.stringZC(d.d.DecodeBytes(nil))
  1842. } else {
  1843. d.n.v = valueTypeBytes
  1844. d.n.l = d.d.DecodeBytes([]byte{})
  1845. }
  1846. }
  1847. func (d *Decoder) oneShotAddrRV(rvt reflect.Type, rvk reflect.Kind) reflect.Value {
  1848. if decUseTransient &&
  1849. (numBoolStrSliceBitset.isset(byte(rvk)) ||
  1850. ((rvk == reflect.Struct || rvk == reflect.Array) &&
  1851. d.h.getTypeInfo(rt2id(rvt), rvt).flagCanTransient)) {
  1852. return d.perType.TransientAddrK(rvt, rvk)
  1853. }
  1854. return rvZeroAddrK(rvt, rvk)
  1855. }
  1856. // --------------------------------------------------
  1857. // decSliceHelper assists when decoding into a slice, from a map or an array in the stream.
  1858. // A slice can be set from a map or array in stream. This supports the MapBySlice interface.
  1859. //
  1860. // Note: if IsNil, do not call ElemContainerState.
  1861. type decSliceHelper struct {
  1862. d *Decoder
  1863. ct valueType
  1864. Array bool
  1865. IsNil bool
  1866. }
  1867. func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) {
  1868. x.ct = d.d.ContainerType()
  1869. x.d = d
  1870. switch x.ct {
  1871. case valueTypeNil:
  1872. x.IsNil = true
  1873. case valueTypeArray:
  1874. x.Array = true
  1875. clen = d.arrayStart(d.d.ReadArrayStart())
  1876. case valueTypeMap:
  1877. clen = d.mapStart(d.d.ReadMapStart())
  1878. clen += clen
  1879. default:
  1880. d.errorf("only encoded map or array can be decoded into a slice (%d)", x.ct)
  1881. }
  1882. return
  1883. }
  1884. func (x decSliceHelper) End() {
  1885. if x.IsNil {
  1886. } else if x.Array {
  1887. x.d.arrayEnd()
  1888. } else {
  1889. x.d.mapEnd()
  1890. }
  1891. }
  1892. func (x decSliceHelper) ElemContainerState(index int) {
  1893. // Note: if isnil, clen=0, so we never call into ElemContainerState
  1894. if x.Array {
  1895. x.d.arrayElem()
  1896. } else if index&1 == 0 { // index%2 == 0 {
  1897. x.d.mapElemKey()
  1898. } else {
  1899. x.d.mapElemValue()
  1900. }
  1901. }
  1902. func (x decSliceHelper) arrayCannotExpand(hasLen bool, lenv, j, containerLenS int) {
  1903. x.d.arrayCannotExpand(lenv, j+1)
  1904. // drain completely and return
  1905. x.ElemContainerState(j)
  1906. x.d.swallow()
  1907. j++
  1908. for ; x.d.containerNext(j, containerLenS, hasLen); j++ {
  1909. x.ElemContainerState(j)
  1910. x.d.swallow()
  1911. }
  1912. x.End()
  1913. }
  1914. // decNextValueBytesHelper helps with NextValueBytes calls.
  1915. //
  1916. // Typical usage:
  1917. // - each Handle's decDriver will implement a high level nextValueBytes,
  1918. // which will track the current cursor, delegate to a nextValueBytesR
  1919. // method, and then potentially call bytesRdV at the end.
  1920. //
  1921. // See simple.go for typical usage model.
  1922. type decNextValueBytesHelper struct {
  1923. d *Decoder
  1924. }
  1925. func (x decNextValueBytesHelper) append1(v *[]byte, b byte) {
  1926. if *v != nil && !x.d.bytes {
  1927. *v = append(*v, b)
  1928. }
  1929. }
  1930. func (x decNextValueBytesHelper) appendN(v *[]byte, b ...byte) {
  1931. if *v != nil && !x.d.bytes {
  1932. *v = append(*v, b...)
  1933. }
  1934. }
  1935. func (x decNextValueBytesHelper) appendS(v *[]byte, b string) {
  1936. if *v != nil && !x.d.bytes {
  1937. *v = append(*v, b...)
  1938. }
  1939. }
  1940. func (x decNextValueBytesHelper) bytesRdV(v *[]byte, startpos uint) {
  1941. if x.d.bytes {
  1942. *v = x.d.rb.b[startpos:x.d.rb.c]
  1943. }
  1944. }
  1945. // decNegintPosintFloatNumberHelper is used for formats that are binary
  1946. // and have distinct ways of storing positive integers vs negative integers
  1947. // vs floats, which are uniquely identified by the byte descriptor.
  1948. //
  1949. // Currently, these formats are binc, cbor and simple.
  1950. type decNegintPosintFloatNumberHelper struct {
  1951. d *Decoder
  1952. }
  1953. func (x decNegintPosintFloatNumberHelper) uint64(ui uint64, neg, ok bool) uint64 {
  1954. if ok && !neg {
  1955. return ui
  1956. }
  1957. return x.uint64TryFloat(ok)
  1958. }
  1959. func (x decNegintPosintFloatNumberHelper) uint64TryFloat(ok bool) (ui uint64) {
  1960. if ok { // neg = true
  1961. x.d.errorf("assigning negative signed value to unsigned type")
  1962. }
  1963. f, ok := x.d.d.decFloat()
  1964. if ok && f >= 0 && noFrac64(math.Float64bits(f)) {
  1965. ui = uint64(f)
  1966. } else {
  1967. x.d.errorf("invalid number loading uint64, with descriptor: %v", x.d.d.descBd())
  1968. }
  1969. return ui
  1970. }
  1971. func decNegintPosintFloatNumberHelperInt64v(ui uint64, neg, incrIfNeg bool) (i int64) {
  1972. if neg && incrIfNeg {
  1973. ui++
  1974. }
  1975. i = chkOvf.SignedIntV(ui)
  1976. if neg {
  1977. i = -i
  1978. }
  1979. return
  1980. }
  1981. func (x decNegintPosintFloatNumberHelper) int64(ui uint64, neg, ok bool) (i int64) {
  1982. if ok {
  1983. return decNegintPosintFloatNumberHelperInt64v(ui, neg, x.d.cbor)
  1984. }
  1985. // return x.int64TryFloat()
  1986. // }
  1987. // func (x decNegintPosintFloatNumberHelper) int64TryFloat() (i int64) {
  1988. f, ok := x.d.d.decFloat()
  1989. if ok && noFrac64(math.Float64bits(f)) {
  1990. i = int64(f)
  1991. } else {
  1992. x.d.errorf("invalid number loading uint64, with descriptor: %v", x.d.d.descBd())
  1993. }
  1994. return
  1995. }
  1996. func (x decNegintPosintFloatNumberHelper) float64(f float64, ok bool) float64 {
  1997. if ok {
  1998. return f
  1999. }
  2000. return x.float64TryInteger()
  2001. }
  2002. func (x decNegintPosintFloatNumberHelper) float64TryInteger() float64 {
  2003. ui, neg, ok := x.d.d.decInteger()
  2004. if !ok {
  2005. x.d.errorf("invalid descriptor for float: %v", x.d.d.descBd())
  2006. }
  2007. return float64(decNegintPosintFloatNumberHelperInt64v(ui, neg, x.d.cbor))
  2008. }
  2009. // isDecodeable checks if value can be decoded into
  2010. //
  2011. // decode can take any reflect.Value that is a inherently addressable i.e.
  2012. // - non-nil chan (we will SEND to it)
  2013. // - non-nil slice (we will set its elements)
  2014. // - non-nil map (we will put into it)
  2015. // - non-nil pointer (we can "update" it)
  2016. // - func: no
  2017. // - interface: no
  2018. // - array: if canAddr=true
  2019. // - any other value pointer: if canAddr=true
  2020. func isDecodeable(rv reflect.Value) (canDecode bool, reason decNotDecodeableReason) {
  2021. switch rv.Kind() {
  2022. case reflect.Ptr, reflect.Slice, reflect.Chan, reflect.Map:
  2023. canDecode = !rvIsNil(rv)
  2024. reason = decNotDecodeableReasonNilReference
  2025. case reflect.Func, reflect.Interface, reflect.Invalid, reflect.UnsafePointer:
  2026. reason = decNotDecodeableReasonBadKind
  2027. default:
  2028. canDecode = rv.CanAddr()
  2029. reason = decNotDecodeableReasonNonAddrValue
  2030. }
  2031. return
  2032. }
  2033. func decByteSlice(r *decRd, clen, maxInitLen int, bs []byte) (bsOut []byte) {
  2034. if clen <= 0 {
  2035. bsOut = zeroByteSlice
  2036. } else if cap(bs) >= clen {
  2037. bsOut = bs[:clen]
  2038. r.readb(bsOut)
  2039. } else {
  2040. var len2 int
  2041. for len2 < clen {
  2042. len3 := decInferLen(clen-len2, maxInitLen, 1)
  2043. bs3 := bsOut
  2044. bsOut = make([]byte, len2+len3)
  2045. copy(bsOut, bs3)
  2046. r.readb(bsOut[len2:])
  2047. len2 += len3
  2048. }
  2049. }
  2050. return
  2051. }
  2052. // decInferLen will infer a sensible length, given the following:
  2053. // - clen: length wanted.
  2054. // - maxlen: max length to be returned.
  2055. // if <= 0, it is unset, and we infer it based on the unit size
  2056. // - unit: number of bytes for each element of the collection
  2057. func decInferLen(clen, maxlen, unit int) int {
  2058. // anecdotal testing showed increase in allocation with map length of 16.
  2059. // We saw same typical alloc from 0-8, then a 20% increase at 16.
  2060. // Thus, we set it to 8.
  2061. const (
  2062. minLenIfUnset = 8
  2063. maxMem = 256 * 1024 // 256Kb Memory
  2064. )
  2065. // handle when maxlen is not set i.e. <= 0
  2066. // clen==0: use 0
  2067. // maxlen<=0, clen<0: use default
  2068. // maxlen> 0, clen<0: use default
  2069. // maxlen<=0, clen>0: infer maxlen, and cap on it
  2070. // maxlen> 0, clen>0: cap at maxlen
  2071. if clen == 0 || clen == containerLenNil {
  2072. return 0
  2073. }
  2074. if clen < 0 {
  2075. // if unspecified, return 64 for bytes, ... 8 for uint64, ... and everything else
  2076. clen = 64 / unit
  2077. if clen > minLenIfUnset {
  2078. return clen
  2079. }
  2080. return minLenIfUnset
  2081. }
  2082. if unit <= 0 {
  2083. return clen
  2084. }
  2085. if maxlen <= 0 {
  2086. maxlen = maxMem / unit
  2087. }
  2088. if clen < maxlen {
  2089. return clen
  2090. }
  2091. return maxlen
  2092. }