helper.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. // Contains code shared by both encode and decode.
  5. // Some shared ideas around encoding/decoding
  6. // ------------------------------------------
  7. //
  8. // If an interface{} is passed, we first do a type assertion to see if it is
  9. // a primitive type or a map/slice of primitive types, and use a fastpath to handle it.
  10. //
  11. // If we start with a reflect.Value, we are already in reflect.Value land and
  12. // will try to grab the function for the underlying Type and directly call that function.
  13. // This is more performant than calling reflect.Value.Interface().
  14. //
  15. // This still helps us bypass many layers of reflection, and give best performance.
  16. //
  17. // Containers
  18. // ------------
  19. // Containers in the stream are either associative arrays (key-value pairs) or
  20. // regular arrays (indexed by incrementing integers).
  21. //
  22. // Some streams support indefinite-length containers, and use a breaking
  23. // byte-sequence to denote that the container has come to an end.
  24. //
  25. // Some streams also are text-based, and use explicit separators to denote the
  26. // end/beginning of different values.
  27. //
  28. // During encode, we use a high-level condition to determine how to iterate through
  29. // the container. That decision is based on whether the container is text-based (with
  30. // separators) or binary (without separators). If binary, we do not even call the
  31. // encoding of separators.
  32. //
  33. // During decode, we use a different high-level condition to determine how to iterate
  34. // through the containers. That decision is based on whether the stream contained
  35. // a length prefix, or if it used explicit breaks. If length-prefixed, we assume that
  36. // it has to be binary, and we do not even try to read separators.
  37. //
  38. // Philosophy
  39. // ------------
  40. // On decode, this codec will update containers appropriately:
  41. // - If struct, update fields from stream into fields of struct.
  42. // If field in stream not found in struct, handle appropriately (based on option).
  43. // If a struct field has no corresponding value in the stream, leave it AS IS.
  44. // If nil in stream, set value to nil/zero value.
  45. // - If map, update map from stream.
  46. // If the stream value is NIL, set the map to nil.
  47. // - if slice, try to update up to length of array in stream.
  48. // if container len is less than stream array length,
  49. // and container cannot be expanded, handled (based on option).
  50. // This means you can decode 4-element stream array into 1-element array.
  51. //
  52. // ------------------------------------
  53. // On encode, user can specify omitEmpty. This means that the value will be omitted
  54. // if the zero value. The problem may occur during decode, where omitted values do not affect
  55. // the value being decoded into. This means that if decoding into a struct with an
  56. // int field with current value=5, and the field is omitted in the stream, then after
  57. // decoding, the value will still be 5 (not 0).
  58. // omitEmpty only works if you guarantee that you always decode into zero-values.
  59. //
  60. // ------------------------------------
  61. // We could have truncated a map to remove keys not available in the stream,
  62. // or set values in the struct which are not in the stream to their zero values.
  63. // We decided against it because there is no efficient way to do it.
  64. // We may introduce it as an option later.
  65. // However, that will require enabling it for both runtime and code generation modes.
  66. //
  67. // To support truncate, we need to do 2 passes over the container:
  68. // map
  69. // - first collect all keys (e.g. in k1)
  70. // - for each key in stream, mark k1 that the key should not be removed
  71. // - after updating map, do second pass and call delete for all keys in k1 which are not marked
  72. // struct:
  73. // - for each field, track the *typeInfo s1
  74. // - iterate through all s1, and for each one not marked, set value to zero
  75. // - this involves checking the possible anonymous fields which are nil ptrs.
  76. // too much work.
  77. //
  78. // ------------------------------------------
  79. // Error Handling is done within the library using panic.
  80. //
  81. // This way, the code doesn't have to keep checking if an error has happened,
  82. // and we don't have to keep sending the error value along with each call
  83. // or storing it in the En|Decoder and checking it constantly along the way.
  84. //
  85. // The disadvantage is that small functions which use panics cannot be inlined.
  86. // The code accounts for that by only using panics behind an interface;
  87. // since interface calls cannot be inlined, this is irrelevant.
  88. //
  89. // We considered storing the error is En|Decoder.
  90. // - once it has its err field set, it cannot be used again.
  91. // - panicing will be optional, controlled by const flag.
  92. // - code should always check error first and return early.
  93. // We eventually decided against it as it makes the code clumsier to always
  94. // check for these error conditions.
  95. import (
  96. "bytes"
  97. "encoding"
  98. "encoding/binary"
  99. "errors"
  100. "fmt"
  101. "math"
  102. "os"
  103. "reflect"
  104. "sort"
  105. "strconv"
  106. "strings"
  107. "sync"
  108. "time"
  109. )
  110. const (
  111. scratchByteArrayLen = 32
  112. // initCollectionCap = 16 // 32 is defensive. 16 is preferred.
  113. // Support encoding.(Binary|Text)(Unm|M)arshaler.
  114. // This constant flag will enable or disable it.
  115. supportMarshalInterfaces = true
  116. // for debugging, set this to false, to catch panic traces.
  117. // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
  118. recoverPanicToErr = true
  119. // arrayCacheLen is the length of the cache used in encoder or decoder for
  120. // allowing zero-alloc initialization.
  121. arrayCacheLen = 8
  122. // always set xDebug = false before releasing software
  123. xDebug = true
  124. )
  125. var (
  126. oneByteArr = [1]byte{0}
  127. zeroByteSlice = oneByteArr[:0:0]
  128. )
  129. var refBitset bitset32
  130. var pool pooler
  131. func init() {
  132. pool.init()
  133. refBitset.set(byte(reflect.Map))
  134. refBitset.set(byte(reflect.Ptr))
  135. refBitset.set(byte(reflect.Func))
  136. refBitset.set(byte(reflect.Chan))
  137. }
  138. // type findCodecFnMode uint8
  139. // const (
  140. // findCodecFnModeMap findCodecFnMode = iota
  141. // findCodecFnModeBinarySearch
  142. // findCodecFnModeLinearSearch
  143. // )
  144. type charEncoding uint8
  145. const (
  146. c_RAW charEncoding = iota
  147. c_UTF8
  148. c_UTF16LE
  149. c_UTF16BE
  150. c_UTF32LE
  151. c_UTF32BE
  152. )
  153. // valueType is the stream type
  154. type valueType uint8
  155. const (
  156. valueTypeUnset valueType = iota
  157. valueTypeNil
  158. valueTypeInt
  159. valueTypeUint
  160. valueTypeFloat
  161. valueTypeBool
  162. valueTypeString
  163. valueTypeSymbol
  164. valueTypeBytes
  165. valueTypeMap
  166. valueTypeArray
  167. valueTypeTimestamp
  168. valueTypeExt
  169. // valueTypeInvalid = 0xff
  170. )
  171. var valueTypeStrings = [...]string{
  172. "Unset",
  173. "Nil",
  174. "Int",
  175. "Uint",
  176. "Float",
  177. "Bool",
  178. "String",
  179. "Symbol",
  180. "Bytes",
  181. "Map",
  182. "Array",
  183. "Timestamp",
  184. "Ext",
  185. }
  186. func (x valueType) String() string {
  187. if int(x) < len(valueTypeStrings) {
  188. return valueTypeStrings[x]
  189. }
  190. return strconv.FormatInt(int64(x), 10)
  191. }
  192. type seqType uint8
  193. const (
  194. _ seqType = iota
  195. seqTypeArray
  196. seqTypeSlice
  197. seqTypeChan
  198. )
  199. // note that containerMapStart and containerArraySend are not sent.
  200. // This is because the ReadXXXStart and EncodeXXXStart already does these.
  201. type containerState uint8
  202. const (
  203. _ containerState = iota
  204. containerMapStart // slot left open, since Driver method already covers it
  205. containerMapKey
  206. containerMapValue
  207. containerMapEnd
  208. containerArrayStart // slot left open, since Driver methods already cover it
  209. containerArrayElem
  210. containerArrayEnd
  211. )
  212. // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
  213. type sfiIdx struct {
  214. name string
  215. index int
  216. }
  217. // do not recurse if a containing type refers to an embedded type
  218. // which refers back to its containing type (via a pointer).
  219. // The second time this back-reference happens, break out,
  220. // so as not to cause an infinite loop.
  221. const rgetMaxRecursion = 2
  222. // Anecdotally, we believe most types have <= 12 fields.
  223. // Java's PMD rules set TooManyFields threshold to 15.
  224. const typeInfoLoadArrayLen = 12
  225. type typeInfoLoad struct {
  226. fNames []string
  227. encNames []string
  228. etypes []uintptr
  229. sfis []*structFieldInfo
  230. }
  231. type typeInfoLoadArray struct {
  232. fNames [typeInfoLoadArrayLen]string
  233. encNames [typeInfoLoadArrayLen]string
  234. etypes [typeInfoLoadArrayLen]uintptr
  235. sfis [typeInfoLoadArrayLen]*structFieldInfo
  236. sfiidx [typeInfoLoadArrayLen]sfiIdx
  237. }
  238. // type containerStateRecv interface {
  239. // sendContainerState(containerState)
  240. // }
  241. // mirror json.Marshaler and json.Unmarshaler here,
  242. // so we don't import the encoding/json package
  243. type jsonMarshaler interface {
  244. MarshalJSON() ([]byte, error)
  245. }
  246. type jsonUnmarshaler interface {
  247. UnmarshalJSON([]byte) error
  248. }
  249. // type byteAccepter func(byte) bool
  250. var (
  251. bigen = binary.BigEndian
  252. structInfoFieldName = "_struct"
  253. mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  254. mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
  255. intfSliceTyp = reflect.TypeOf([]interface{}(nil))
  256. intfTyp = intfSliceTyp.Elem()
  257. stringTyp = reflect.TypeOf("")
  258. timeTyp = reflect.TypeOf(time.Time{})
  259. rawExtTyp = reflect.TypeOf(RawExt{})
  260. rawTyp = reflect.TypeOf(Raw{})
  261. uint8SliceTyp = reflect.TypeOf([]uint8(nil))
  262. mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
  263. binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  264. binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  265. textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  266. textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  267. jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  268. jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  269. selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
  270. uint8SliceTypId = rt2id(uint8SliceTyp)
  271. rawExtTypId = rt2id(rawExtTyp)
  272. rawTypId = rt2id(rawTyp)
  273. intfTypId = rt2id(intfTyp)
  274. timeTypId = rt2id(timeTyp)
  275. stringTypId = rt2id(stringTyp)
  276. mapStrIntfTypId = rt2id(mapStrIntfTyp)
  277. mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
  278. intfSliceTypId = rt2id(intfSliceTyp)
  279. // mapBySliceTypId = rt2id(mapBySliceTyp)
  280. intBitsize uint8 = uint8(reflect.TypeOf(int(0)).Bits())
  281. uintBitsize uint8 = uint8(reflect.TypeOf(uint(0)).Bits())
  282. bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
  283. bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  284. chkOvf checkOverflow
  285. noFieldNameToStructFieldInfoErr = errors.New("no field name passed to parseStructFieldInfo")
  286. )
  287. var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
  288. var immutableKindsSet = [32]bool{
  289. // reflect.Invalid: ,
  290. reflect.Bool: true,
  291. reflect.Int: true,
  292. reflect.Int8: true,
  293. reflect.Int16: true,
  294. reflect.Int32: true,
  295. reflect.Int64: true,
  296. reflect.Uint: true,
  297. reflect.Uint8: true,
  298. reflect.Uint16: true,
  299. reflect.Uint32: true,
  300. reflect.Uint64: true,
  301. reflect.Uintptr: true,
  302. reflect.Float32: true,
  303. reflect.Float64: true,
  304. reflect.Complex64: true,
  305. reflect.Complex128: true,
  306. // reflect.Array
  307. // reflect.Chan
  308. // reflect.Func: true,
  309. // reflect.Interface
  310. // reflect.Map
  311. // reflect.Ptr
  312. // reflect.Slice
  313. reflect.String: true,
  314. // reflect.Struct
  315. // reflect.UnsafePointer
  316. }
  317. // Selfer defines methods by which a value can encode or decode itself.
  318. //
  319. // Any type which implements Selfer will be able to encode or decode itself.
  320. // Consequently, during (en|de)code, this takes precedence over
  321. // (text|binary)(M|Unm)arshal or extension support.
  322. type Selfer interface {
  323. CodecEncodeSelf(*Encoder)
  324. CodecDecodeSelf(*Decoder)
  325. }
  326. // MapBySlice represents a slice which should be encoded as a map in the stream.
  327. // The slice contains a sequence of key-value pairs.
  328. // This affords storing a map in a specific sequence in the stream.
  329. //
  330. // The support of MapBySlice affords the following:
  331. // - A slice type which implements MapBySlice will be encoded as a map
  332. // - A slice can be decoded from a map in the stream
  333. type MapBySlice interface {
  334. MapBySlice()
  335. }
  336. // WARNING: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
  337. //
  338. // BasicHandle encapsulates the common options and extension functions.
  339. type BasicHandle struct {
  340. // TypeInfos is used to get the type info for any type.
  341. //
  342. // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
  343. TypeInfos *TypeInfos
  344. extHandle
  345. EncodeOptions
  346. DecodeOptions
  347. noBuiltInTypeChecker
  348. }
  349. func (x *BasicHandle) getBasicHandle() *BasicHandle {
  350. return x
  351. }
  352. func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  353. if x.TypeInfos == nil {
  354. return defTypeInfos.get(rtid, rt)
  355. }
  356. return x.TypeInfos.get(rtid, rt)
  357. }
  358. // Handle is the interface for a specific encoding format.
  359. //
  360. // Typically, a Handle is pre-configured before first time use,
  361. // and not modified while in use. Such a pre-configured Handle
  362. // is safe for concurrent access.
  363. type Handle interface {
  364. getBasicHandle() *BasicHandle
  365. newEncDriver(w *Encoder) encDriver
  366. newDecDriver(r *Decoder) decDriver
  367. isBinary() bool
  368. hasElemSeparators() bool
  369. IsBuiltinType(rtid uintptr) bool
  370. }
  371. // Raw represents raw formatted bytes.
  372. // We "blindly" store it during encode and store the raw bytes during decode.
  373. // Note: it is dangerous during encode, so we may gate the behaviour behind an Encode flag which must be explicitly set.
  374. type Raw []byte
  375. // RawExt represents raw unprocessed extension data.
  376. // Some codecs will decode extension data as a *RawExt if there is no registered extension for the tag.
  377. //
  378. // Only one of Data or Value is nil. If Data is nil, then the content of the RawExt is in the Value.
  379. type RawExt struct {
  380. Tag uint64
  381. // Data is the []byte which represents the raw ext. If Data is nil, ext is exposed in Value.
  382. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types
  383. Data []byte
  384. // Value represents the extension, if Data is nil.
  385. // Value is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  386. Value interface{}
  387. }
  388. // BytesExt handles custom (de)serialization of types to/from []byte.
  389. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  390. type BytesExt interface {
  391. // WriteExt converts a value to a []byte.
  392. //
  393. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  394. WriteExt(v interface{}) []byte
  395. // ReadExt updates a value from a []byte.
  396. ReadExt(dst interface{}, src []byte)
  397. }
  398. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  399. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  400. //
  401. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  402. type InterfaceExt interface {
  403. // ConvertExt converts a value into a simpler interface for easy encoding e.g. convert time.Time to int64.
  404. //
  405. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  406. ConvertExt(v interface{}) interface{}
  407. // UpdateExt updates a value from a simpler interface for easy decoding e.g. convert int64 to time.Time.
  408. UpdateExt(dst interface{}, src interface{})
  409. }
  410. // Ext handles custom (de)serialization of custom types / extensions.
  411. type Ext interface {
  412. BytesExt
  413. InterfaceExt
  414. }
  415. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  416. type addExtWrapper struct {
  417. encFn func(reflect.Value) ([]byte, error)
  418. decFn func(reflect.Value, []byte) error
  419. }
  420. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  421. bs, err := x.encFn(reflect.ValueOf(v))
  422. if err != nil {
  423. panic(err)
  424. }
  425. return bs
  426. }
  427. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  428. if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
  429. panic(err)
  430. }
  431. }
  432. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  433. return x.WriteExt(v)
  434. }
  435. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  436. x.ReadExt(dest, v.([]byte))
  437. }
  438. type setExtWrapper struct {
  439. b BytesExt
  440. i InterfaceExt
  441. }
  442. func (x *setExtWrapper) WriteExt(v interface{}) []byte {
  443. if x.b == nil {
  444. panic("BytesExt.WriteExt is not supported")
  445. }
  446. return x.b.WriteExt(v)
  447. }
  448. func (x *setExtWrapper) ReadExt(v interface{}, bs []byte) {
  449. if x.b == nil {
  450. panic("BytesExt.WriteExt is not supported")
  451. }
  452. x.b.ReadExt(v, bs)
  453. }
  454. func (x *setExtWrapper) ConvertExt(v interface{}) interface{} {
  455. if x.i == nil {
  456. panic("InterfaceExt.ConvertExt is not supported")
  457. }
  458. return x.i.ConvertExt(v)
  459. }
  460. func (x *setExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  461. if x.i == nil {
  462. panic("InterfaceExxt.UpdateExt is not supported")
  463. }
  464. x.i.UpdateExt(dest, v)
  465. }
  466. type binaryEncodingType struct{}
  467. func (_ binaryEncodingType) isBinary() bool { return true }
  468. type textEncodingType struct{}
  469. func (_ textEncodingType) isBinary() bool { return false }
  470. // noBuiltInTypes is embedded into many types which do not support builtins
  471. // e.g. msgpack, simple, cbor.
  472. type noBuiltInTypeChecker struct{}
  473. func (_ noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
  474. type noBuiltInTypes struct{ noBuiltInTypeChecker }
  475. func (_ noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  476. func (_ noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  477. // type noStreamingCodec struct{}
  478. // func (_ noStreamingCodec) CheckBreak() bool { return false }
  479. // func (_ noStreamingCodec) hasElemSeparators() bool { return false }
  480. type noElemSeparators struct{}
  481. func (_ noElemSeparators) hasElemSeparators() (v bool) { return }
  482. // bigenHelper.
  483. // Users must already slice the x completely, because we will not reslice.
  484. type bigenHelper struct {
  485. x []byte // must be correctly sliced to appropriate len. slicing is a cost.
  486. w encWriter
  487. }
  488. func (z bigenHelper) writeUint16(v uint16) {
  489. bigen.PutUint16(z.x, v)
  490. z.w.writeb(z.x)
  491. }
  492. func (z bigenHelper) writeUint32(v uint32) {
  493. bigen.PutUint32(z.x, v)
  494. z.w.writeb(z.x)
  495. }
  496. func (z bigenHelper) writeUint64(v uint64) {
  497. bigen.PutUint64(z.x, v)
  498. z.w.writeb(z.x)
  499. }
  500. type extTypeTagFn struct {
  501. rtid uintptr
  502. rt reflect.Type
  503. tag uint64
  504. ext Ext
  505. }
  506. type extHandle []extTypeTagFn
  507. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  508. //
  509. // AddExt registes an encode and decode function for a reflect.Type.
  510. // AddExt internally calls SetExt.
  511. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  512. func (o *extHandle) AddExt(
  513. rt reflect.Type, tag byte,
  514. encfn func(reflect.Value) ([]byte, error), decfn func(reflect.Value, []byte) error,
  515. ) (err error) {
  516. if encfn == nil || decfn == nil {
  517. return o.SetExt(rt, uint64(tag), nil)
  518. }
  519. return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  520. }
  521. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  522. //
  523. // Note that the type must be a named type, and specifically not
  524. // a pointer or Interface. An error is returned if that is not honored.
  525. //
  526. // To Deregister an ext, call SetExt with nil Ext
  527. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  528. // o is a pointer, because we may need to initialize it
  529. if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
  530. err = fmt.Errorf("codec.Handle.AddExt: Takes named type, not a pointer or interface: %T",
  531. reflect.Zero(rt).Interface())
  532. return
  533. }
  534. rtid := rt2id(rt)
  535. for _, v := range *o {
  536. if v.rtid == rtid {
  537. v.tag, v.ext = tag, ext
  538. return
  539. }
  540. }
  541. if *o == nil {
  542. *o = make([]extTypeTagFn, 0, 4)
  543. }
  544. *o = append(*o, extTypeTagFn{rtid, rt, tag, ext})
  545. return
  546. }
  547. func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
  548. var v *extTypeTagFn
  549. for i := range o {
  550. v = &o[i]
  551. if v.rtid == rtid {
  552. return v
  553. }
  554. }
  555. return nil
  556. }
  557. func (o extHandle) getExtForTag(tag uint64) *extTypeTagFn {
  558. var v *extTypeTagFn
  559. for i := range o {
  560. v = &o[i]
  561. if v.tag == tag {
  562. return v
  563. }
  564. }
  565. return nil
  566. }
  567. const maxLevelsEmbedding = 16
  568. type structFieldInfo struct {
  569. encName string // encode name
  570. fieldName string // field name
  571. is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
  572. nis uint8 // num levels of embedding. if 1, then it's not embedded.
  573. omitEmpty bool
  574. toArray bool // if field is _struct, is the toArray set?
  575. }
  576. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  577. if v, valid := si.field(v, false); valid {
  578. v.Set(reflect.Zero(v.Type()))
  579. }
  580. }
  581. // rv returns the field of the struct.
  582. // If anonymous, it returns an Invalid
  583. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
  584. // replicate FieldByIndex
  585. for i, x := range si.is {
  586. if uint8(i) == si.nis {
  587. break
  588. }
  589. if v, valid = baseStructRv(v, update); !valid {
  590. return
  591. }
  592. v = v.Field(int(x))
  593. }
  594. return v, true
  595. }
  596. // func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
  597. // v, _ = si.field(v, update)
  598. // return v
  599. // }
  600. func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
  601. // if fname == "" {
  602. // panic(noFieldNameToStructFieldInfoErr)
  603. // }
  604. si := structFieldInfo{
  605. encName: fname,
  606. }
  607. if stag != "" {
  608. for i, s := range strings.Split(stag, ",") {
  609. if i == 0 {
  610. if s != "" {
  611. si.encName = s
  612. }
  613. } else {
  614. if s == "omitempty" {
  615. si.omitEmpty = true
  616. } else if s == "toarray" {
  617. si.toArray = true
  618. }
  619. }
  620. }
  621. }
  622. // si.encNameBs = []byte(si.encName)
  623. return &si
  624. }
  625. type sfiSortedByEncName []*structFieldInfo
  626. func (p sfiSortedByEncName) Len() int {
  627. return len(p)
  628. }
  629. func (p sfiSortedByEncName) Less(i, j int) bool {
  630. return p[i].encName < p[j].encName
  631. }
  632. func (p sfiSortedByEncName) Swap(i, j int) {
  633. p[i], p[j] = p[j], p[i]
  634. }
  635. const structFieldNodeNumToCache = 4
  636. type structFieldNodeCache struct {
  637. rv [structFieldNodeNumToCache]reflect.Value
  638. idx [structFieldNodeNumToCache]uint32
  639. num uint8
  640. }
  641. func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
  642. // defer func() { fmt.Printf(">>>> found in cache2? %v\n", valid) }()
  643. for i, k := range &x.idx {
  644. if uint8(i) == x.num {
  645. return // break
  646. }
  647. if key == k {
  648. return x.rv[i], true
  649. }
  650. }
  651. return
  652. }
  653. func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
  654. if x.num < structFieldNodeNumToCache {
  655. x.rv[x.num] = fv
  656. x.idx[x.num] = key
  657. x.num++
  658. return
  659. }
  660. }
  661. type structFieldNode struct {
  662. v reflect.Value
  663. cache2 structFieldNodeCache
  664. cache3 structFieldNodeCache
  665. update bool
  666. }
  667. func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
  668. // return si.fieldval(x.v, x.update)
  669. // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
  670. // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
  671. var valid bool
  672. switch si.nis {
  673. case 1:
  674. fv = x.v.Field(int(si.is[0]))
  675. case 2:
  676. if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
  677. fv = fv.Field(int(si.is[1]))
  678. return
  679. }
  680. fv = x.v.Field(int(si.is[0]))
  681. if fv, valid = baseStructRv(fv, x.update); !valid {
  682. return
  683. }
  684. x.cache2.tryAdd(fv, uint32(si.is[0]))
  685. fv = fv.Field(int(si.is[1]))
  686. case 3:
  687. var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
  688. if fv, valid = x.cache3.get(key); valid {
  689. fv = fv.Field(int(si.is[2]))
  690. return
  691. }
  692. fv = x.v.Field(int(si.is[0]))
  693. if fv, valid = baseStructRv(fv, x.update); !valid {
  694. return
  695. }
  696. fv = fv.Field(int(si.is[1]))
  697. if fv, valid = baseStructRv(fv, x.update); !valid {
  698. return
  699. }
  700. x.cache3.tryAdd(fv, key)
  701. fv = fv.Field(int(si.is[2]))
  702. default:
  703. fv, _ = si.field(x.v, x.update)
  704. }
  705. return
  706. }
  707. func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
  708. for v.Kind() == reflect.Ptr {
  709. if v.IsNil() {
  710. if !update {
  711. return
  712. }
  713. v.Set(reflect.New(v.Type().Elem()))
  714. }
  715. v = v.Elem()
  716. }
  717. return v, true
  718. }
  719. // typeInfo keeps information about each (non-ptr) type referenced in the encode/decode sequence.
  720. //
  721. // During an encode/decode sequence, we work as below:
  722. // - If base is a built in type, en/decode base value
  723. // - If base is registered as an extension, en/decode base value
  724. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  725. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  726. // - Else decode appropriately based on the reflect.Kind
  727. type typeInfo struct {
  728. sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
  729. sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  730. rt reflect.Type
  731. rtid uintptr
  732. // rv0 reflect.Value // saved zero value, used if immutableKind
  733. numMeth uint16 // number of methods
  734. anyOmitEmpty bool
  735. mbs bool // base type (T or *T) is a MapBySlice
  736. // format of marshal type fields below: [btj][mu]p? OR csp?
  737. bm bool // T is a binaryMarshaler
  738. bmp bool // *T is a binaryMarshaler
  739. bu bool // T is a binaryUnmarshaler
  740. bup bool // *T is a binaryUnmarshaler
  741. tm bool // T is a textMarshaler
  742. tmp bool // *T is a textMarshaler
  743. tu bool // T is a textUnmarshaler
  744. tup bool // *T is a textUnmarshaler
  745. jm bool // T is a jsonMarshaler
  746. jmp bool // *T is a jsonMarshaler
  747. ju bool // T is a jsonUnmarshaler
  748. jup bool // *T is a jsonUnmarshaler
  749. cs bool // T is a Selfer
  750. csp bool // *T is a Selfer
  751. toArray bool // whether this (struct) type should be encoded as an array
  752. }
  753. // define length beyond which we do a binary search instead of a linear search.
  754. // From our testing, linear search seems faster than binary search up to 16-field structs.
  755. // However, we set to 8 similar to what python does for hashtables.
  756. const indexForEncNameBinarySearchThreshold = 8
  757. func (ti *typeInfo) indexForEncName(name string) int {
  758. // NOTE: name may be a stringView, so don't pass it to another function.
  759. //tisfi := ti.sfi
  760. sfilen := len(ti.sfi)
  761. if sfilen < indexForEncNameBinarySearchThreshold {
  762. for i, si := range ti.sfi {
  763. if si.encName == name {
  764. return i
  765. }
  766. }
  767. return -1
  768. }
  769. // binary search. adapted from sort/search.go.
  770. h, i, j := 0, 0, sfilen
  771. for i < j {
  772. h = i + (j-i)/2
  773. if ti.sfi[h].encName < name {
  774. i = h + 1
  775. } else {
  776. j = h
  777. }
  778. }
  779. if i < sfilen && ti.sfi[i].encName == name {
  780. return i
  781. }
  782. return -1
  783. }
  784. type rtid2ti struct {
  785. rtid uintptr
  786. ti *typeInfo
  787. }
  788. // TypeInfos caches typeInfo for each type on first inspection.
  789. //
  790. // It is configured with a set of tag keys, which are used to get
  791. // configuration for the type.
  792. type TypeInfos struct {
  793. infos atomicTypeInfoSlice // formerly map[uintptr]*typeInfo, now *[]rtid2ti
  794. mu sync.Mutex
  795. tags []string
  796. }
  797. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  798. //
  799. // This allows users customize the struct tag keys which contain configuration
  800. // of their types.
  801. func NewTypeInfos(tags []string) *TypeInfos {
  802. return &TypeInfos{tags: tags}
  803. }
  804. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  805. // check for tags: codec, json, in that order.
  806. // this allows seamless support for many configured structs.
  807. for _, x := range x.tags {
  808. s = t.Get(x)
  809. if s != "" {
  810. return s
  811. }
  812. }
  813. return
  814. }
  815. func (x *TypeInfos) find(sp *[]rtid2ti, rtid uintptr) (idx int, ti *typeInfo) {
  816. // binary search. adapted from sort/search.go.
  817. // if sp == nil {
  818. // return -1, nil
  819. // }
  820. s := *sp
  821. h, i, j := 0, 0, len(s)
  822. for i < j {
  823. h = i + (j-i)/2
  824. if s[h].rtid < rtid {
  825. i = h + 1
  826. } else {
  827. j = h
  828. }
  829. }
  830. if i < len(s) && s[i].rtid == rtid {
  831. return i, s[i].ti
  832. }
  833. return i, nil
  834. }
  835. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  836. sp := x.infos.load()
  837. var idx int
  838. if sp != nil {
  839. idx, pti = x.find(sp, rtid)
  840. if pti != nil {
  841. return
  842. }
  843. }
  844. rk := rt.Kind()
  845. if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) {
  846. panic(fmt.Errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt))
  847. }
  848. // do not hold lock while computing this.
  849. // it may lead to duplication, but that's ok.
  850. ti := typeInfo{rt: rt, rtid: rtid}
  851. // ti.rv0 = reflect.Zero(rt)
  852. ti.numMeth = uint16(rt.NumMethod())
  853. ti.bm, ti.bmp = implIntf(rt, binaryMarshalerTyp)
  854. ti.bu, ti.bup = implIntf(rt, binaryUnmarshalerTyp)
  855. ti.tm, ti.tmp = implIntf(rt, textMarshalerTyp)
  856. ti.tu, ti.tup = implIntf(rt, textUnmarshalerTyp)
  857. ti.jm, ti.jmp = implIntf(rt, jsonMarshalerTyp)
  858. ti.ju, ti.jup = implIntf(rt, jsonUnmarshalerTyp)
  859. ti.cs, ti.csp = implIntf(rt, selferTyp)
  860. ti.mbs, _ = implIntf(rt, mapBySliceTyp)
  861. if rk == reflect.Struct {
  862. var omitEmpty bool
  863. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  864. siInfo := parseStructFieldInfo(structInfoFieldName, x.structTag(f.Tag))
  865. ti.toArray = siInfo.toArray
  866. omitEmpty = siInfo.omitEmpty
  867. }
  868. pp, pi := pool.tiLoad()
  869. pv := pi.(*typeInfoLoadArray)
  870. pv.etypes[0] = ti.rtid
  871. vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  872. x.rget(rt, rtid, omitEmpty, nil, &vv)
  873. ti.sfip, ti.sfi, ti.anyOmitEmpty = rgetResolveSFI(vv.sfis, pv.sfiidx[:0])
  874. pp.Put(pi)
  875. }
  876. // sfi = sfip
  877. var vs []rtid2ti
  878. x.mu.Lock()
  879. sp = x.infos.load()
  880. if sp == nil {
  881. pti = &ti
  882. vs = []rtid2ti{{rtid, pti}}
  883. x.infos.store(&vs)
  884. } else {
  885. idx, pti = x.find(sp, rtid)
  886. if pti == nil {
  887. s := *sp
  888. pti = &ti
  889. vs = make([]rtid2ti, len(s)+1)
  890. copy(vs, s[:idx])
  891. vs[idx] = rtid2ti{rtid, pti}
  892. copy(vs[idx+1:], s[idx:])
  893. x.infos.store(&vs)
  894. }
  895. }
  896. x.mu.Unlock()
  897. return
  898. }
  899. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  900. indexstack []uint16, pv *typeInfoLoad,
  901. ) {
  902. // Read up fields and store how to access the value.
  903. //
  904. // It uses go's rules for message selectors,
  905. // which say that the field with the shallowest depth is selected.
  906. //
  907. // Note: we consciously use slices, not a map, to simulate a set.
  908. // Typically, types have < 16 fields,
  909. // and iteration using equals is faster than maps there
  910. flen := rt.NumField()
  911. if flen > (1<<maxLevelsEmbedding - 1) {
  912. panic(fmt.Errorf("codec: types with more than %v fields are not supported - has %v fields", (1<<maxLevelsEmbedding - 1), flen))
  913. }
  914. LOOP:
  915. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  916. f := rt.Field(int(j))
  917. fkind := f.Type.Kind()
  918. // skip if a func type, or is unexported, or structTag value == "-"
  919. switch fkind {
  920. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  921. continue LOOP
  922. }
  923. // if r1, _ := utf8.DecodeRuneInString(f.Name);
  924. // r1 == utf8.RuneError || !unicode.IsUpper(r1) {
  925. if f.PkgPath != "" && !f.Anonymous { // unexported, not embedded
  926. continue
  927. }
  928. stag := x.structTag(f.Tag)
  929. if stag == "-" {
  930. continue
  931. }
  932. var si *structFieldInfo
  933. // if anonymous and no struct tag (or it's blank),
  934. // and a struct (or pointer to struct), inline it.
  935. if f.Anonymous && fkind != reflect.Interface {
  936. doInline := stag == ""
  937. if !doInline {
  938. si = parseStructFieldInfo("", stag)
  939. doInline = si.encName == ""
  940. // doInline = si.isZero()
  941. }
  942. if doInline {
  943. ft := f.Type
  944. for ft.Kind() == reflect.Ptr {
  945. ft = ft.Elem()
  946. }
  947. if ft.Kind() == reflect.Struct {
  948. // if etypes contains this, don't call rget again (as fields are already seen here)
  949. ftid := rt2id(ft)
  950. // We cannot recurse forever, but we need to track other field depths.
  951. // So - we break if we see a type twice (not the first time).
  952. // This should be sufficient to handle an embedded type that refers to its
  953. // owning type, which then refers to its embedded type.
  954. processIt := true
  955. numk := 0
  956. for _, k := range pv.etypes {
  957. if k == ftid {
  958. numk++
  959. if numk == rgetMaxRecursion {
  960. processIt = false
  961. break
  962. }
  963. }
  964. }
  965. if processIt {
  966. pv.etypes = append(pv.etypes, ftid)
  967. indexstack2 := make([]uint16, len(indexstack)+1)
  968. copy(indexstack2, indexstack)
  969. indexstack2[len(indexstack)] = j
  970. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  971. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  972. }
  973. continue
  974. }
  975. }
  976. }
  977. // after the anonymous dance: if an unexported field, skip
  978. if f.PkgPath != "" { // unexported
  979. continue
  980. }
  981. if f.Name == "" {
  982. panic(noFieldNameToStructFieldInfoErr)
  983. }
  984. pv.fNames = append(pv.fNames, f.Name)
  985. if si == nil {
  986. si = parseStructFieldInfo(f.Name, stag)
  987. } else if si.encName == "" {
  988. si.encName = f.Name
  989. }
  990. si.fieldName = f.Name
  991. pv.encNames = append(pv.encNames, si.encName)
  992. // si.ikind = int(f.Type.Kind())
  993. if len(indexstack) > maxLevelsEmbedding-1 {
  994. panic(fmt.Errorf("codec: only supports up to %v depth of embedding - type has %v depth", maxLevelsEmbedding-1, len(indexstack)))
  995. }
  996. si.nis = uint8(len(indexstack)) + 1
  997. copy(si.is[:], indexstack)
  998. si.is[len(indexstack)] = j
  999. if omitEmpty {
  1000. si.omitEmpty = true
  1001. }
  1002. pv.sfis = append(pv.sfis, si)
  1003. }
  1004. }
  1005. // resolves the struct field info got from a call to rget.
  1006. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  1007. func rgetResolveSFI(x []*structFieldInfo, pv []sfiIdx) (y, z []*structFieldInfo, anyOmitEmpty bool) {
  1008. var n int
  1009. for i, v := range x {
  1010. xn := v.encName // TODO: fieldName or encName? use encName for now.
  1011. var found bool
  1012. for j, k := range pv {
  1013. if k.name == xn {
  1014. // one of them must be reset to nil, and the index updated appropriately to the other one
  1015. if v.nis == x[k.index].nis {
  1016. } else if v.nis < x[k.index].nis {
  1017. pv[j].index = i
  1018. if x[k.index] != nil {
  1019. x[k.index] = nil
  1020. n++
  1021. }
  1022. } else {
  1023. if x[i] != nil {
  1024. x[i] = nil
  1025. n++
  1026. }
  1027. }
  1028. found = true
  1029. break
  1030. }
  1031. }
  1032. if !found {
  1033. pv = append(pv, sfiIdx{xn, i})
  1034. }
  1035. }
  1036. // remove all the nils
  1037. y = make([]*structFieldInfo, len(x)-n)
  1038. n = 0
  1039. for _, v := range x {
  1040. if v == nil {
  1041. continue
  1042. }
  1043. if !anyOmitEmpty && v.omitEmpty {
  1044. anyOmitEmpty = true
  1045. }
  1046. y[n] = v
  1047. n++
  1048. }
  1049. z = make([]*structFieldInfo, len(y))
  1050. copy(z, y)
  1051. sort.Sort(sfiSortedByEncName(z))
  1052. return
  1053. }
  1054. func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) {
  1055. return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp)
  1056. }
  1057. func xprintf(format string, a ...interface{}) {
  1058. if xDebug {
  1059. fmt.Fprintf(os.Stderr, format, a...)
  1060. }
  1061. }
  1062. func panicToErr(err *error) {
  1063. if recoverPanicToErr {
  1064. if x := recover(); x != nil {
  1065. // if false && xDebug {
  1066. // fmt.Printf("panic'ing with: %v\n", x)
  1067. // debug.PrintStack()
  1068. // }
  1069. panicValToErr(x, err)
  1070. }
  1071. }
  1072. }
  1073. func panicToErrs2(err1, err2 *error) {
  1074. if recoverPanicToErr {
  1075. if x := recover(); x != nil {
  1076. panicValToErr(x, err1)
  1077. panicValToErr(x, err2)
  1078. }
  1079. }
  1080. }
  1081. // func doPanic(tag string, format string, params ...interface{}) {
  1082. // params2 := make([]interface{}, len(params)+1)
  1083. // params2[0] = tag
  1084. // copy(params2[1:], params)
  1085. // panic(fmt.Errorf("%s: "+format, params2...))
  1086. // }
  1087. func isImmutableKind(k reflect.Kind) (v bool) {
  1088. return immutableKindsSet[k]
  1089. // return false ||
  1090. // k == reflect.Int ||
  1091. // k == reflect.Int8 ||
  1092. // k == reflect.Int16 ||
  1093. // k == reflect.Int32 ||
  1094. // k == reflect.Int64 ||
  1095. // k == reflect.Uint ||
  1096. // k == reflect.Uint8 ||
  1097. // k == reflect.Uint16 ||
  1098. // k == reflect.Uint32 ||
  1099. // k == reflect.Uint64 ||
  1100. // k == reflect.Uintptr ||
  1101. // k == reflect.Float32 ||
  1102. // k == reflect.Float64 ||
  1103. // k == reflect.Bool ||
  1104. // k == reflect.String
  1105. }
  1106. // ----
  1107. type codecFnInfo struct {
  1108. ti *typeInfo
  1109. xfFn Ext
  1110. xfTag uint64
  1111. seq seqType
  1112. addrD bool
  1113. addrE bool
  1114. }
  1115. // codecFn encapsulates the captured variables and the encode function.
  1116. // This way, we only do some calculations one times, and pass to the
  1117. // code block that should be called (encapsulated in a function)
  1118. // instead of executing the checks every time.
  1119. type codecFn struct {
  1120. i codecFnInfo
  1121. fe func(*Encoder, *codecFnInfo, reflect.Value)
  1122. fd func(*Decoder, *codecFnInfo, reflect.Value)
  1123. }
  1124. type codecRtidFn struct {
  1125. rtid uintptr
  1126. fn codecFn
  1127. }
  1128. type codecFner struct {
  1129. hh Handle
  1130. h *BasicHandle
  1131. cs [arrayCacheLen]*[arrayCacheLen]codecRtidFn
  1132. s []*[arrayCacheLen]codecRtidFn
  1133. sn uint32
  1134. be bool
  1135. js bool
  1136. cf [arrayCacheLen]codecRtidFn
  1137. }
  1138. func (c *codecFner) reset(hh Handle) {
  1139. c.hh = hh
  1140. c.h = hh.getBasicHandle()
  1141. _, c.js = hh.(*JsonHandle)
  1142. c.be = hh.isBinary()
  1143. }
  1144. func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
  1145. rtid := rt2id(rt)
  1146. var j uint32
  1147. var sn uint32 = c.sn
  1148. if sn == 0 {
  1149. c.s = c.cs[:1]
  1150. c.s[0] = &c.cf
  1151. c.cf[0].rtid = rtid
  1152. fn = &(c.cf[0].fn)
  1153. c.sn = 1
  1154. } else {
  1155. LOOP1:
  1156. for _, x := range c.s {
  1157. for i := range x {
  1158. if j == sn {
  1159. break LOOP1
  1160. }
  1161. if x[i].rtid == rtid {
  1162. fn = &(x[i].fn)
  1163. return
  1164. }
  1165. j++
  1166. }
  1167. }
  1168. sx, sy := sn/arrayCacheLen, sn%arrayCacheLen
  1169. if sy == 0 {
  1170. c.s = append(c.s, &[arrayCacheLen]codecRtidFn{})
  1171. }
  1172. c.s[sx][sy].rtid = rtid
  1173. fn = &(c.s[sx][sy].fn)
  1174. c.sn++
  1175. }
  1176. ti := c.h.getTypeInfo(rtid, rt)
  1177. fi := &(fn.i)
  1178. fi.ti = ti
  1179. rk := rt.Kind()
  1180. if checkCodecSelfer && (ti.cs || ti.csp) {
  1181. fn.fe = (*Encoder).selferMarshal
  1182. fn.fd = (*Decoder).selferUnmarshal
  1183. fi.addrD = ti.csp
  1184. fi.addrE = ti.csp
  1185. } else if rtid == rawTypId {
  1186. fn.fe = (*Encoder).raw
  1187. fn.fd = (*Decoder).raw
  1188. } else if rtid == rawExtTypId {
  1189. fn.fe = (*Encoder).rawExt
  1190. fn.fd = (*Decoder).rawExt
  1191. fi.addrD = true
  1192. fi.addrE = true
  1193. } else if c.hh.IsBuiltinType(rtid) {
  1194. fn.fe = (*Encoder).builtin
  1195. fn.fd = (*Decoder).builtin
  1196. fi.addrD = true
  1197. } else if xfFn := c.h.getExt(rtid); xfFn != nil {
  1198. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  1199. fn.fe = (*Encoder).ext
  1200. fn.fd = (*Decoder).ext
  1201. fi.addrD = true
  1202. if rk == reflect.Struct || rk == reflect.Array {
  1203. fi.addrE = true
  1204. }
  1205. } else if supportMarshalInterfaces && c.be && (ti.bm || ti.bmp) && (ti.bu || ti.bup) {
  1206. fn.fe = (*Encoder).binaryMarshal
  1207. fn.fd = (*Decoder).binaryUnmarshal
  1208. fi.addrD = ti.bup
  1209. fi.addrE = ti.bmp
  1210. } else if supportMarshalInterfaces && !c.be && c.js && (ti.jm || ti.jmp) && (ti.ju || ti.jup) {
  1211. //If JSON, we should check JSONMarshal before textMarshal
  1212. fn.fe = (*Encoder).jsonMarshal
  1213. fn.fd = (*Decoder).jsonUnmarshal
  1214. fi.addrD = ti.jup
  1215. fi.addrE = ti.jmp
  1216. } else if supportMarshalInterfaces && !c.be && (ti.tm || ti.tmp) && (ti.tu || ti.tup) {
  1217. fn.fe = (*Encoder).textMarshal
  1218. fn.fd = (*Decoder).textUnmarshal
  1219. fi.addrD = ti.tup
  1220. fi.addrE = ti.tmp
  1221. } else {
  1222. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  1223. if rt.PkgPath() == "" { // un-named slice or map
  1224. if idx := fastpathAV.index(rtid); idx != -1 {
  1225. fn.fe = fastpathAV[idx].encfn
  1226. fn.fd = fastpathAV[idx].decfn
  1227. fi.addrD = true
  1228. }
  1229. } else {
  1230. // use mapping for underlying type if there
  1231. var rtu reflect.Type
  1232. if rk == reflect.Map {
  1233. rtu = reflect.MapOf(rt.Key(), rt.Elem())
  1234. } else {
  1235. rtu = reflect.SliceOf(rt.Elem())
  1236. }
  1237. rtuid := rt2id(rtu)
  1238. if idx := fastpathAV.index(rtuid); idx != -1 {
  1239. xfnf := fastpathAV[idx].encfn
  1240. xrt := fastpathAV[idx].rt
  1241. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  1242. xfnf(e, xf, xrv.Convert(xrt))
  1243. }
  1244. fi.addrD = true
  1245. xfnf2 := fastpathAV[idx].decfn
  1246. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1247. xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
  1248. }
  1249. }
  1250. }
  1251. }
  1252. if fn.fe == nil && fn.fd == nil {
  1253. switch rk {
  1254. case reflect.Bool:
  1255. fn.fe = (*Encoder).kBool
  1256. fn.fd = (*Decoder).kBool
  1257. case reflect.String:
  1258. fn.fe = (*Encoder).kString
  1259. fn.fd = (*Decoder).kString
  1260. case reflect.Int:
  1261. fn.fd = (*Decoder).kInt
  1262. fn.fe = (*Encoder).kInt
  1263. case reflect.Int8:
  1264. fn.fe = (*Encoder).kInt8
  1265. fn.fd = (*Decoder).kInt8
  1266. case reflect.Int16:
  1267. fn.fe = (*Encoder).kInt16
  1268. fn.fd = (*Decoder).kInt16
  1269. case reflect.Int32:
  1270. fn.fe = (*Encoder).kInt32
  1271. fn.fd = (*Decoder).kInt32
  1272. case reflect.Int64:
  1273. fn.fe = (*Encoder).kInt64
  1274. fn.fd = (*Decoder).kInt64
  1275. case reflect.Uint:
  1276. fn.fd = (*Decoder).kUint
  1277. fn.fe = (*Encoder).kUint
  1278. case reflect.Uint8:
  1279. fn.fe = (*Encoder).kUint8
  1280. fn.fd = (*Decoder).kUint8
  1281. case reflect.Uint16:
  1282. fn.fe = (*Encoder).kUint16
  1283. fn.fd = (*Decoder).kUint16
  1284. case reflect.Uint32:
  1285. fn.fe = (*Encoder).kUint32
  1286. fn.fd = (*Decoder).kUint32
  1287. case reflect.Uint64:
  1288. fn.fe = (*Encoder).kUint64
  1289. fn.fd = (*Decoder).kUint64
  1290. // case reflect.Ptr:
  1291. // fn.fd = (*Decoder).kPtr
  1292. case reflect.Uintptr:
  1293. fn.fe = (*Encoder).kUintptr
  1294. fn.fd = (*Decoder).kUintptr
  1295. case reflect.Float32:
  1296. fn.fe = (*Encoder).kFloat32
  1297. fn.fd = (*Decoder).kFloat32
  1298. case reflect.Float64:
  1299. fn.fe = (*Encoder).kFloat64
  1300. fn.fd = (*Decoder).kFloat64
  1301. case reflect.Invalid:
  1302. fn.fe = (*Encoder).kInvalid
  1303. fn.fd = (*Decoder).kErr
  1304. case reflect.Chan:
  1305. fi.seq = seqTypeChan
  1306. fn.fe = (*Encoder).kSlice
  1307. fn.fd = (*Decoder).kSlice
  1308. case reflect.Slice:
  1309. fi.seq = seqTypeSlice
  1310. fn.fe = (*Encoder).kSlice
  1311. fn.fd = (*Decoder).kSlice
  1312. case reflect.Array:
  1313. fi.seq = seqTypeArray
  1314. fn.fe = (*Encoder).kSlice
  1315. fi.addrD = false
  1316. rt2 := reflect.SliceOf(rt.Elem())
  1317. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1318. // println(">>>>>> decoding an array ... ")
  1319. d.cf.get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
  1320. // println(">>>>>> decoding an array ... DONE")
  1321. }
  1322. // fn.fd = (*Decoder).kArray
  1323. case reflect.Struct:
  1324. if ti.anyOmitEmpty {
  1325. fn.fe = (*Encoder).kStruct
  1326. } else {
  1327. fn.fe = (*Encoder).kStructNoOmitempty
  1328. }
  1329. fn.fd = (*Decoder).kStruct
  1330. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  1331. // case reflect.Ptr:
  1332. // fn.fe = (*Encoder).kPtr
  1333. // case reflect.Interface:
  1334. // fn.fe = (*Encoder).kInterface
  1335. case reflect.Map:
  1336. fn.fe = (*Encoder).kMap
  1337. fn.fd = (*Decoder).kMap
  1338. case reflect.Interface:
  1339. // encode: reflect.Interface are handled already by preEncodeValue
  1340. fn.fd = (*Decoder).kInterface
  1341. fn.fe = (*Encoder).kErr
  1342. default:
  1343. fn.fe = (*Encoder).kErr
  1344. fn.fd = (*Decoder).kErr
  1345. }
  1346. }
  1347. }
  1348. return
  1349. }
  1350. // ----
  1351. // these functions must be inlinable, and not call anybody
  1352. type checkOverflow struct{}
  1353. func (_ checkOverflow) Float32(f float64) (overflow bool) {
  1354. if f < 0 {
  1355. f = -f
  1356. }
  1357. return math.MaxFloat32 < f && f <= math.MaxFloat64
  1358. }
  1359. func (_ checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  1360. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1361. return
  1362. }
  1363. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1364. overflow = true
  1365. }
  1366. return
  1367. }
  1368. func (_ checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  1369. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1370. return
  1371. }
  1372. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1373. overflow = true
  1374. }
  1375. return
  1376. }
  1377. func (_ checkOverflow) SignedInt(v uint64) (i int64, overflow bool) {
  1378. //e.g. -127 to 128 for int8
  1379. pos := (v >> 63) == 0
  1380. ui2 := v & 0x7fffffffffffffff
  1381. if pos {
  1382. if ui2 > math.MaxInt64 {
  1383. overflow = true
  1384. return
  1385. }
  1386. } else {
  1387. if ui2 > math.MaxInt64-1 {
  1388. overflow = true
  1389. return
  1390. }
  1391. }
  1392. i = int64(v)
  1393. return
  1394. }
  1395. // ------------------ SORT -----------------
  1396. func isNaN(f float64) bool { return f != f }
  1397. // -----------------------
  1398. type intSlice []int64
  1399. type uintSlice []uint64
  1400. type uintptrSlice []uintptr
  1401. type floatSlice []float64
  1402. type boolSlice []bool
  1403. type stringSlice []string
  1404. type bytesSlice [][]byte
  1405. func (p intSlice) Len() int { return len(p) }
  1406. func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
  1407. func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1408. func (p uintSlice) Len() int { return len(p) }
  1409. func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
  1410. func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1411. func (p uintptrSlice) Len() int { return len(p) }
  1412. func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] }
  1413. func (p uintptrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1414. func (p floatSlice) Len() int { return len(p) }
  1415. func (p floatSlice) Less(i, j int) bool {
  1416. return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
  1417. }
  1418. func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1419. func (p stringSlice) Len() int { return len(p) }
  1420. func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
  1421. func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1422. func (p bytesSlice) Len() int { return len(p) }
  1423. func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
  1424. func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1425. func (p boolSlice) Len() int { return len(p) }
  1426. func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
  1427. func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1428. // ---------------------
  1429. type intRv struct {
  1430. v int64
  1431. r reflect.Value
  1432. }
  1433. type intRvSlice []intRv
  1434. type uintRv struct {
  1435. v uint64
  1436. r reflect.Value
  1437. }
  1438. type uintRvSlice []uintRv
  1439. type floatRv struct {
  1440. v float64
  1441. r reflect.Value
  1442. }
  1443. type floatRvSlice []floatRv
  1444. type boolRv struct {
  1445. v bool
  1446. r reflect.Value
  1447. }
  1448. type boolRvSlice []boolRv
  1449. type stringRv struct {
  1450. v string
  1451. r reflect.Value
  1452. }
  1453. type stringRvSlice []stringRv
  1454. type bytesRv struct {
  1455. v []byte
  1456. r reflect.Value
  1457. }
  1458. type bytesRvSlice []bytesRv
  1459. func (p intRvSlice) Len() int { return len(p) }
  1460. func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1461. func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1462. func (p uintRvSlice) Len() int { return len(p) }
  1463. func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1464. func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1465. func (p floatRvSlice) Len() int { return len(p) }
  1466. func (p floatRvSlice) Less(i, j int) bool {
  1467. return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
  1468. }
  1469. func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1470. func (p stringRvSlice) Len() int { return len(p) }
  1471. func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1472. func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1473. func (p bytesRvSlice) Len() int { return len(p) }
  1474. func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1475. func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1476. func (p boolRvSlice) Len() int { return len(p) }
  1477. func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
  1478. func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1479. // -----------------
  1480. type bytesI struct {
  1481. v []byte
  1482. i interface{}
  1483. }
  1484. type bytesISlice []bytesI
  1485. func (p bytesISlice) Len() int { return len(p) }
  1486. func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1487. func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1488. // -----------------
  1489. type set []uintptr
  1490. func (s *set) add(v uintptr) (exists bool) {
  1491. // e.ci is always nil, or len >= 1
  1492. x := *s
  1493. if x == nil {
  1494. x = make([]uintptr, 1, 8)
  1495. x[0] = v
  1496. *s = x
  1497. return
  1498. }
  1499. // typically, length will be 1. make this perform.
  1500. if len(x) == 1 {
  1501. if j := x[0]; j == 0 {
  1502. x[0] = v
  1503. } else if j == v {
  1504. exists = true
  1505. } else {
  1506. x = append(x, v)
  1507. *s = x
  1508. }
  1509. return
  1510. }
  1511. // check if it exists
  1512. for _, j := range x {
  1513. if j == v {
  1514. exists = true
  1515. return
  1516. }
  1517. }
  1518. // try to replace a "deleted" slot
  1519. for i, j := range x {
  1520. if j == 0 {
  1521. x[i] = v
  1522. return
  1523. }
  1524. }
  1525. // if unable to replace deleted slot, just append it.
  1526. x = append(x, v)
  1527. *s = x
  1528. return
  1529. }
  1530. func (s *set) remove(v uintptr) (exists bool) {
  1531. x := *s
  1532. if len(x) == 0 {
  1533. return
  1534. }
  1535. if len(x) == 1 {
  1536. if x[0] == v {
  1537. x[0] = 0
  1538. }
  1539. return
  1540. }
  1541. for i, j := range x {
  1542. if j == v {
  1543. exists = true
  1544. x[i] = 0 // set it to 0, as way to delete it.
  1545. // copy(x[i:], x[i+1:])
  1546. // x = x[:len(x)-1]
  1547. return
  1548. }
  1549. }
  1550. return
  1551. }
  1552. // ------
  1553. // bitset types are better than [256]bool, because they permit the whole
  1554. // bitset array being on a single cache line and use less memory.
  1555. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  1556. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  1557. type bitset256 [32]byte
  1558. func (x *bitset256) isset(pos byte) bool {
  1559. return x[pos>>3]&(1<<(pos&7)) != 0
  1560. }
  1561. func (x *bitset256) set(pos byte) {
  1562. x[pos>>3] |= (1 << (pos & 7))
  1563. }
  1564. // func (x *bitset256) unset(pos byte) {
  1565. // x[pos>>3] &^= (1 << (pos & 7))
  1566. // }
  1567. type bitset128 [16]byte
  1568. func (x *bitset128) isset(pos byte) bool {
  1569. return x[pos>>3]&(1<<(pos&7)) != 0
  1570. }
  1571. func (x *bitset128) set(pos byte) {
  1572. x[pos>>3] |= (1 << (pos & 7))
  1573. }
  1574. // func (x *bitset128) unset(pos byte) {
  1575. // x[pos>>3] &^= (1 << (pos & 7))
  1576. // }
  1577. type bitset32 [4]byte
  1578. func (x *bitset32) isset(pos byte) bool {
  1579. return x[pos>>3]&(1<<(pos&7)) != 0
  1580. }
  1581. func (x *bitset32) set(pos byte) {
  1582. x[pos>>3] |= (1 << (pos & 7))
  1583. }
  1584. // func (x *bitset32) unset(pos byte) {
  1585. // x[pos>>3] &^= (1 << (pos & 7))
  1586. // }
  1587. // ------------
  1588. type pooler struct {
  1589. // for stringRV
  1590. strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool
  1591. // for the decNaked
  1592. dn sync.Pool
  1593. tiload sync.Pool
  1594. }
  1595. func (p *pooler) init() {
  1596. p.strRv8.New = func() interface{} { return new([8]stringRv) }
  1597. p.strRv16.New = func() interface{} { return new([16]stringRv) }
  1598. p.strRv32.New = func() interface{} { return new([32]stringRv) }
  1599. p.strRv64.New = func() interface{} { return new([64]stringRv) }
  1600. p.strRv128.New = func() interface{} { return new([128]stringRv) }
  1601. p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
  1602. p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
  1603. }
  1604. func (p *pooler) stringRv8() (sp *sync.Pool, v interface{}) {
  1605. return &p.strRv8, p.strRv8.Get()
  1606. }
  1607. func (p *pooler) stringRv16() (sp *sync.Pool, v interface{}) {
  1608. return &p.strRv16, p.strRv16.Get()
  1609. }
  1610. func (p *pooler) stringRv32() (sp *sync.Pool, v interface{}) {
  1611. return &p.strRv32, p.strRv32.Get()
  1612. }
  1613. func (p *pooler) stringRv64() (sp *sync.Pool, v interface{}) {
  1614. return &p.strRv64, p.strRv64.Get()
  1615. }
  1616. func (p *pooler) stringRv128() (sp *sync.Pool, v interface{}) {
  1617. return &p.strRv128, p.strRv128.Get()
  1618. }
  1619. func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
  1620. return &p.dn, p.dn.Get()
  1621. }
  1622. func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
  1623. return &p.tiload, p.tiload.Get()
  1624. }