helper.go 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  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. // AddExt registes an encode and decode function for a reflect.Type.
  508. // AddExt internally calls SetExt.
  509. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  510. //
  511. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  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. // Note that the type must be a named type, and specifically not
  522. // a pointer or Interface. An error is returned if that is not honored.
  523. // To Deregister an ext, call SetExt with nil Ext.
  524. //
  525. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  526. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  527. // o is a pointer, because we may need to initialize it
  528. if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
  529. err = fmt.Errorf("codec.Handle.AddExt: Takes named type, not a pointer or interface: %T",
  530. reflect.Zero(rt).Interface())
  531. return
  532. }
  533. rtid := rt2id(rt)
  534. for _, v := range *o {
  535. if v.rtid == rtid {
  536. v.tag, v.ext = tag, ext
  537. return
  538. }
  539. }
  540. if *o == nil {
  541. *o = make([]extTypeTagFn, 0, 4)
  542. }
  543. *o = append(*o, extTypeTagFn{rtid, rt, tag, ext})
  544. return
  545. }
  546. func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
  547. var v *extTypeTagFn
  548. for i := range o {
  549. v = &o[i]
  550. if v.rtid == rtid {
  551. return v
  552. }
  553. }
  554. return nil
  555. }
  556. func (o extHandle) getExtForTag(tag uint64) *extTypeTagFn {
  557. var v *extTypeTagFn
  558. for i := range o {
  559. v = &o[i]
  560. if v.tag == tag {
  561. return v
  562. }
  563. }
  564. return nil
  565. }
  566. const maxLevelsEmbedding = 16
  567. type structFieldInfo struct {
  568. encName string // encode name
  569. fieldName string // field name
  570. is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
  571. nis uint8 // num levels of embedding. if 1, then it's not embedded.
  572. omitEmpty bool
  573. toArray bool // if field is _struct, is the toArray set?
  574. }
  575. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  576. if v, valid := si.field(v, false); valid {
  577. v.Set(reflect.Zero(v.Type()))
  578. }
  579. }
  580. // rv returns the field of the struct.
  581. // If anonymous, it returns an Invalid
  582. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
  583. // replicate FieldByIndex
  584. for i, x := range si.is {
  585. if uint8(i) == si.nis {
  586. break
  587. }
  588. if v, valid = baseStructRv(v, update); !valid {
  589. return
  590. }
  591. v = v.Field(int(x))
  592. }
  593. return v, true
  594. }
  595. // func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
  596. // v, _ = si.field(v, update)
  597. // return v
  598. // }
  599. func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
  600. // if fname == "" {
  601. // panic(noFieldNameToStructFieldInfoErr)
  602. // }
  603. si := structFieldInfo{
  604. encName: fname,
  605. }
  606. if stag != "" {
  607. for i, s := range strings.Split(stag, ",") {
  608. if i == 0 {
  609. if s != "" {
  610. si.encName = s
  611. }
  612. } else {
  613. if s == "omitempty" {
  614. si.omitEmpty = true
  615. } else if s == "toarray" {
  616. si.toArray = true
  617. }
  618. }
  619. }
  620. }
  621. // si.encNameBs = []byte(si.encName)
  622. return &si
  623. }
  624. type sfiSortedByEncName []*structFieldInfo
  625. func (p sfiSortedByEncName) Len() int {
  626. return len(p)
  627. }
  628. func (p sfiSortedByEncName) Less(i, j int) bool {
  629. return p[i].encName < p[j].encName
  630. }
  631. func (p sfiSortedByEncName) Swap(i, j int) {
  632. p[i], p[j] = p[j], p[i]
  633. }
  634. const structFieldNodeNumToCache = 4
  635. type structFieldNodeCache struct {
  636. rv [structFieldNodeNumToCache]reflect.Value
  637. idx [structFieldNodeNumToCache]uint32
  638. num uint8
  639. }
  640. func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
  641. // defer func() { fmt.Printf(">>>> found in cache2? %v\n", valid) }()
  642. for i, k := range &x.idx {
  643. if uint8(i) == x.num {
  644. return // break
  645. }
  646. if key == k {
  647. return x.rv[i], true
  648. }
  649. }
  650. return
  651. }
  652. func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
  653. if x.num < structFieldNodeNumToCache {
  654. x.rv[x.num] = fv
  655. x.idx[x.num] = key
  656. x.num++
  657. return
  658. }
  659. }
  660. type structFieldNode struct {
  661. v reflect.Value
  662. cache2 structFieldNodeCache
  663. cache3 structFieldNodeCache
  664. update bool
  665. }
  666. func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
  667. // return si.fieldval(x.v, x.update)
  668. // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
  669. // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
  670. var valid bool
  671. switch si.nis {
  672. case 1:
  673. fv = x.v.Field(int(si.is[0]))
  674. case 2:
  675. if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
  676. fv = fv.Field(int(si.is[1]))
  677. return
  678. }
  679. fv = x.v.Field(int(si.is[0]))
  680. if fv, valid = baseStructRv(fv, x.update); !valid {
  681. return
  682. }
  683. x.cache2.tryAdd(fv, uint32(si.is[0]))
  684. fv = fv.Field(int(si.is[1]))
  685. case 3:
  686. var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
  687. if fv, valid = x.cache3.get(key); valid {
  688. fv = fv.Field(int(si.is[2]))
  689. return
  690. }
  691. fv = x.v.Field(int(si.is[0]))
  692. if fv, valid = baseStructRv(fv, x.update); !valid {
  693. return
  694. }
  695. fv = fv.Field(int(si.is[1]))
  696. if fv, valid = baseStructRv(fv, x.update); !valid {
  697. return
  698. }
  699. x.cache3.tryAdd(fv, key)
  700. fv = fv.Field(int(si.is[2]))
  701. default:
  702. fv, _ = si.field(x.v, x.update)
  703. }
  704. return
  705. }
  706. func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
  707. for v.Kind() == reflect.Ptr {
  708. if v.IsNil() {
  709. if !update {
  710. return
  711. }
  712. v.Set(reflect.New(v.Type().Elem()))
  713. }
  714. v = v.Elem()
  715. }
  716. return v, true
  717. }
  718. // typeInfo keeps information about each (non-ptr) type referenced in the encode/decode sequence.
  719. //
  720. // During an encode/decode sequence, we work as below:
  721. // - If base is a built in type, en/decode base value
  722. // - If base is registered as an extension, en/decode base value
  723. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  724. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  725. // - Else decode appropriately based on the reflect.Kind
  726. type typeInfo struct {
  727. sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
  728. sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  729. rt reflect.Type
  730. rtid uintptr
  731. // rv0 reflect.Value // saved zero value, used if immutableKind
  732. numMeth uint16 // number of methods
  733. anyOmitEmpty bool
  734. mbs bool // base type (T or *T) is a MapBySlice
  735. // format of marshal type fields below: [btj][mu]p? OR csp?
  736. bm bool // T is a binaryMarshaler
  737. bmp bool // *T is a binaryMarshaler
  738. bu bool // T is a binaryUnmarshaler
  739. bup bool // *T is a binaryUnmarshaler
  740. tm bool // T is a textMarshaler
  741. tmp bool // *T is a textMarshaler
  742. tu bool // T is a textUnmarshaler
  743. tup bool // *T is a textUnmarshaler
  744. jm bool // T is a jsonMarshaler
  745. jmp bool // *T is a jsonMarshaler
  746. ju bool // T is a jsonUnmarshaler
  747. jup bool // *T is a jsonUnmarshaler
  748. cs bool // T is a Selfer
  749. csp bool // *T is a Selfer
  750. toArray bool // whether this (struct) type should be encoded as an array
  751. }
  752. // define length beyond which we do a binary search instead of a linear search.
  753. // From our testing, linear search seems faster than binary search up to 16-field structs.
  754. // However, we set to 8 similar to what python does for hashtables.
  755. const indexForEncNameBinarySearchThreshold = 8
  756. func (ti *typeInfo) indexForEncName(name string) int {
  757. // NOTE: name may be a stringView, so don't pass it to another function.
  758. //tisfi := ti.sfi
  759. sfilen := len(ti.sfi)
  760. if sfilen < indexForEncNameBinarySearchThreshold {
  761. for i, si := range ti.sfi {
  762. if si.encName == name {
  763. return i
  764. }
  765. }
  766. return -1
  767. }
  768. // binary search. adapted from sort/search.go.
  769. h, i, j := 0, 0, sfilen
  770. for i < j {
  771. h = i + (j-i)/2
  772. if ti.sfi[h].encName < name {
  773. i = h + 1
  774. } else {
  775. j = h
  776. }
  777. }
  778. if i < sfilen && ti.sfi[i].encName == name {
  779. return i
  780. }
  781. return -1
  782. }
  783. type rtid2ti struct {
  784. rtid uintptr
  785. ti *typeInfo
  786. }
  787. // TypeInfos caches typeInfo for each type on first inspection.
  788. //
  789. // It is configured with a set of tag keys, which are used to get
  790. // configuration for the type.
  791. type TypeInfos struct {
  792. infos atomicTypeInfoSlice // formerly map[uintptr]*typeInfo, now *[]rtid2ti
  793. mu sync.Mutex
  794. tags []string
  795. }
  796. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  797. //
  798. // This allows users customize the struct tag keys which contain configuration
  799. // of their types.
  800. func NewTypeInfos(tags []string) *TypeInfos {
  801. return &TypeInfos{tags: tags}
  802. }
  803. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  804. // check for tags: codec, json, in that order.
  805. // this allows seamless support for many configured structs.
  806. for _, x := range x.tags {
  807. s = t.Get(x)
  808. if s != "" {
  809. return s
  810. }
  811. }
  812. return
  813. }
  814. func (x *TypeInfos) find(sp *[]rtid2ti, rtid uintptr) (idx int, ti *typeInfo) {
  815. // binary search. adapted from sort/search.go.
  816. // if sp == nil {
  817. // return -1, nil
  818. // }
  819. s := *sp
  820. h, i, j := 0, 0, len(s)
  821. for i < j {
  822. h = i + (j-i)/2
  823. if s[h].rtid < rtid {
  824. i = h + 1
  825. } else {
  826. j = h
  827. }
  828. }
  829. if i < len(s) && s[i].rtid == rtid {
  830. return i, s[i].ti
  831. }
  832. return i, nil
  833. }
  834. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  835. sp := x.infos.load()
  836. var idx int
  837. if sp != nil {
  838. idx, pti = x.find(sp, rtid)
  839. if pti != nil {
  840. return
  841. }
  842. }
  843. rk := rt.Kind()
  844. if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) {
  845. panic(fmt.Errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt))
  846. }
  847. // do not hold lock while computing this.
  848. // it may lead to duplication, but that's ok.
  849. ti := typeInfo{rt: rt, rtid: rtid}
  850. // ti.rv0 = reflect.Zero(rt)
  851. ti.numMeth = uint16(rt.NumMethod())
  852. ti.bm, ti.bmp = implIntf(rt, binaryMarshalerTyp)
  853. ti.bu, ti.bup = implIntf(rt, binaryUnmarshalerTyp)
  854. ti.tm, ti.tmp = implIntf(rt, textMarshalerTyp)
  855. ti.tu, ti.tup = implIntf(rt, textUnmarshalerTyp)
  856. ti.jm, ti.jmp = implIntf(rt, jsonMarshalerTyp)
  857. ti.ju, ti.jup = implIntf(rt, jsonUnmarshalerTyp)
  858. ti.cs, ti.csp = implIntf(rt, selferTyp)
  859. ti.mbs, _ = implIntf(rt, mapBySliceTyp)
  860. if rk == reflect.Struct {
  861. var omitEmpty bool
  862. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  863. siInfo := parseStructFieldInfo(structInfoFieldName, x.structTag(f.Tag))
  864. ti.toArray = siInfo.toArray
  865. omitEmpty = siInfo.omitEmpty
  866. }
  867. pp, pi := pool.tiLoad()
  868. pv := pi.(*typeInfoLoadArray)
  869. pv.etypes[0] = ti.rtid
  870. vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  871. x.rget(rt, rtid, omitEmpty, nil, &vv)
  872. ti.sfip, ti.sfi, ti.anyOmitEmpty = rgetResolveSFI(vv.sfis, pv.sfiidx[:0])
  873. pp.Put(pi)
  874. }
  875. // sfi = sfip
  876. var vs []rtid2ti
  877. x.mu.Lock()
  878. sp = x.infos.load()
  879. if sp == nil {
  880. pti = &ti
  881. vs = []rtid2ti{{rtid, pti}}
  882. x.infos.store(&vs)
  883. } else {
  884. idx, pti = x.find(sp, rtid)
  885. if pti == nil {
  886. s := *sp
  887. pti = &ti
  888. vs = make([]rtid2ti, len(s)+1)
  889. copy(vs, s[:idx])
  890. vs[idx] = rtid2ti{rtid, pti}
  891. copy(vs[idx+1:], s[idx:])
  892. x.infos.store(&vs)
  893. }
  894. }
  895. x.mu.Unlock()
  896. return
  897. }
  898. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  899. indexstack []uint16, pv *typeInfoLoad,
  900. ) {
  901. // Read up fields and store how to access the value.
  902. //
  903. // It uses go's rules for message selectors,
  904. // which say that the field with the shallowest depth is selected.
  905. //
  906. // Note: we consciously use slices, not a map, to simulate a set.
  907. // Typically, types have < 16 fields,
  908. // and iteration using equals is faster than maps there
  909. flen := rt.NumField()
  910. if flen > (1<<maxLevelsEmbedding - 1) {
  911. panic(fmt.Errorf("codec: types with more than %v fields are not supported - has %v fields", (1<<maxLevelsEmbedding - 1), flen))
  912. }
  913. LOOP:
  914. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  915. f := rt.Field(int(j))
  916. fkind := f.Type.Kind()
  917. // skip if a func type, or is unexported, or structTag value == "-"
  918. switch fkind {
  919. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  920. continue LOOP
  921. }
  922. // if r1, _ := utf8.DecodeRuneInString(f.Name);
  923. // r1 == utf8.RuneError || !unicode.IsUpper(r1) {
  924. if f.PkgPath != "" && !f.Anonymous { // unexported, not embedded
  925. continue
  926. }
  927. stag := x.structTag(f.Tag)
  928. if stag == "-" {
  929. continue
  930. }
  931. var si *structFieldInfo
  932. // if anonymous and no struct tag (or it's blank),
  933. // and a struct (or pointer to struct), inline it.
  934. if f.Anonymous && fkind != reflect.Interface {
  935. doInline := stag == ""
  936. if !doInline {
  937. si = parseStructFieldInfo("", stag)
  938. doInline = si.encName == ""
  939. // doInline = si.isZero()
  940. }
  941. if doInline {
  942. ft := f.Type
  943. for ft.Kind() == reflect.Ptr {
  944. ft = ft.Elem()
  945. }
  946. if ft.Kind() == reflect.Struct {
  947. // if etypes contains this, don't call rget again (as fields are already seen here)
  948. ftid := rt2id(ft)
  949. // We cannot recurse forever, but we need to track other field depths.
  950. // So - we break if we see a type twice (not the first time).
  951. // This should be sufficient to handle an embedded type that refers to its
  952. // owning type, which then refers to its embedded type.
  953. processIt := true
  954. numk := 0
  955. for _, k := range pv.etypes {
  956. if k == ftid {
  957. numk++
  958. if numk == rgetMaxRecursion {
  959. processIt = false
  960. break
  961. }
  962. }
  963. }
  964. if processIt {
  965. pv.etypes = append(pv.etypes, ftid)
  966. indexstack2 := make([]uint16, len(indexstack)+1)
  967. copy(indexstack2, indexstack)
  968. indexstack2[len(indexstack)] = j
  969. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  970. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  971. }
  972. continue
  973. }
  974. }
  975. }
  976. // after the anonymous dance: if an unexported field, skip
  977. if f.PkgPath != "" { // unexported
  978. continue
  979. }
  980. if f.Name == "" {
  981. panic(noFieldNameToStructFieldInfoErr)
  982. }
  983. pv.fNames = append(pv.fNames, f.Name)
  984. if si == nil {
  985. si = parseStructFieldInfo(f.Name, stag)
  986. } else if si.encName == "" {
  987. si.encName = f.Name
  988. }
  989. si.fieldName = f.Name
  990. pv.encNames = append(pv.encNames, si.encName)
  991. // si.ikind = int(f.Type.Kind())
  992. if len(indexstack) > maxLevelsEmbedding-1 {
  993. panic(fmt.Errorf("codec: only supports up to %v depth of embedding - type has %v depth", maxLevelsEmbedding-1, len(indexstack)))
  994. }
  995. si.nis = uint8(len(indexstack)) + 1
  996. copy(si.is[:], indexstack)
  997. si.is[len(indexstack)] = j
  998. if omitEmpty {
  999. si.omitEmpty = true
  1000. }
  1001. pv.sfis = append(pv.sfis, si)
  1002. }
  1003. }
  1004. // resolves the struct field info got from a call to rget.
  1005. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  1006. func rgetResolveSFI(x []*structFieldInfo, pv []sfiIdx) (y, z []*structFieldInfo, anyOmitEmpty bool) {
  1007. var n int
  1008. for i, v := range x {
  1009. xn := v.encName // TODO: fieldName or encName? use encName for now.
  1010. var found bool
  1011. for j, k := range pv {
  1012. if k.name == xn {
  1013. // one of them must be reset to nil, and the index updated appropriately to the other one
  1014. if v.nis == x[k.index].nis {
  1015. } else if v.nis < x[k.index].nis {
  1016. pv[j].index = i
  1017. if x[k.index] != nil {
  1018. x[k.index] = nil
  1019. n++
  1020. }
  1021. } else {
  1022. if x[i] != nil {
  1023. x[i] = nil
  1024. n++
  1025. }
  1026. }
  1027. found = true
  1028. break
  1029. }
  1030. }
  1031. if !found {
  1032. pv = append(pv, sfiIdx{xn, i})
  1033. }
  1034. }
  1035. // remove all the nils
  1036. y = make([]*structFieldInfo, len(x)-n)
  1037. n = 0
  1038. for _, v := range x {
  1039. if v == nil {
  1040. continue
  1041. }
  1042. if !anyOmitEmpty && v.omitEmpty {
  1043. anyOmitEmpty = true
  1044. }
  1045. y[n] = v
  1046. n++
  1047. }
  1048. z = make([]*structFieldInfo, len(y))
  1049. copy(z, y)
  1050. sort.Sort(sfiSortedByEncName(z))
  1051. return
  1052. }
  1053. func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) {
  1054. return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp)
  1055. }
  1056. func xprintf(format string, a ...interface{}) {
  1057. if xDebug {
  1058. fmt.Fprintf(os.Stderr, format, a...)
  1059. }
  1060. }
  1061. func panicToErr(err *error) {
  1062. if recoverPanicToErr {
  1063. if x := recover(); x != nil {
  1064. // if false && xDebug {
  1065. // fmt.Printf("panic'ing with: %v\n", x)
  1066. // debug.PrintStack()
  1067. // }
  1068. panicValToErr(x, err)
  1069. }
  1070. }
  1071. }
  1072. func panicToErrs2(err1, err2 *error) {
  1073. if recoverPanicToErr {
  1074. if x := recover(); x != nil {
  1075. panicValToErr(x, err1)
  1076. panicValToErr(x, err2)
  1077. }
  1078. }
  1079. }
  1080. // func doPanic(tag string, format string, params ...interface{}) {
  1081. // params2 := make([]interface{}, len(params)+1)
  1082. // params2[0] = tag
  1083. // copy(params2[1:], params)
  1084. // panic(fmt.Errorf("%s: "+format, params2...))
  1085. // }
  1086. func isImmutableKind(k reflect.Kind) (v bool) {
  1087. return immutableKindsSet[k]
  1088. // return false ||
  1089. // k == reflect.Int ||
  1090. // k == reflect.Int8 ||
  1091. // k == reflect.Int16 ||
  1092. // k == reflect.Int32 ||
  1093. // k == reflect.Int64 ||
  1094. // k == reflect.Uint ||
  1095. // k == reflect.Uint8 ||
  1096. // k == reflect.Uint16 ||
  1097. // k == reflect.Uint32 ||
  1098. // k == reflect.Uint64 ||
  1099. // k == reflect.Uintptr ||
  1100. // k == reflect.Float32 ||
  1101. // k == reflect.Float64 ||
  1102. // k == reflect.Bool ||
  1103. // k == reflect.String
  1104. }
  1105. // ----
  1106. type codecFnInfo struct {
  1107. ti *typeInfo
  1108. xfFn Ext
  1109. xfTag uint64
  1110. seq seqType
  1111. addrD bool
  1112. addrE bool
  1113. }
  1114. // codecFn encapsulates the captured variables and the encode function.
  1115. // This way, we only do some calculations one times, and pass to the
  1116. // code block that should be called (encapsulated in a function)
  1117. // instead of executing the checks every time.
  1118. type codecFn struct {
  1119. i codecFnInfo
  1120. fe func(*Encoder, *codecFnInfo, reflect.Value)
  1121. fd func(*Decoder, *codecFnInfo, reflect.Value)
  1122. }
  1123. type codecRtidFn struct {
  1124. rtid uintptr
  1125. fn codecFn
  1126. }
  1127. type codecFner struct {
  1128. hh Handle
  1129. h *BasicHandle
  1130. cs [arrayCacheLen]*[arrayCacheLen]codecRtidFn
  1131. s []*[arrayCacheLen]codecRtidFn
  1132. sn uint32
  1133. be bool
  1134. js bool
  1135. cf [arrayCacheLen]codecRtidFn
  1136. }
  1137. func (c *codecFner) reset(hh Handle) {
  1138. c.hh = hh
  1139. c.h = hh.getBasicHandle()
  1140. _, c.js = hh.(*JsonHandle)
  1141. c.be = hh.isBinary()
  1142. }
  1143. func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
  1144. rtid := rt2id(rt)
  1145. var j uint32
  1146. var sn uint32 = c.sn
  1147. if sn == 0 {
  1148. c.s = c.cs[:1]
  1149. c.s[0] = &c.cf
  1150. c.cf[0].rtid = rtid
  1151. fn = &(c.cf[0].fn)
  1152. c.sn = 1
  1153. } else {
  1154. LOOP1:
  1155. for _, x := range c.s {
  1156. for i := range x {
  1157. if j == sn {
  1158. break LOOP1
  1159. }
  1160. if x[i].rtid == rtid {
  1161. fn = &(x[i].fn)
  1162. return
  1163. }
  1164. j++
  1165. }
  1166. }
  1167. sx, sy := sn/arrayCacheLen, sn%arrayCacheLen
  1168. if sy == 0 {
  1169. c.s = append(c.s, &[arrayCacheLen]codecRtidFn{})
  1170. }
  1171. c.s[sx][sy].rtid = rtid
  1172. fn = &(c.s[sx][sy].fn)
  1173. c.sn++
  1174. }
  1175. ti := c.h.getTypeInfo(rtid, rt)
  1176. fi := &(fn.i)
  1177. fi.ti = ti
  1178. rk := rt.Kind()
  1179. if checkCodecSelfer && (ti.cs || ti.csp) {
  1180. fn.fe = (*Encoder).selferMarshal
  1181. fn.fd = (*Decoder).selferUnmarshal
  1182. fi.addrD = ti.csp
  1183. fi.addrE = ti.csp
  1184. } else if rtid == rawTypId {
  1185. fn.fe = (*Encoder).raw
  1186. fn.fd = (*Decoder).raw
  1187. } else if rtid == rawExtTypId {
  1188. fn.fe = (*Encoder).rawExt
  1189. fn.fd = (*Decoder).rawExt
  1190. fi.addrD = true
  1191. fi.addrE = true
  1192. } else if c.hh.IsBuiltinType(rtid) {
  1193. fn.fe = (*Encoder).builtin
  1194. fn.fd = (*Decoder).builtin
  1195. fi.addrD = true
  1196. } else if xfFn := c.h.getExt(rtid); xfFn != nil {
  1197. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  1198. fn.fe = (*Encoder).ext
  1199. fn.fd = (*Decoder).ext
  1200. fi.addrD = true
  1201. if rk == reflect.Struct || rk == reflect.Array {
  1202. fi.addrE = true
  1203. }
  1204. } else if supportMarshalInterfaces && c.be && (ti.bm || ti.bmp) && (ti.bu || ti.bup) {
  1205. fn.fe = (*Encoder).binaryMarshal
  1206. fn.fd = (*Decoder).binaryUnmarshal
  1207. fi.addrD = ti.bup
  1208. fi.addrE = ti.bmp
  1209. } else if supportMarshalInterfaces && !c.be && c.js && (ti.jm || ti.jmp) && (ti.ju || ti.jup) {
  1210. //If JSON, we should check JSONMarshal before textMarshal
  1211. fn.fe = (*Encoder).jsonMarshal
  1212. fn.fd = (*Decoder).jsonUnmarshal
  1213. fi.addrD = ti.jup
  1214. fi.addrE = ti.jmp
  1215. } else if supportMarshalInterfaces && !c.be && (ti.tm || ti.tmp) && (ti.tu || ti.tup) {
  1216. fn.fe = (*Encoder).textMarshal
  1217. fn.fd = (*Decoder).textUnmarshal
  1218. fi.addrD = ti.tup
  1219. fi.addrE = ti.tmp
  1220. } else {
  1221. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  1222. if rt.PkgPath() == "" { // un-named slice or map
  1223. if idx := fastpathAV.index(rtid); idx != -1 {
  1224. fn.fe = fastpathAV[idx].encfn
  1225. fn.fd = fastpathAV[idx].decfn
  1226. fi.addrD = true
  1227. }
  1228. } else {
  1229. // use mapping for underlying type if there
  1230. var rtu reflect.Type
  1231. if rk == reflect.Map {
  1232. rtu = reflect.MapOf(rt.Key(), rt.Elem())
  1233. } else {
  1234. rtu = reflect.SliceOf(rt.Elem())
  1235. }
  1236. rtuid := rt2id(rtu)
  1237. if idx := fastpathAV.index(rtuid); idx != -1 {
  1238. xfnf := fastpathAV[idx].encfn
  1239. xrt := fastpathAV[idx].rt
  1240. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  1241. xfnf(e, xf, xrv.Convert(xrt))
  1242. }
  1243. fi.addrD = true
  1244. xfnf2 := fastpathAV[idx].decfn
  1245. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1246. xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
  1247. }
  1248. }
  1249. }
  1250. }
  1251. if fn.fe == nil && fn.fd == nil {
  1252. switch rk {
  1253. case reflect.Bool:
  1254. fn.fe = (*Encoder).kBool
  1255. fn.fd = (*Decoder).kBool
  1256. case reflect.String:
  1257. fn.fe = (*Encoder).kString
  1258. fn.fd = (*Decoder).kString
  1259. case reflect.Int:
  1260. fn.fd = (*Decoder).kInt
  1261. fn.fe = (*Encoder).kInt
  1262. case reflect.Int8:
  1263. fn.fe = (*Encoder).kInt8
  1264. fn.fd = (*Decoder).kInt8
  1265. case reflect.Int16:
  1266. fn.fe = (*Encoder).kInt16
  1267. fn.fd = (*Decoder).kInt16
  1268. case reflect.Int32:
  1269. fn.fe = (*Encoder).kInt32
  1270. fn.fd = (*Decoder).kInt32
  1271. case reflect.Int64:
  1272. fn.fe = (*Encoder).kInt64
  1273. fn.fd = (*Decoder).kInt64
  1274. case reflect.Uint:
  1275. fn.fd = (*Decoder).kUint
  1276. fn.fe = (*Encoder).kUint
  1277. case reflect.Uint8:
  1278. fn.fe = (*Encoder).kUint8
  1279. fn.fd = (*Decoder).kUint8
  1280. case reflect.Uint16:
  1281. fn.fe = (*Encoder).kUint16
  1282. fn.fd = (*Decoder).kUint16
  1283. case reflect.Uint32:
  1284. fn.fe = (*Encoder).kUint32
  1285. fn.fd = (*Decoder).kUint32
  1286. case reflect.Uint64:
  1287. fn.fe = (*Encoder).kUint64
  1288. fn.fd = (*Decoder).kUint64
  1289. // case reflect.Ptr:
  1290. // fn.fd = (*Decoder).kPtr
  1291. case reflect.Uintptr:
  1292. fn.fe = (*Encoder).kUintptr
  1293. fn.fd = (*Decoder).kUintptr
  1294. case reflect.Float32:
  1295. fn.fe = (*Encoder).kFloat32
  1296. fn.fd = (*Decoder).kFloat32
  1297. case reflect.Float64:
  1298. fn.fe = (*Encoder).kFloat64
  1299. fn.fd = (*Decoder).kFloat64
  1300. case reflect.Invalid:
  1301. fn.fe = (*Encoder).kInvalid
  1302. fn.fd = (*Decoder).kErr
  1303. case reflect.Chan:
  1304. fi.seq = seqTypeChan
  1305. fn.fe = (*Encoder).kSlice
  1306. fn.fd = (*Decoder).kSlice
  1307. case reflect.Slice:
  1308. fi.seq = seqTypeSlice
  1309. fn.fe = (*Encoder).kSlice
  1310. fn.fd = (*Decoder).kSlice
  1311. case reflect.Array:
  1312. fi.seq = seqTypeArray
  1313. fn.fe = (*Encoder).kSlice
  1314. fi.addrD = false
  1315. rt2 := reflect.SliceOf(rt.Elem())
  1316. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1317. // println(">>>>>> decoding an array ... ")
  1318. d.cf.get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
  1319. // println(">>>>>> decoding an array ... DONE")
  1320. }
  1321. // fn.fd = (*Decoder).kArray
  1322. case reflect.Struct:
  1323. if ti.anyOmitEmpty {
  1324. fn.fe = (*Encoder).kStruct
  1325. } else {
  1326. fn.fe = (*Encoder).kStructNoOmitempty
  1327. }
  1328. fn.fd = (*Decoder).kStruct
  1329. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  1330. // case reflect.Ptr:
  1331. // fn.fe = (*Encoder).kPtr
  1332. // case reflect.Interface:
  1333. // fn.fe = (*Encoder).kInterface
  1334. case reflect.Map:
  1335. fn.fe = (*Encoder).kMap
  1336. fn.fd = (*Decoder).kMap
  1337. case reflect.Interface:
  1338. // encode: reflect.Interface are handled already by preEncodeValue
  1339. fn.fd = (*Decoder).kInterface
  1340. fn.fe = (*Encoder).kErr
  1341. default:
  1342. fn.fe = (*Encoder).kErr
  1343. fn.fd = (*Decoder).kErr
  1344. }
  1345. }
  1346. }
  1347. return
  1348. }
  1349. // ----
  1350. // these functions must be inlinable, and not call anybody
  1351. type checkOverflow struct{}
  1352. func (_ checkOverflow) Float32(f float64) (overflow bool) {
  1353. if f < 0 {
  1354. f = -f
  1355. }
  1356. return math.MaxFloat32 < f && f <= math.MaxFloat64
  1357. }
  1358. func (_ checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  1359. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1360. return
  1361. }
  1362. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1363. overflow = true
  1364. }
  1365. return
  1366. }
  1367. func (_ checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  1368. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1369. return
  1370. }
  1371. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1372. overflow = true
  1373. }
  1374. return
  1375. }
  1376. func (_ checkOverflow) SignedInt(v uint64) (i int64, overflow bool) {
  1377. //e.g. -127 to 128 for int8
  1378. pos := (v >> 63) == 0
  1379. ui2 := v & 0x7fffffffffffffff
  1380. if pos {
  1381. if ui2 > math.MaxInt64 {
  1382. overflow = true
  1383. return
  1384. }
  1385. } else {
  1386. if ui2 > math.MaxInt64-1 {
  1387. overflow = true
  1388. return
  1389. }
  1390. }
  1391. i = int64(v)
  1392. return
  1393. }
  1394. // ------------------ SORT -----------------
  1395. func isNaN(f float64) bool { return f != f }
  1396. // -----------------------
  1397. type ioFlusher interface {
  1398. Flush() error
  1399. }
  1400. // -----------------------
  1401. type intSlice []int64
  1402. type uintSlice []uint64
  1403. type uintptrSlice []uintptr
  1404. type floatSlice []float64
  1405. type boolSlice []bool
  1406. type stringSlice []string
  1407. type bytesSlice [][]byte
  1408. func (p intSlice) Len() int { return len(p) }
  1409. func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
  1410. func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1411. func (p uintSlice) Len() int { return len(p) }
  1412. func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
  1413. func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1414. func (p uintptrSlice) Len() int { return len(p) }
  1415. func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] }
  1416. func (p uintptrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1417. func (p floatSlice) Len() int { return len(p) }
  1418. func (p floatSlice) Less(i, j int) bool {
  1419. return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
  1420. }
  1421. func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1422. func (p stringSlice) Len() int { return len(p) }
  1423. func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
  1424. func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1425. func (p bytesSlice) Len() int { return len(p) }
  1426. func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
  1427. func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1428. func (p boolSlice) Len() int { return len(p) }
  1429. func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
  1430. func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1431. // ---------------------
  1432. type intRv struct {
  1433. v int64
  1434. r reflect.Value
  1435. }
  1436. type intRvSlice []intRv
  1437. type uintRv struct {
  1438. v uint64
  1439. r reflect.Value
  1440. }
  1441. type uintRvSlice []uintRv
  1442. type floatRv struct {
  1443. v float64
  1444. r reflect.Value
  1445. }
  1446. type floatRvSlice []floatRv
  1447. type boolRv struct {
  1448. v bool
  1449. r reflect.Value
  1450. }
  1451. type boolRvSlice []boolRv
  1452. type stringRv struct {
  1453. v string
  1454. r reflect.Value
  1455. }
  1456. type stringRvSlice []stringRv
  1457. type bytesRv struct {
  1458. v []byte
  1459. r reflect.Value
  1460. }
  1461. type bytesRvSlice []bytesRv
  1462. func (p intRvSlice) Len() int { return len(p) }
  1463. func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1464. func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1465. func (p uintRvSlice) Len() int { return len(p) }
  1466. func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1467. func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1468. func (p floatRvSlice) Len() int { return len(p) }
  1469. func (p floatRvSlice) Less(i, j int) bool {
  1470. return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
  1471. }
  1472. func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1473. func (p stringRvSlice) Len() int { return len(p) }
  1474. func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1475. func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1476. func (p bytesRvSlice) Len() int { return len(p) }
  1477. func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1478. func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1479. func (p boolRvSlice) Len() int { return len(p) }
  1480. func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
  1481. func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1482. // -----------------
  1483. type bytesI struct {
  1484. v []byte
  1485. i interface{}
  1486. }
  1487. type bytesISlice []bytesI
  1488. func (p bytesISlice) Len() int { return len(p) }
  1489. func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1490. func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1491. // -----------------
  1492. type set []uintptr
  1493. func (s *set) add(v uintptr) (exists bool) {
  1494. // e.ci is always nil, or len >= 1
  1495. x := *s
  1496. if x == nil {
  1497. x = make([]uintptr, 1, 8)
  1498. x[0] = v
  1499. *s = x
  1500. return
  1501. }
  1502. // typically, length will be 1. make this perform.
  1503. if len(x) == 1 {
  1504. if j := x[0]; j == 0 {
  1505. x[0] = v
  1506. } else if j == v {
  1507. exists = true
  1508. } else {
  1509. x = append(x, v)
  1510. *s = x
  1511. }
  1512. return
  1513. }
  1514. // check if it exists
  1515. for _, j := range x {
  1516. if j == v {
  1517. exists = true
  1518. return
  1519. }
  1520. }
  1521. // try to replace a "deleted" slot
  1522. for i, j := range x {
  1523. if j == 0 {
  1524. x[i] = v
  1525. return
  1526. }
  1527. }
  1528. // if unable to replace deleted slot, just append it.
  1529. x = append(x, v)
  1530. *s = x
  1531. return
  1532. }
  1533. func (s *set) remove(v uintptr) (exists bool) {
  1534. x := *s
  1535. if len(x) == 0 {
  1536. return
  1537. }
  1538. if len(x) == 1 {
  1539. if x[0] == v {
  1540. x[0] = 0
  1541. }
  1542. return
  1543. }
  1544. for i, j := range x {
  1545. if j == v {
  1546. exists = true
  1547. x[i] = 0 // set it to 0, as way to delete it.
  1548. // copy(x[i:], x[i+1:])
  1549. // x = x[:len(x)-1]
  1550. return
  1551. }
  1552. }
  1553. return
  1554. }
  1555. // ------
  1556. // bitset types are better than [256]bool, because they permit the whole
  1557. // bitset array being on a single cache line and use less memory.
  1558. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  1559. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  1560. type bitset256 [32]byte
  1561. func (x *bitset256) isset(pos byte) bool {
  1562. return x[pos>>3]&(1<<(pos&7)) != 0
  1563. }
  1564. func (x *bitset256) set(pos byte) {
  1565. x[pos>>3] |= (1 << (pos & 7))
  1566. }
  1567. // func (x *bitset256) unset(pos byte) {
  1568. // x[pos>>3] &^= (1 << (pos & 7))
  1569. // }
  1570. type bitset128 [16]byte
  1571. func (x *bitset128) isset(pos byte) bool {
  1572. return x[pos>>3]&(1<<(pos&7)) != 0
  1573. }
  1574. func (x *bitset128) set(pos byte) {
  1575. x[pos>>3] |= (1 << (pos & 7))
  1576. }
  1577. // func (x *bitset128) unset(pos byte) {
  1578. // x[pos>>3] &^= (1 << (pos & 7))
  1579. // }
  1580. type bitset32 [4]byte
  1581. func (x *bitset32) isset(pos byte) bool {
  1582. return x[pos>>3]&(1<<(pos&7)) != 0
  1583. }
  1584. func (x *bitset32) set(pos byte) {
  1585. x[pos>>3] |= (1 << (pos & 7))
  1586. }
  1587. // func (x *bitset32) unset(pos byte) {
  1588. // x[pos>>3] &^= (1 << (pos & 7))
  1589. // }
  1590. // ------------
  1591. type pooler struct {
  1592. // for stringRV
  1593. strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool
  1594. // for the decNaked
  1595. dn sync.Pool
  1596. tiload sync.Pool
  1597. }
  1598. func (p *pooler) init() {
  1599. p.strRv8.New = func() interface{} { return new([8]stringRv) }
  1600. p.strRv16.New = func() interface{} { return new([16]stringRv) }
  1601. p.strRv32.New = func() interface{} { return new([32]stringRv) }
  1602. p.strRv64.New = func() interface{} { return new([64]stringRv) }
  1603. p.strRv128.New = func() interface{} { return new([128]stringRv) }
  1604. p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
  1605. p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
  1606. }
  1607. func (p *pooler) stringRv8() (sp *sync.Pool, v interface{}) {
  1608. return &p.strRv8, p.strRv8.Get()
  1609. }
  1610. func (p *pooler) stringRv16() (sp *sync.Pool, v interface{}) {
  1611. return &p.strRv16, p.strRv16.Get()
  1612. }
  1613. func (p *pooler) stringRv32() (sp *sync.Pool, v interface{}) {
  1614. return &p.strRv32, p.strRv32.Get()
  1615. }
  1616. func (p *pooler) stringRv64() (sp *sync.Pool, v interface{}) {
  1617. return &p.strRv64, p.strRv64.Get()
  1618. }
  1619. func (p *pooler) stringRv128() (sp *sync.Pool, v interface{}) {
  1620. return &p.strRv128, p.strRv128.Get()
  1621. }
  1622. func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
  1623. return &p.dn, p.dn.Get()
  1624. }
  1625. func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
  1626. return &p.tiload, p.tiload.Get()
  1627. }