helper.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. // 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. "io"
  102. "math"
  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. // size of the cacheline: defaulting to value for archs: amd64, arm64, 386
  123. // should use "runtime/internal/sys".CacheLineSize, but that is not exposed.
  124. cacheLineSize = 64
  125. wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize
  126. wordSize = wordSizeBits / 8
  127. maxLevelsEmbedding = 15 // use this, so structFieldInfo fits into 8 bytes
  128. )
  129. var (
  130. oneByteArr = [1]byte{0}
  131. zeroByteSlice = oneByteArr[:0:0]
  132. )
  133. var refBitset bitset32
  134. var pool pooler
  135. var panicv panicHdl
  136. func init() {
  137. pool.init()
  138. refBitset.set(byte(reflect.Map))
  139. refBitset.set(byte(reflect.Ptr))
  140. refBitset.set(byte(reflect.Func))
  141. refBitset.set(byte(reflect.Chan))
  142. }
  143. type charEncoding uint8
  144. const (
  145. cRAW charEncoding = iota
  146. cUTF8
  147. cUTF16LE
  148. cUTF16BE
  149. cUTF32LE
  150. cUTF32BE
  151. )
  152. // valueType is the stream type
  153. type valueType uint8
  154. const (
  155. valueTypeUnset valueType = iota
  156. valueTypeNil
  157. valueTypeInt
  158. valueTypeUint
  159. valueTypeFloat
  160. valueTypeBool
  161. valueTypeString
  162. valueTypeSymbol
  163. valueTypeBytes
  164. valueTypeMap
  165. valueTypeArray
  166. valueTypeTime
  167. valueTypeExt
  168. // valueTypeInvalid = 0xff
  169. )
  170. var valueTypeStrings = [...]string{
  171. "Unset",
  172. "Nil",
  173. "Int",
  174. "Uint",
  175. "Float",
  176. "Bool",
  177. "String",
  178. "Symbol",
  179. "Bytes",
  180. "Map",
  181. "Array",
  182. "Timestamp",
  183. "Ext",
  184. }
  185. func (x valueType) String() string {
  186. if int(x) < len(valueTypeStrings) {
  187. return valueTypeStrings[x]
  188. }
  189. return strconv.FormatInt(int64(x), 10)
  190. }
  191. type seqType uint8
  192. const (
  193. _ seqType = iota
  194. seqTypeArray
  195. seqTypeSlice
  196. seqTypeChan
  197. )
  198. // note that containerMapStart and containerArraySend are not sent.
  199. // This is because the ReadXXXStart and EncodeXXXStart already does these.
  200. type containerState uint8
  201. const (
  202. _ containerState = iota
  203. containerMapStart // slot left open, since Driver method already covers it
  204. containerMapKey
  205. containerMapValue
  206. containerMapEnd
  207. containerArrayStart // slot left open, since Driver methods already cover it
  208. containerArrayElem
  209. containerArrayEnd
  210. )
  211. // // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
  212. // type sfiIdx struct {
  213. // name string
  214. // index int
  215. // }
  216. // do not recurse if a containing type refers to an embedded type
  217. // which refers back to its containing type (via a pointer).
  218. // The second time this back-reference happens, break out,
  219. // so as not to cause an infinite loop.
  220. const rgetMaxRecursion = 2
  221. // Anecdotally, we believe most types have <= 12 fields.
  222. // - even Java's PMD rules set TooManyFields threshold to 15.
  223. // However, go has embedded fields, which should be regarded as
  224. // top level, allowing structs to possibly double or triple.
  225. // In addition, we don't want to keep creating transient arrays,
  226. // especially for the sfi index tracking, and the evtypes tracking.
  227. //
  228. // So - try to keep typeInfoLoadArray within 2K bytes
  229. const (
  230. typeInfoLoadArraySfisLen = 16
  231. typeInfoLoadArraySfiidxLen = 8 * 112
  232. typeInfoLoadArrayEtypesLen = 12
  233. typeInfoLoadArrayBLen = 8 * 4
  234. )
  235. type typeInfoLoad struct {
  236. // fNames []string
  237. // encNames []string
  238. etypes []uintptr
  239. sfis []structFieldInfo
  240. }
  241. type typeInfoLoadArray struct {
  242. // fNames [typeInfoLoadArrayLen]string
  243. // encNames [typeInfoLoadArrayLen]string
  244. sfis [typeInfoLoadArraySfisLen]structFieldInfo
  245. sfiidx [typeInfoLoadArraySfiidxLen]byte
  246. etypes [typeInfoLoadArrayEtypesLen]uintptr
  247. b [typeInfoLoadArrayBLen]byte // scratch - used for struct field names
  248. }
  249. // mirror json.Marshaler and json.Unmarshaler here,
  250. // so we don't import the encoding/json package
  251. type jsonMarshaler interface {
  252. MarshalJSON() ([]byte, error)
  253. }
  254. type jsonUnmarshaler interface {
  255. UnmarshalJSON([]byte) error
  256. }
  257. type isZeroer interface {
  258. IsZero() bool
  259. }
  260. // type byteAccepter func(byte) bool
  261. var (
  262. bigen = binary.BigEndian
  263. structInfoFieldName = "_struct"
  264. mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  265. mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
  266. intfSliceTyp = reflect.TypeOf([]interface{}(nil))
  267. intfTyp = intfSliceTyp.Elem()
  268. reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem()
  269. stringTyp = reflect.TypeOf("")
  270. timeTyp = reflect.TypeOf(time.Time{})
  271. rawExtTyp = reflect.TypeOf(RawExt{})
  272. rawTyp = reflect.TypeOf(Raw{})
  273. uintptrTyp = reflect.TypeOf(uintptr(0))
  274. uint8Typ = reflect.TypeOf(uint8(0))
  275. uint8SliceTyp = reflect.TypeOf([]uint8(nil))
  276. uintTyp = reflect.TypeOf(uint(0))
  277. intTyp = reflect.TypeOf(int(0))
  278. mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
  279. binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  280. binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  281. textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  282. textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  283. jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  284. jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  285. selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
  286. iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem()
  287. uint8TypId = rt2id(uint8Typ)
  288. uint8SliceTypId = rt2id(uint8SliceTyp)
  289. rawExtTypId = rt2id(rawExtTyp)
  290. rawTypId = rt2id(rawTyp)
  291. intfTypId = rt2id(intfTyp)
  292. timeTypId = rt2id(timeTyp)
  293. stringTypId = rt2id(stringTyp)
  294. mapStrIntfTypId = rt2id(mapStrIntfTyp)
  295. mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
  296. intfSliceTypId = rt2id(intfSliceTyp)
  297. // mapBySliceTypId = rt2id(mapBySliceTyp)
  298. intBitsize = uint8(intTyp.Bits())
  299. uintBitsize = uint8(uintTyp.Bits())
  300. bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
  301. bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  302. chkOvf checkOverflow
  303. errNoFieldNameToStructFieldInfo = errors.New("no field name passed to parseStructFieldInfo")
  304. )
  305. var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
  306. var immutableKindsSet = [32]bool{
  307. // reflect.Invalid: ,
  308. reflect.Bool: true,
  309. reflect.Int: true,
  310. reflect.Int8: true,
  311. reflect.Int16: true,
  312. reflect.Int32: true,
  313. reflect.Int64: true,
  314. reflect.Uint: true,
  315. reflect.Uint8: true,
  316. reflect.Uint16: true,
  317. reflect.Uint32: true,
  318. reflect.Uint64: true,
  319. reflect.Uintptr: true,
  320. reflect.Float32: true,
  321. reflect.Float64: true,
  322. reflect.Complex64: true,
  323. reflect.Complex128: true,
  324. // reflect.Array
  325. // reflect.Chan
  326. // reflect.Func: true,
  327. // reflect.Interface
  328. // reflect.Map
  329. // reflect.Ptr
  330. // reflect.Slice
  331. reflect.String: true,
  332. // reflect.Struct
  333. // reflect.UnsafePointer
  334. }
  335. // Selfer defines methods by which a value can encode or decode itself.
  336. //
  337. // Any type which implements Selfer will be able to encode or decode itself.
  338. // Consequently, during (en|de)code, this takes precedence over
  339. // (text|binary)(M|Unm)arshal or extension support.
  340. //
  341. // Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
  342. // This is because, during each decode, we first check the the next set of bytes
  343. // represent nil, and if so, we just set the value to nil.
  344. type Selfer interface {
  345. CodecEncodeSelf(*Encoder)
  346. CodecDecodeSelf(*Decoder)
  347. }
  348. // MapBySlice is a tag interface that denotes wrapped slice should encode as a map in the stream.
  349. // The slice contains a sequence of key-value pairs.
  350. // This affords storing a map in a specific sequence in the stream.
  351. //
  352. // Example usage:
  353. // type T1 []string // or []int or []Point or any other "slice" type
  354. // func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map
  355. // type T2 struct { KeyValues T1 }
  356. //
  357. // var kvs = []string{"one", "1", "two", "2", "three", "3"}
  358. // var v2 = T2{ KeyValues: T1(kvs) }
  359. // // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} }
  360. //
  361. // The support of MapBySlice affords the following:
  362. // - A slice type which implements MapBySlice will be encoded as a map
  363. // - A slice can be decoded from a map in the stream
  364. // - It MUST be a slice type (not a pointer receiver) that implements MapBySlice
  365. type MapBySlice interface {
  366. MapBySlice()
  367. }
  368. // BasicHandle encapsulates the common options and extension functions.
  369. //
  370. // Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
  371. type BasicHandle struct {
  372. // BasicHandle is always a part of a different type.
  373. // It doesn't have to fit into it own cache lines.
  374. // TypeInfos is used to get the type info for any type.
  375. //
  376. // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
  377. TypeInfos *TypeInfos
  378. // Note: BasicHandle is not comparable, due to these slices here (extHandle, intf2impls).
  379. // If *[]T is used instead, this becomes comparable, at the cost of extra indirection.
  380. // Thses slices are used all the time, so keep as slices (not pointers).
  381. extHandle
  382. intf2impls
  383. RPCOptions
  384. // ---- cache line
  385. DecodeOptions
  386. // ---- cache line
  387. EncodeOptions
  388. // noBuiltInTypeChecker
  389. }
  390. func (x *BasicHandle) getBasicHandle() *BasicHandle {
  391. return x
  392. }
  393. func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  394. if x.TypeInfos == nil {
  395. return defTypeInfos.get(rtid, rt)
  396. }
  397. return x.TypeInfos.get(rtid, rt)
  398. }
  399. // Handle is the interface for a specific encoding format.
  400. //
  401. // Typically, a Handle is pre-configured before first time use,
  402. // and not modified while in use. Such a pre-configured Handle
  403. // is safe for concurrent access.
  404. type Handle interface {
  405. Name() string
  406. getBasicHandle() *BasicHandle
  407. recreateEncDriver(encDriver) bool
  408. newEncDriver(w *Encoder) encDriver
  409. newDecDriver(r *Decoder) decDriver
  410. isBinary() bool
  411. hasElemSeparators() bool
  412. // IsBuiltinType(rtid uintptr) bool
  413. }
  414. // Raw represents raw formatted bytes.
  415. // We "blindly" store it during encode and retrieve the raw bytes during decode.
  416. // Note: it is dangerous during encode, so we may gate the behaviour
  417. // behind an Encode flag which must be explicitly set.
  418. type Raw []byte
  419. // RawExt represents raw unprocessed extension data.
  420. // Some codecs will decode extension data as a *RawExt
  421. // if there is no registered extension for the tag.
  422. //
  423. // Only one of Data or Value is nil.
  424. // If Data is nil, then the content of the RawExt is in the Value.
  425. type RawExt struct {
  426. Tag uint64
  427. // Data is the []byte which represents the raw ext. If nil, ext is exposed in Value.
  428. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types
  429. Data []byte
  430. // Value represents the extension, if Data is nil.
  431. // Value is used by codecs (e.g. cbor, json) which leverage the format to do
  432. // custom serialization of the types.
  433. Value interface{}
  434. }
  435. // BytesExt handles custom (de)serialization of types to/from []byte.
  436. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  437. type BytesExt interface {
  438. // WriteExt converts a value to a []byte.
  439. //
  440. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  441. WriteExt(v interface{}) []byte
  442. // ReadExt updates a value from a []byte.
  443. //
  444. // Note: dst is always a pointer kind to the registered extension type.
  445. ReadExt(dst interface{}, src []byte)
  446. }
  447. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  448. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  449. //
  450. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types.
  451. type InterfaceExt interface {
  452. // ConvertExt converts a value into a simpler interface for easy encoding
  453. // e.g. convert time.Time to int64.
  454. //
  455. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  456. ConvertExt(v interface{}) interface{}
  457. // UpdateExt updates a value from a simpler interface for easy decoding
  458. // e.g. convert int64 to time.Time.
  459. //
  460. // Note: dst is always a pointer kind to the registered extension type.
  461. UpdateExt(dst interface{}, src interface{})
  462. }
  463. // Ext handles custom (de)serialization of custom types / extensions.
  464. type Ext interface {
  465. BytesExt
  466. InterfaceExt
  467. }
  468. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  469. type addExtWrapper struct {
  470. encFn func(reflect.Value) ([]byte, error)
  471. decFn func(reflect.Value, []byte) error
  472. }
  473. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  474. bs, err := x.encFn(reflect.ValueOf(v))
  475. if err != nil {
  476. panic(err)
  477. }
  478. return bs
  479. }
  480. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  481. if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
  482. panic(err)
  483. }
  484. }
  485. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  486. return x.WriteExt(v)
  487. }
  488. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  489. x.ReadExt(dest, v.([]byte))
  490. }
  491. type extWrapper struct {
  492. BytesExt
  493. InterfaceExt
  494. }
  495. type bytesExtFailer struct{}
  496. func (bytesExtFailer) WriteExt(v interface{}) []byte {
  497. panicv.errorstr("BytesExt.WriteExt is not supported")
  498. return nil
  499. }
  500. func (bytesExtFailer) ReadExt(v interface{}, bs []byte) {
  501. panicv.errorstr("BytesExt.ReadExt is not supported")
  502. }
  503. type interfaceExtFailer struct{}
  504. func (interfaceExtFailer) ConvertExt(v interface{}) interface{} {
  505. panicv.errorstr("InterfaceExt.ConvertExt is not supported")
  506. return nil
  507. }
  508. func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) {
  509. panicv.errorstr("InterfaceExt.UpdateExt is not supported")
  510. }
  511. type binaryEncodingType struct{}
  512. func (binaryEncodingType) isBinary() bool { return true }
  513. type textEncodingType struct{}
  514. func (textEncodingType) isBinary() bool { return false }
  515. // noBuiltInTypes is embedded into many types which do not support builtins
  516. // e.g. msgpack, simple, cbor.
  517. // type noBuiltInTypeChecker struct{}
  518. // func (noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
  519. // type noBuiltInTypes struct{ noBuiltInTypeChecker }
  520. type noBuiltInTypes struct{}
  521. func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  522. func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  523. // type noStreamingCodec struct{}
  524. // func (noStreamingCodec) CheckBreak() bool { return false }
  525. // func (noStreamingCodec) hasElemSeparators() bool { return false }
  526. type noElemSeparators struct{}
  527. func (noElemSeparators) hasElemSeparators() (v bool) { return }
  528. func (noElemSeparators) recreateEncDriver(e encDriver) (v bool) { return }
  529. // bigenHelper.
  530. // Users must already slice the x completely, because we will not reslice.
  531. type bigenHelper struct {
  532. x []byte // must be correctly sliced to appropriate len. slicing is a cost.
  533. w encWriter
  534. }
  535. func (z bigenHelper) writeUint16(v uint16) {
  536. bigen.PutUint16(z.x, v)
  537. z.w.writeb(z.x)
  538. }
  539. func (z bigenHelper) writeUint32(v uint32) {
  540. bigen.PutUint32(z.x, v)
  541. z.w.writeb(z.x)
  542. }
  543. func (z bigenHelper) writeUint64(v uint64) {
  544. bigen.PutUint64(z.x, v)
  545. z.w.writeb(z.x)
  546. }
  547. type extTypeTagFn struct {
  548. rtid uintptr
  549. rtidptr uintptr
  550. rt reflect.Type
  551. tag uint64
  552. ext Ext
  553. _ [1]uint64 // padding
  554. }
  555. type extHandle []extTypeTagFn
  556. // AddExt registes an encode and decode function for a reflect.Type.
  557. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  558. //
  559. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  560. func (o *extHandle) AddExt(rt reflect.Type, tag byte,
  561. encfn func(reflect.Value) ([]byte, error),
  562. decfn func(reflect.Value, []byte) error) (err error) {
  563. if encfn == nil || decfn == nil {
  564. return o.SetExt(rt, uint64(tag), nil)
  565. }
  566. return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  567. }
  568. // SetExt will set the extension for a tag and reflect.Type.
  569. // Note that the type must be a named type, and specifically not a pointer or Interface.
  570. // An error is returned if that is not honored.
  571. // To Deregister an ext, call SetExt with nil Ext.
  572. //
  573. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  574. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  575. // o is a pointer, because we may need to initialize it
  576. rk := rt.Kind()
  577. for rk == reflect.Ptr {
  578. rt = rt.Elem()
  579. rk = rt.Kind()
  580. }
  581. if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr {
  582. return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt)
  583. }
  584. rtid := rt2id(rt)
  585. switch rtid {
  586. case timeTypId, rawTypId, rawExtTypId:
  587. // all natively supported type, so cannot have an extension
  588. return // TODO: should we silently ignore, or return an error???
  589. }
  590. // if o == nil {
  591. // return errors.New("codec.Handle.SetExt: extHandle not initialized")
  592. // }
  593. o2 := *o
  594. // if o2 == nil {
  595. // return errors.New("codec.Handle.SetExt: extHandle not initialized")
  596. // }
  597. for i := range o2 {
  598. v := &o2[i]
  599. if v.rtid == rtid {
  600. v.tag, v.ext = tag, ext
  601. return
  602. }
  603. }
  604. rtidptr := rt2id(reflect.PtrTo(rt))
  605. *o = append(o2, extTypeTagFn{rtid, rtidptr, rt, tag, ext, [1]uint64{}})
  606. return
  607. }
  608. func (o extHandle) getExt(rtid uintptr) (v *extTypeTagFn) {
  609. for i := range o {
  610. v = &o[i]
  611. if v.rtid == rtid || v.rtidptr == rtid {
  612. return
  613. }
  614. }
  615. return nil
  616. }
  617. func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) {
  618. for i := range o {
  619. v = &o[i]
  620. if v.tag == tag {
  621. return
  622. }
  623. }
  624. return nil
  625. }
  626. type intf2impl struct {
  627. rtid uintptr // for intf
  628. impl reflect.Type
  629. // _ [1]uint64 // padding // not-needed, as *intf2impl is never returned.
  630. }
  631. type intf2impls []intf2impl
  632. // Intf2Impl maps an interface to an implementing type.
  633. // This allows us support infering the concrete type
  634. // and populating it when passed an interface.
  635. // e.g. var v io.Reader can be decoded as a bytes.Buffer, etc.
  636. //
  637. // Passing a nil impl will clear the mapping.
  638. func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) {
  639. if impl != nil && !impl.Implements(intf) {
  640. return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf)
  641. }
  642. rtid := rt2id(intf)
  643. o2 := *o
  644. for i := range o2 {
  645. v := &o2[i]
  646. if v.rtid == rtid {
  647. v.impl = impl
  648. return
  649. }
  650. }
  651. *o = append(o2, intf2impl{rtid, impl})
  652. return
  653. }
  654. func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) {
  655. for i := range o {
  656. v := &o[i]
  657. if v.rtid == rtid {
  658. if v.impl == nil {
  659. return
  660. }
  661. if v.impl.Kind() == reflect.Ptr {
  662. return reflect.New(v.impl.Elem())
  663. }
  664. return reflect.New(v.impl).Elem()
  665. }
  666. }
  667. return
  668. }
  669. type structFieldInfoFlag uint8
  670. const (
  671. _ structFieldInfoFlag = 1 << iota
  672. structFieldInfoFlagReady
  673. structFieldInfoFlagOmitEmpty
  674. )
  675. func (x *structFieldInfoFlag) flagSet(f structFieldInfoFlag) {
  676. *x = *x | f
  677. }
  678. func (x *structFieldInfoFlag) flagClr(f structFieldInfoFlag) {
  679. *x = *x &^ f
  680. }
  681. func (x structFieldInfoFlag) flagGet(f structFieldInfoFlag) bool {
  682. return x&f != 0
  683. }
  684. func (x structFieldInfoFlag) omitEmpty() bool {
  685. return x.flagGet(structFieldInfoFlagOmitEmpty)
  686. }
  687. func (x structFieldInfoFlag) ready() bool {
  688. return x.flagGet(structFieldInfoFlagReady)
  689. }
  690. type structFieldInfo struct {
  691. encName string // encode name
  692. fieldName string // field name
  693. is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
  694. nis uint8 // num levels of embedding. if 1, then it's not embedded.
  695. structFieldInfoFlag
  696. }
  697. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  698. if v, valid := si.field(v, false); valid {
  699. v.Set(reflect.Zero(v.Type()))
  700. }
  701. }
  702. // rv returns the field of the struct.
  703. // If anonymous, it returns an Invalid
  704. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
  705. // replicate FieldByIndex
  706. for i, x := range si.is {
  707. if uint8(i) == si.nis {
  708. break
  709. }
  710. if v, valid = baseStructRv(v, update); !valid {
  711. return
  712. }
  713. v = v.Field(int(x))
  714. }
  715. return v, true
  716. }
  717. // func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
  718. // v, _ = si.field(v, update)
  719. // return v
  720. // }
  721. func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) {
  722. keytype = valueTypeString // default
  723. if stag == "" {
  724. return
  725. }
  726. for i, s := range strings.Split(stag, ",") {
  727. if i == 0 {
  728. } else {
  729. switch s {
  730. case "omitempty":
  731. omitEmpty = true
  732. case "toarray":
  733. toArray = true
  734. case "int":
  735. keytype = valueTypeInt
  736. case "uint":
  737. keytype = valueTypeUint
  738. case "float":
  739. keytype = valueTypeFloat
  740. // case "bool":
  741. // keytype = valueTypeBool
  742. case "string":
  743. keytype = valueTypeString
  744. }
  745. }
  746. }
  747. return
  748. }
  749. func (si *structFieldInfo) parseTag(stag string) {
  750. // if fname == "" {
  751. // panic(errNoFieldNameToStructFieldInfo)
  752. // }
  753. if stag == "" {
  754. return
  755. }
  756. for i, s := range strings.Split(stag, ",") {
  757. if i == 0 {
  758. if s != "" {
  759. si.encName = s
  760. }
  761. } else {
  762. switch s {
  763. case "omitempty":
  764. si.flagSet(structFieldInfoFlagOmitEmpty)
  765. // si.omitEmpty = true
  766. // case "toarray":
  767. // si.toArray = true
  768. }
  769. }
  770. }
  771. }
  772. type sfiSortedByEncName []*structFieldInfo
  773. func (p sfiSortedByEncName) Len() int {
  774. return len(p)
  775. }
  776. func (p sfiSortedByEncName) Less(i, j int) bool {
  777. return p[i].encName < p[j].encName
  778. }
  779. func (p sfiSortedByEncName) Swap(i, j int) {
  780. p[i], p[j] = p[j], p[i]
  781. }
  782. const structFieldNodeNumToCache = 4
  783. type structFieldNodeCache struct {
  784. rv [structFieldNodeNumToCache]reflect.Value
  785. idx [structFieldNodeNumToCache]uint32
  786. num uint8
  787. }
  788. func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
  789. for i, k := range &x.idx {
  790. if uint8(i) == x.num {
  791. return // break
  792. }
  793. if key == k {
  794. return x.rv[i], true
  795. }
  796. }
  797. return
  798. }
  799. func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
  800. if x.num < structFieldNodeNumToCache {
  801. x.rv[x.num] = fv
  802. x.idx[x.num] = key
  803. x.num++
  804. return
  805. }
  806. }
  807. type structFieldNode struct {
  808. v reflect.Value
  809. cache2 structFieldNodeCache
  810. cache3 structFieldNodeCache
  811. update bool
  812. }
  813. func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
  814. // return si.fieldval(x.v, x.update)
  815. // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
  816. // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
  817. var valid bool
  818. switch si.nis {
  819. case 1:
  820. fv = x.v.Field(int(si.is[0]))
  821. case 2:
  822. if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
  823. fv = fv.Field(int(si.is[1]))
  824. return
  825. }
  826. fv = x.v.Field(int(si.is[0]))
  827. if fv, valid = baseStructRv(fv, x.update); !valid {
  828. return
  829. }
  830. x.cache2.tryAdd(fv, uint32(si.is[0]))
  831. fv = fv.Field(int(si.is[1]))
  832. case 3:
  833. var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
  834. if fv, valid = x.cache3.get(key); valid {
  835. fv = fv.Field(int(si.is[2]))
  836. return
  837. }
  838. fv = x.v.Field(int(si.is[0]))
  839. if fv, valid = baseStructRv(fv, x.update); !valid {
  840. return
  841. }
  842. fv = fv.Field(int(si.is[1]))
  843. if fv, valid = baseStructRv(fv, x.update); !valid {
  844. return
  845. }
  846. x.cache3.tryAdd(fv, key)
  847. fv = fv.Field(int(si.is[2]))
  848. default:
  849. fv, _ = si.field(x.v, x.update)
  850. }
  851. return
  852. }
  853. func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
  854. for v.Kind() == reflect.Ptr {
  855. if v.IsNil() {
  856. if !update {
  857. return
  858. }
  859. v.Set(reflect.New(v.Type().Elem()))
  860. }
  861. v = v.Elem()
  862. }
  863. return v, true
  864. }
  865. type typeInfoFlag uint8
  866. const (
  867. typeInfoFlagComparable = 1 << iota
  868. typeInfoFlagIsZeroer
  869. typeInfoFlagIsZeroerPtr
  870. )
  871. // typeInfo keeps information about each (non-ptr) type referenced in the encode/decode sequence.
  872. //
  873. // During an encode/decode sequence, we work as below:
  874. // - If base is a built in type, en/decode base value
  875. // - If base is registered as an extension, en/decode base value
  876. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  877. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  878. // - Else decode appropriately based on the reflect.Kind
  879. type typeInfo struct {
  880. rt reflect.Type
  881. elem reflect.Type
  882. pkgpath string
  883. rtid uintptr
  884. // rv0 reflect.Value // saved zero value, used if immutableKind
  885. numMeth uint16 // number of methods
  886. kind uint8
  887. chandir uint8
  888. anyOmitEmpty bool // true if a struct, and any of the fields are tagged "omitempty"
  889. toArray bool // whether this (struct) type should be encoded as an array
  890. keyType valueType // if struct, how is the field name stored in a stream? default is string
  891. mbs bool // base type (T or *T) is a MapBySlice
  892. // ---- cpu cache line boundary?
  893. sfiSort []*structFieldInfo // sorted. Used when enc/dec struct to map.
  894. sfiSrc []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  895. key reflect.Type
  896. // ---- cpu cache line boundary?
  897. // sfis []structFieldInfo // all sfi, in src order, as created.
  898. sfiNamesSort []byte // all names, with indexes into the sfiSort
  899. // format of marshal type fields below: [btj][mu]p? OR csp?
  900. bm bool // T is a binaryMarshaler
  901. bmp bool // *T is a binaryMarshaler
  902. bu bool // T is a binaryUnmarshaler
  903. bup bool // *T is a binaryUnmarshaler
  904. tm bool // T is a textMarshaler
  905. tmp bool // *T is a textMarshaler
  906. tu bool // T is a textUnmarshaler
  907. tup bool // *T is a textUnmarshaler
  908. jm bool // T is a jsonMarshaler
  909. jmp bool // *T is a jsonMarshaler
  910. ju bool // T is a jsonUnmarshaler
  911. jup bool // *T is a jsonUnmarshaler
  912. cs bool // T is a Selfer
  913. csp bool // *T is a Selfer
  914. // other flags, with individual bits representing if set.
  915. flags typeInfoFlag
  916. // _ [2]byte // padding
  917. _ [3]uint64 // padding
  918. }
  919. func (ti *typeInfo) isFlag(f typeInfoFlag) bool {
  920. return ti.flags&f != 0
  921. }
  922. func (ti *typeInfo) indexForEncName(name []byte) (index int16) {
  923. var sn []byte
  924. if len(name)+2 <= 32 {
  925. var buf [32]byte // should not escape
  926. sn = buf[:len(name)+2]
  927. } else {
  928. sn = make([]byte, len(name)+2)
  929. }
  930. copy(sn[1:], name)
  931. sn[0], sn[len(sn)-1] = tiSep2(name), 0xff
  932. j := bytes.Index(ti.sfiNamesSort, sn)
  933. if j < 0 {
  934. return -1
  935. }
  936. index = int16(uint16(ti.sfiNamesSort[j+len(sn)+1]) | uint16(ti.sfiNamesSort[j+len(sn)])<<8)
  937. return
  938. }
  939. type rtid2ti struct {
  940. rtid uintptr
  941. ti *typeInfo
  942. }
  943. // TypeInfos caches typeInfo for each type on first inspection.
  944. //
  945. // It is configured with a set of tag keys, which are used to get
  946. // configuration for the type.
  947. type TypeInfos struct {
  948. // infos: formerly map[uintptr]*typeInfo, now *[]rtid2ti, 2 words expected
  949. infos atomicTypeInfoSlice
  950. mu sync.Mutex
  951. tags []string
  952. _ [2]uint64 // padding
  953. }
  954. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  955. //
  956. // This allows users customize the struct tag keys which contain configuration
  957. // of their types.
  958. func NewTypeInfos(tags []string) *TypeInfos {
  959. return &TypeInfos{tags: tags}
  960. }
  961. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  962. // check for tags: codec, json, in that order.
  963. // this allows seamless support for many configured structs.
  964. for _, x := range x.tags {
  965. s = t.Get(x)
  966. if s != "" {
  967. return s
  968. }
  969. }
  970. return
  971. }
  972. func (x *TypeInfos) find(s []rtid2ti, rtid uintptr) (idx int, ti *typeInfo) {
  973. // binary search. adapted from sort/search.go.
  974. // if sp == nil {
  975. // return -1, nil
  976. // }
  977. // s := *sp
  978. h, i, j := 0, 0, len(s)
  979. for i < j {
  980. h = i + (j-i)/2
  981. if s[h].rtid < rtid {
  982. i = h + 1
  983. } else {
  984. j = h
  985. }
  986. }
  987. if i < len(s) && s[i].rtid == rtid {
  988. return i, s[i].ti
  989. }
  990. return i, nil
  991. }
  992. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  993. sp := x.infos.load()
  994. var idx int
  995. if sp != nil {
  996. idx, pti = x.find(sp, rtid)
  997. if pti != nil {
  998. return
  999. }
  1000. }
  1001. rk := rt.Kind()
  1002. if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) {
  1003. panicv.errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt)
  1004. }
  1005. // do not hold lock while computing this.
  1006. // it may lead to duplication, but that's ok.
  1007. ti := typeInfo{rt: rt, rtid: rtid, kind: uint8(rk), pkgpath: rt.PkgPath()}
  1008. // ti.rv0 = reflect.Zero(rt)
  1009. // ti.comparable = rt.Comparable()
  1010. ti.numMeth = uint16(rt.NumMethod())
  1011. ti.bm, ti.bmp = implIntf(rt, binaryMarshalerTyp)
  1012. ti.bu, ti.bup = implIntf(rt, binaryUnmarshalerTyp)
  1013. ti.tm, ti.tmp = implIntf(rt, textMarshalerTyp)
  1014. ti.tu, ti.tup = implIntf(rt, textUnmarshalerTyp)
  1015. ti.jm, ti.jmp = implIntf(rt, jsonMarshalerTyp)
  1016. ti.ju, ti.jup = implIntf(rt, jsonUnmarshalerTyp)
  1017. ti.cs, ti.csp = implIntf(rt, selferTyp)
  1018. b1, b2 := implIntf(rt, iszeroTyp)
  1019. if b1 {
  1020. ti.flags |= typeInfoFlagIsZeroer
  1021. }
  1022. if b2 {
  1023. ti.flags |= typeInfoFlagIsZeroerPtr
  1024. }
  1025. if rt.Comparable() {
  1026. ti.flags |= typeInfoFlagComparable
  1027. }
  1028. switch rk {
  1029. case reflect.Struct:
  1030. var omitEmpty bool
  1031. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  1032. ti.toArray, omitEmpty, ti.keyType = parseStructInfo(x.structTag(f.Tag))
  1033. } else {
  1034. ti.keyType = valueTypeString
  1035. }
  1036. pp, pi := pool.tiLoad()
  1037. pv := pi.(*typeInfoLoadArray)
  1038. pv.etypes[0] = ti.rtid
  1039. // vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  1040. vv := typeInfoLoad{pv.etypes[:1], pv.sfis[:0]}
  1041. x.rget(rt, rtid, omitEmpty, nil, &vv)
  1042. // ti.sfis = vv.sfis
  1043. ti.sfiSrc, ti.sfiSort, ti.sfiNamesSort, ti.anyOmitEmpty = rgetResolveSFI(rt, vv.sfis, pv)
  1044. pp.Put(pi)
  1045. case reflect.Map:
  1046. ti.elem = rt.Elem()
  1047. ti.key = rt.Key()
  1048. case reflect.Slice:
  1049. ti.mbs, _ = implIntf(rt, mapBySliceTyp)
  1050. ti.elem = rt.Elem()
  1051. case reflect.Chan:
  1052. ti.elem = rt.Elem()
  1053. ti.chandir = uint8(rt.ChanDir())
  1054. case reflect.Array, reflect.Ptr:
  1055. ti.elem = rt.Elem()
  1056. }
  1057. // sfi = sfiSrc
  1058. x.mu.Lock()
  1059. sp = x.infos.load()
  1060. if sp == nil {
  1061. pti = &ti
  1062. vs := []rtid2ti{{rtid, pti}}
  1063. x.infos.store(vs)
  1064. } else {
  1065. idx, pti = x.find(sp, rtid)
  1066. if pti == nil {
  1067. pti = &ti
  1068. vs := make([]rtid2ti, len(sp)+1)
  1069. copy(vs, sp[:idx])
  1070. copy(vs[idx+1:], sp[idx:])
  1071. vs[idx] = rtid2ti{rtid, pti}
  1072. x.infos.store(vs)
  1073. }
  1074. }
  1075. x.mu.Unlock()
  1076. return
  1077. }
  1078. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  1079. indexstack []uint16, pv *typeInfoLoad) {
  1080. // Read up fields and store how to access the value.
  1081. //
  1082. // It uses go's rules for message selectors,
  1083. // which say that the field with the shallowest depth is selected.
  1084. //
  1085. // Note: we consciously use slices, not a map, to simulate a set.
  1086. // Typically, types have < 16 fields,
  1087. // and iteration using equals is faster than maps there
  1088. flen := rt.NumField()
  1089. if flen > (1<<maxLevelsEmbedding - 1) {
  1090. panicv.errorf("codec: types with > %v fields are not supported - has %v fields",
  1091. (1<<maxLevelsEmbedding - 1), flen)
  1092. }
  1093. // pv.sfis = make([]structFieldInfo, flen)
  1094. LOOP:
  1095. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  1096. f := rt.Field(int(j))
  1097. fkind := f.Type.Kind()
  1098. // skip if a func type, or is unexported, or structTag value == "-"
  1099. switch fkind {
  1100. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  1101. continue LOOP
  1102. }
  1103. isUnexported := f.PkgPath != ""
  1104. if isUnexported && !f.Anonymous {
  1105. continue
  1106. }
  1107. stag := x.structTag(f.Tag)
  1108. if stag == "-" {
  1109. continue
  1110. }
  1111. var si structFieldInfo
  1112. var parsed bool
  1113. // if anonymous and no struct tag (or it's blank),
  1114. // and a struct (or pointer to struct), inline it.
  1115. if f.Anonymous && fkind != reflect.Interface {
  1116. // ^^ redundant but ok: per go spec, an embedded pointer type cannot be to an interface
  1117. ft := f.Type
  1118. isPtr := ft.Kind() == reflect.Ptr
  1119. for ft.Kind() == reflect.Ptr {
  1120. ft = ft.Elem()
  1121. }
  1122. isStruct := ft.Kind() == reflect.Struct
  1123. // Ignore embedded fields of unexported non-struct types.
  1124. // Also, from go1.10, ignore pointers to unexported struct types
  1125. // because unmarshal cannot assign a new struct to an unexported field.
  1126. // See https://golang.org/issue/21357
  1127. if (isUnexported && !isStruct) || (!allowSetUnexportedEmbeddedPtr && isUnexported && isPtr) {
  1128. continue
  1129. }
  1130. doInline := stag == ""
  1131. if !doInline {
  1132. si.parseTag(stag)
  1133. parsed = true
  1134. doInline = si.encName == ""
  1135. // doInline = si.isZero()
  1136. }
  1137. if doInline && isStruct {
  1138. // if etypes contains this, don't call rget again (as fields are already seen here)
  1139. ftid := rt2id(ft)
  1140. // We cannot recurse forever, but we need to track other field depths.
  1141. // So - we break if we see a type twice (not the first time).
  1142. // This should be sufficient to handle an embedded type that refers to its
  1143. // owning type, which then refers to its embedded type.
  1144. processIt := true
  1145. numk := 0
  1146. for _, k := range pv.etypes {
  1147. if k == ftid {
  1148. numk++
  1149. if numk == rgetMaxRecursion {
  1150. processIt = false
  1151. break
  1152. }
  1153. }
  1154. }
  1155. if processIt {
  1156. pv.etypes = append(pv.etypes, ftid)
  1157. indexstack2 := make([]uint16, len(indexstack)+1)
  1158. copy(indexstack2, indexstack)
  1159. indexstack2[len(indexstack)] = j
  1160. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  1161. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  1162. }
  1163. continue
  1164. }
  1165. }
  1166. // after the anonymous dance: if an unexported field, skip
  1167. if isUnexported {
  1168. continue
  1169. }
  1170. if f.Name == "" {
  1171. panic(errNoFieldNameToStructFieldInfo)
  1172. }
  1173. // pv.fNames = append(pv.fNames, f.Name)
  1174. // if si.encName == "" {
  1175. if !parsed {
  1176. si.encName = f.Name
  1177. si.parseTag(stag)
  1178. parsed = true
  1179. } else if si.encName == "" {
  1180. si.encName = f.Name
  1181. }
  1182. si.fieldName = f.Name
  1183. si.flagSet(structFieldInfoFlagReady)
  1184. // pv.encNames = append(pv.encNames, si.encName)
  1185. // si.ikind = int(f.Type.Kind())
  1186. if len(indexstack) > maxLevelsEmbedding-1 {
  1187. panicv.errorf("codec: only supports up to %v depth of embedding - type has %v depth",
  1188. maxLevelsEmbedding-1, len(indexstack))
  1189. }
  1190. si.nis = uint8(len(indexstack)) + 1
  1191. copy(si.is[:], indexstack)
  1192. si.is[len(indexstack)] = j
  1193. if omitEmpty {
  1194. si.flagSet(structFieldInfoFlagOmitEmpty)
  1195. }
  1196. pv.sfis = append(pv.sfis, si)
  1197. }
  1198. }
  1199. func tiSep(name string) uint8 {
  1200. // (xn[0]%64) // (between 192-255 - outside ascii BMP)
  1201. // return 0xfe - (name[0] & 63)
  1202. // return 0xfe - (name[0] & 63) - uint8(len(name))
  1203. // return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1204. // return ((0xfe - (name[0] & 63)) & 0xf8) | (uint8(len(name) & 0x07))
  1205. return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1206. }
  1207. func tiSep2(name []byte) uint8 {
  1208. return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1209. }
  1210. // resolves the struct field info got from a call to rget.
  1211. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  1212. func rgetResolveSFI(rt reflect.Type, x []structFieldInfo, pv *typeInfoLoadArray) (
  1213. y, z []*structFieldInfo, ss []byte, anyOmitEmpty bool) {
  1214. sa := pv.sfiidx[:0]
  1215. sn := pv.b[:]
  1216. n := len(x)
  1217. var xn string
  1218. var ui uint16
  1219. var sep byte
  1220. for i := range x {
  1221. ui = uint16(i)
  1222. xn = x[i].encName // fieldName or encName? use encName for now.
  1223. if len(xn)+2 > cap(pv.b) {
  1224. sn = make([]byte, len(xn)+2)
  1225. } else {
  1226. sn = sn[:len(xn)+2]
  1227. }
  1228. // use a custom sep, so that misses are less frequent,
  1229. // since the sep (first char in search) is as unique as first char in field name.
  1230. sep = tiSep(xn)
  1231. sn[0], sn[len(sn)-1] = sep, 0xff
  1232. copy(sn[1:], xn)
  1233. j := bytes.Index(sa, sn)
  1234. if j == -1 {
  1235. sa = append(sa, sep)
  1236. sa = append(sa, xn...)
  1237. sa = append(sa, 0xff, byte(ui>>8), byte(ui))
  1238. } else {
  1239. index := uint16(sa[j+len(sn)+1]) | uint16(sa[j+len(sn)])<<8
  1240. // one of them must be reset to nil,
  1241. // and the index updated appropriately to the other one
  1242. if x[i].nis == x[index].nis {
  1243. } else if x[i].nis < x[index].nis {
  1244. sa[j+len(sn)], sa[j+len(sn)+1] = byte(ui>>8), byte(ui)
  1245. if x[index].ready() {
  1246. x[index].flagClr(structFieldInfoFlagReady)
  1247. n--
  1248. }
  1249. } else {
  1250. if x[i].ready() {
  1251. x[i].flagClr(structFieldInfoFlagReady)
  1252. n--
  1253. }
  1254. }
  1255. }
  1256. }
  1257. var w []structFieldInfo
  1258. sharingArray := len(x) <= typeInfoLoadArraySfisLen // sharing array with typeInfoLoadArray
  1259. if sharingArray {
  1260. w = make([]structFieldInfo, n)
  1261. }
  1262. // remove all the nils (non-ready)
  1263. y = make([]*structFieldInfo, n)
  1264. n = 0
  1265. var sslen int
  1266. for i := range x {
  1267. if !x[i].ready() {
  1268. continue
  1269. }
  1270. if !anyOmitEmpty && x[i].omitEmpty() {
  1271. anyOmitEmpty = true
  1272. }
  1273. if sharingArray {
  1274. w[n] = x[i]
  1275. y[n] = &w[n]
  1276. } else {
  1277. y[n] = &x[i]
  1278. }
  1279. sslen = sslen + len(x[i].encName) + 4
  1280. n++
  1281. }
  1282. if n != len(y) {
  1283. panicv.errorf("failure reading struct %v - expecting %d of %d valid fields, got %d",
  1284. rt, len(y), len(x), n)
  1285. }
  1286. z = make([]*structFieldInfo, len(y))
  1287. copy(z, y)
  1288. sort.Sort(sfiSortedByEncName(z))
  1289. sharingArray = len(sa) <= typeInfoLoadArraySfiidxLen
  1290. if sharingArray {
  1291. ss = make([]byte, 0, sslen)
  1292. } else {
  1293. ss = sa[:0] // reuse the newly made sa array if necessary
  1294. }
  1295. for i := range z {
  1296. xn = z[i].encName
  1297. sep = tiSep(xn)
  1298. ui = uint16(i)
  1299. ss = append(ss, sep)
  1300. ss = append(ss, xn...)
  1301. ss = append(ss, 0xff, byte(ui>>8), byte(ui))
  1302. }
  1303. return
  1304. }
  1305. func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) {
  1306. return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp)
  1307. }
  1308. // isEmptyStruct is only called from isEmptyValue, and checks if a struct is empty:
  1309. // - does it implement IsZero() bool
  1310. // - is it comparable, and can i compare directly using ==
  1311. // - if checkStruct, then walk through the encodable fields
  1312. // and check if they are empty or not.
  1313. func isEmptyStruct(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool {
  1314. // v is a struct kind - no need to check again.
  1315. // We only check isZero on a struct kind, to reduce the amount of times
  1316. // that we lookup the rtid and typeInfo for each type as we walk the tree.
  1317. vt := v.Type()
  1318. rtid := rt2id(vt)
  1319. if tinfos == nil {
  1320. tinfos = defTypeInfos
  1321. }
  1322. ti := tinfos.get(rtid, vt)
  1323. if ti.rtid == timeTypId {
  1324. return rv2i(v).(time.Time).IsZero()
  1325. }
  1326. if ti.isFlag(typeInfoFlagIsZeroerPtr) && v.CanAddr() {
  1327. return rv2i(v.Addr()).(isZeroer).IsZero()
  1328. }
  1329. if ti.isFlag(typeInfoFlagIsZeroer) {
  1330. return rv2i(v).(isZeroer).IsZero()
  1331. }
  1332. if ti.isFlag(typeInfoFlagComparable) {
  1333. return rv2i(v) == rv2i(reflect.Zero(vt))
  1334. }
  1335. if !checkStruct {
  1336. return false
  1337. }
  1338. // We only care about what we can encode/decode,
  1339. // so that is what we use to check omitEmpty.
  1340. for _, si := range ti.sfiSrc {
  1341. sfv, valid := si.field(v, false)
  1342. if valid && !isEmptyValue(sfv, tinfos, deref, checkStruct) {
  1343. return false
  1344. }
  1345. }
  1346. return true
  1347. }
  1348. // func roundFloat(x float64) float64 {
  1349. // t := math.Trunc(x)
  1350. // if math.Abs(x-t) >= 0.5 {
  1351. // return t + math.Copysign(1, x)
  1352. // }
  1353. // return t
  1354. // }
  1355. func panicToErr(h errstrDecorator, err *error) {
  1356. if recoverPanicToErr {
  1357. if x := recover(); x != nil {
  1358. // fmt.Printf("panic'ing with: %v\n", x)
  1359. // debug.PrintStack()
  1360. panicValToErr(h, x, err)
  1361. }
  1362. }
  1363. }
  1364. func panicToErrs2(h errstrDecorator, err1, err2 *error) {
  1365. if recoverPanicToErr {
  1366. if x := recover(); x != nil {
  1367. panicValToErr(h, x, err1)
  1368. panicValToErr(h, x, err2)
  1369. }
  1370. }
  1371. }
  1372. func panicValToErr(h errstrDecorator, v interface{}, err *error) {
  1373. switch xerr := v.(type) {
  1374. case nil:
  1375. case error:
  1376. switch xerr {
  1377. case nil:
  1378. case io.EOF, io.ErrUnexpectedEOF, errEncoderNotInitialized, errDecoderNotInitialized:
  1379. // treat as special (bubble up)
  1380. *err = xerr
  1381. default:
  1382. h.wrapErrstr(xerr.Error(), err)
  1383. }
  1384. case string:
  1385. if xerr != "" {
  1386. h.wrapErrstr(xerr, err)
  1387. }
  1388. case fmt.Stringer:
  1389. if xerr != nil {
  1390. h.wrapErrstr(xerr.String(), err)
  1391. }
  1392. default:
  1393. h.wrapErrstr(v, err)
  1394. }
  1395. }
  1396. func isImmutableKind(k reflect.Kind) (v bool) {
  1397. return immutableKindsSet[k]
  1398. }
  1399. // ----
  1400. type codecFnInfo struct {
  1401. ti *typeInfo
  1402. xfFn Ext
  1403. xfTag uint64
  1404. seq seqType
  1405. addrD bool
  1406. addrF bool // if addrD, this says whether decode function can take a value or a ptr
  1407. addrE bool
  1408. ready bool // ready to use
  1409. }
  1410. // codecFn encapsulates the captured variables and the encode function.
  1411. // This way, we only do some calculations one times, and pass to the
  1412. // code block that should be called (encapsulated in a function)
  1413. // instead of executing the checks every time.
  1414. type codecFn struct {
  1415. i codecFnInfo
  1416. fe func(*Encoder, *codecFnInfo, reflect.Value)
  1417. fd func(*Decoder, *codecFnInfo, reflect.Value)
  1418. _ [1]uint64 // padding
  1419. }
  1420. type codecRtidFn struct {
  1421. rtid uintptr
  1422. fn *codecFn
  1423. }
  1424. type codecFner struct {
  1425. // hh Handle
  1426. h *BasicHandle
  1427. s []codecRtidFn
  1428. be bool
  1429. js bool
  1430. _ [6]byte // padding
  1431. _ [3]uint64 // padding
  1432. }
  1433. func (c *codecFner) reset(hh Handle) {
  1434. bh := hh.getBasicHandle()
  1435. // only reset iff extensions changed or *TypeInfos changed
  1436. var hhSame = true &&
  1437. c.h == bh && c.h.TypeInfos == bh.TypeInfos &&
  1438. len(c.h.extHandle) == len(bh.extHandle) &&
  1439. (len(c.h.extHandle) == 0 || &c.h.extHandle[0] == &bh.extHandle[0])
  1440. if !hhSame {
  1441. // c.hh = hh
  1442. c.h, bh = bh, c.h // swap both
  1443. _, c.js = hh.(*JsonHandle)
  1444. c.be = hh.isBinary()
  1445. for i := range c.s {
  1446. c.s[i].fn.i.ready = false
  1447. }
  1448. }
  1449. }
  1450. func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
  1451. rtid := rt2id(rt)
  1452. for _, x := range c.s {
  1453. if x.rtid == rtid {
  1454. // if rtid exists, then there's a *codenFn attached (non-nil)
  1455. fn = x.fn
  1456. if fn.i.ready {
  1457. return
  1458. }
  1459. break
  1460. }
  1461. }
  1462. var ti *typeInfo
  1463. if fn == nil {
  1464. fn = new(codecFn)
  1465. if c.s == nil {
  1466. c.s = make([]codecRtidFn, 0, 8)
  1467. }
  1468. c.s = append(c.s, codecRtidFn{rtid, fn})
  1469. } else {
  1470. ti = fn.i.ti
  1471. *fn = codecFn{}
  1472. fn.i.ti = ti
  1473. // fn.fe, fn.fd = nil, nil
  1474. }
  1475. fi := &(fn.i)
  1476. fi.ready = true
  1477. if ti == nil {
  1478. ti = c.h.getTypeInfo(rtid, rt)
  1479. fi.ti = ti
  1480. }
  1481. rk := reflect.Kind(ti.kind)
  1482. if checkCodecSelfer && (ti.cs || ti.csp) {
  1483. fn.fe = (*Encoder).selferMarshal
  1484. fn.fd = (*Decoder).selferUnmarshal
  1485. fi.addrF = true
  1486. fi.addrD = ti.csp
  1487. fi.addrE = ti.csp
  1488. } else if rtid == timeTypId {
  1489. fn.fe = (*Encoder).kTime
  1490. fn.fd = (*Decoder).kTime
  1491. } else if rtid == rawTypId {
  1492. fn.fe = (*Encoder).raw
  1493. fn.fd = (*Decoder).raw
  1494. } else if rtid == rawExtTypId {
  1495. fn.fe = (*Encoder).rawExt
  1496. fn.fd = (*Decoder).rawExt
  1497. fi.addrF = true
  1498. fi.addrD = true
  1499. fi.addrE = true
  1500. } else if xfFn := c.h.getExt(rtid); xfFn != nil {
  1501. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  1502. fn.fe = (*Encoder).ext
  1503. fn.fd = (*Decoder).ext
  1504. fi.addrF = true
  1505. fi.addrD = true
  1506. if rk == reflect.Struct || rk == reflect.Array {
  1507. fi.addrE = true
  1508. }
  1509. } else if supportMarshalInterfaces && c.be && (ti.bm || ti.bmp) && (ti.bu || ti.bup) {
  1510. fn.fe = (*Encoder).binaryMarshal
  1511. fn.fd = (*Decoder).binaryUnmarshal
  1512. fi.addrF = true
  1513. fi.addrD = ti.bup
  1514. fi.addrE = ti.bmp
  1515. } else if supportMarshalInterfaces && !c.be && c.js && (ti.jm || ti.jmp) && (ti.ju || ti.jup) {
  1516. //If JSON, we should check JSONMarshal before textMarshal
  1517. fn.fe = (*Encoder).jsonMarshal
  1518. fn.fd = (*Decoder).jsonUnmarshal
  1519. fi.addrF = true
  1520. fi.addrD = ti.jup
  1521. fi.addrE = ti.jmp
  1522. } else if supportMarshalInterfaces && !c.be && (ti.tm || ti.tmp) && (ti.tu || ti.tup) {
  1523. fn.fe = (*Encoder).textMarshal
  1524. fn.fd = (*Decoder).textUnmarshal
  1525. fi.addrF = true
  1526. fi.addrD = ti.tup
  1527. fi.addrE = ti.tmp
  1528. } else {
  1529. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  1530. if ti.pkgpath == "" { // un-named slice or map
  1531. if idx := fastpathAV.index(rtid); idx != -1 {
  1532. fn.fe = fastpathAV[idx].encfn
  1533. fn.fd = fastpathAV[idx].decfn
  1534. fi.addrD = true
  1535. fi.addrF = false
  1536. }
  1537. } else {
  1538. // use mapping for underlying type if there
  1539. var rtu reflect.Type
  1540. if rk == reflect.Map {
  1541. rtu = reflect.MapOf(ti.key, ti.elem)
  1542. } else {
  1543. rtu = reflect.SliceOf(ti.elem)
  1544. }
  1545. rtuid := rt2id(rtu)
  1546. if idx := fastpathAV.index(rtuid); idx != -1 {
  1547. xfnf := fastpathAV[idx].encfn
  1548. xrt := fastpathAV[idx].rt
  1549. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  1550. xfnf(e, xf, xrv.Convert(xrt))
  1551. }
  1552. fi.addrD = true
  1553. fi.addrF = false // meaning it can be an address(ptr) or a value
  1554. xfnf2 := fastpathAV[idx].decfn
  1555. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1556. if xrv.Kind() == reflect.Ptr {
  1557. xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
  1558. } else {
  1559. xfnf2(d, xf, xrv.Convert(xrt))
  1560. }
  1561. }
  1562. }
  1563. }
  1564. }
  1565. if fn.fe == nil && fn.fd == nil {
  1566. switch rk {
  1567. case reflect.Bool:
  1568. fn.fe = (*Encoder).kBool
  1569. fn.fd = (*Decoder).kBool
  1570. case reflect.String:
  1571. fn.fe = (*Encoder).kString
  1572. fn.fd = (*Decoder).kString
  1573. case reflect.Int:
  1574. fn.fd = (*Decoder).kInt
  1575. fn.fe = (*Encoder).kInt
  1576. case reflect.Int8:
  1577. fn.fe = (*Encoder).kInt8
  1578. fn.fd = (*Decoder).kInt8
  1579. case reflect.Int16:
  1580. fn.fe = (*Encoder).kInt16
  1581. fn.fd = (*Decoder).kInt16
  1582. case reflect.Int32:
  1583. fn.fe = (*Encoder).kInt32
  1584. fn.fd = (*Decoder).kInt32
  1585. case reflect.Int64:
  1586. fn.fe = (*Encoder).kInt64
  1587. fn.fd = (*Decoder).kInt64
  1588. case reflect.Uint:
  1589. fn.fd = (*Decoder).kUint
  1590. fn.fe = (*Encoder).kUint
  1591. case reflect.Uint8:
  1592. fn.fe = (*Encoder).kUint8
  1593. fn.fd = (*Decoder).kUint8
  1594. case reflect.Uint16:
  1595. fn.fe = (*Encoder).kUint16
  1596. fn.fd = (*Decoder).kUint16
  1597. case reflect.Uint32:
  1598. fn.fe = (*Encoder).kUint32
  1599. fn.fd = (*Decoder).kUint32
  1600. case reflect.Uint64:
  1601. fn.fe = (*Encoder).kUint64
  1602. fn.fd = (*Decoder).kUint64
  1603. case reflect.Uintptr:
  1604. fn.fe = (*Encoder).kUintptr
  1605. fn.fd = (*Decoder).kUintptr
  1606. case reflect.Float32:
  1607. fn.fe = (*Encoder).kFloat32
  1608. fn.fd = (*Decoder).kFloat32
  1609. case reflect.Float64:
  1610. fn.fe = (*Encoder).kFloat64
  1611. fn.fd = (*Decoder).kFloat64
  1612. case reflect.Invalid:
  1613. fn.fe = (*Encoder).kInvalid
  1614. fn.fd = (*Decoder).kErr
  1615. case reflect.Chan:
  1616. fi.seq = seqTypeChan
  1617. fn.fe = (*Encoder).kSlice
  1618. fn.fd = (*Decoder).kSlice
  1619. case reflect.Slice:
  1620. fi.seq = seqTypeSlice
  1621. fn.fe = (*Encoder).kSlice
  1622. fn.fd = (*Decoder).kSlice
  1623. case reflect.Array:
  1624. fi.seq = seqTypeArray
  1625. fn.fe = (*Encoder).kSlice
  1626. fi.addrF = false
  1627. fi.addrD = false
  1628. rt2 := reflect.SliceOf(ti.elem)
  1629. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1630. d.cfer().get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
  1631. }
  1632. // fn.fd = (*Decoder).kArray
  1633. case reflect.Struct:
  1634. if ti.anyOmitEmpty {
  1635. fn.fe = (*Encoder).kStruct
  1636. } else {
  1637. fn.fe = (*Encoder).kStructNoOmitempty
  1638. }
  1639. fn.fd = (*Decoder).kStruct
  1640. case reflect.Map:
  1641. fn.fe = (*Encoder).kMap
  1642. fn.fd = (*Decoder).kMap
  1643. case reflect.Interface:
  1644. // encode: reflect.Interface are handled already by preEncodeValue
  1645. fn.fd = (*Decoder).kInterface
  1646. fn.fe = (*Encoder).kErr
  1647. default:
  1648. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  1649. fn.fe = (*Encoder).kErr
  1650. fn.fd = (*Decoder).kErr
  1651. }
  1652. }
  1653. }
  1654. return
  1655. }
  1656. type codecFnPooler struct {
  1657. cf *codecFner
  1658. cfp *sync.Pool
  1659. hh Handle
  1660. }
  1661. func (d *codecFnPooler) cfer() *codecFner {
  1662. if d.cf == nil {
  1663. var v interface{}
  1664. d.cfp, v = pool.codecFner()
  1665. d.cf = v.(*codecFner)
  1666. d.cf.reset(d.hh)
  1667. }
  1668. return d.cf
  1669. }
  1670. func (d *codecFnPooler) alwaysAtEnd() {
  1671. if d.cf != nil {
  1672. d.cfp.Put(d.cf)
  1673. d.cf, d.cfp = nil, nil
  1674. }
  1675. }
  1676. // ----
  1677. // these "checkOverflow" functions must be inlinable, and not call anybody.
  1678. // Overflow means that the value cannot be represented without wrapping/overflow.
  1679. // Overflow=false does not mean that the value can be represented without losing precision
  1680. // (especially for floating point).
  1681. type checkOverflow struct{}
  1682. // func (checkOverflow) Float16(f float64) (overflow bool) {
  1683. // panicv.errorf("unimplemented")
  1684. // if f < 0 {
  1685. // f = -f
  1686. // }
  1687. // return math.MaxFloat32 < f && f <= math.MaxFloat64
  1688. // }
  1689. func (checkOverflow) Float32(v float64) (overflow bool) {
  1690. if v < 0 {
  1691. v = -v
  1692. }
  1693. return math.MaxFloat32 < v && v <= math.MaxFloat64
  1694. }
  1695. func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  1696. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1697. return
  1698. }
  1699. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1700. overflow = true
  1701. }
  1702. return
  1703. }
  1704. func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  1705. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1706. return
  1707. }
  1708. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1709. overflow = true
  1710. }
  1711. return
  1712. }
  1713. func (checkOverflow) SignedInt(v uint64) (overflow bool) {
  1714. //e.g. -127 to 128 for int8
  1715. pos := (v >> 63) == 0
  1716. ui2 := v & 0x7fffffffffffffff
  1717. if pos {
  1718. if ui2 > math.MaxInt64 {
  1719. overflow = true
  1720. }
  1721. } else {
  1722. if ui2 > math.MaxInt64-1 {
  1723. overflow = true
  1724. }
  1725. }
  1726. return
  1727. }
  1728. func (x checkOverflow) Float32V(v float64) float64 {
  1729. if x.Float32(v) {
  1730. panicv.errorf("float32 overflow: %v", v)
  1731. }
  1732. return v
  1733. }
  1734. func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 {
  1735. if x.Uint(v, bitsize) {
  1736. panicv.errorf("uint64 overflow: %v", v)
  1737. }
  1738. return v
  1739. }
  1740. func (x checkOverflow) IntV(v int64, bitsize uint8) int64 {
  1741. if x.Int(v, bitsize) {
  1742. panicv.errorf("int64 overflow: %v", v)
  1743. }
  1744. return v
  1745. }
  1746. func (x checkOverflow) SignedIntV(v uint64) int64 {
  1747. if x.SignedInt(v) {
  1748. panicv.errorf("uint64 to int64 overflow: %v", v)
  1749. }
  1750. return int64(v)
  1751. }
  1752. // ------------------ SORT -----------------
  1753. func isNaN(f float64) bool { return f != f }
  1754. // -----------------------
  1755. type ioFlusher interface {
  1756. Flush() error
  1757. }
  1758. type ioPeeker interface {
  1759. Peek(int) ([]byte, error)
  1760. }
  1761. type ioBuffered interface {
  1762. Buffered() int
  1763. }
  1764. // -----------------------
  1765. type intSlice []int64
  1766. type uintSlice []uint64
  1767. // type uintptrSlice []uintptr
  1768. type floatSlice []float64
  1769. type boolSlice []bool
  1770. type stringSlice []string
  1771. // type bytesSlice [][]byte
  1772. func (p intSlice) Len() int { return len(p) }
  1773. func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
  1774. func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1775. func (p uintSlice) Len() int { return len(p) }
  1776. func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
  1777. func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1778. // func (p uintptrSlice) Len() int { return len(p) }
  1779. // func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] }
  1780. // func (p uintptrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1781. func (p floatSlice) Len() int { return len(p) }
  1782. func (p floatSlice) Less(i, j int) bool {
  1783. return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
  1784. }
  1785. func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1786. func (p stringSlice) Len() int { return len(p) }
  1787. func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
  1788. func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1789. // func (p bytesSlice) Len() int { return len(p) }
  1790. // func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
  1791. // func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1792. func (p boolSlice) Len() int { return len(p) }
  1793. func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
  1794. func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1795. // ---------------------
  1796. type intRv struct {
  1797. v int64
  1798. r reflect.Value
  1799. }
  1800. type intRvSlice []intRv
  1801. type uintRv struct {
  1802. v uint64
  1803. r reflect.Value
  1804. }
  1805. type uintRvSlice []uintRv
  1806. type floatRv struct {
  1807. v float64
  1808. r reflect.Value
  1809. }
  1810. type floatRvSlice []floatRv
  1811. type boolRv struct {
  1812. v bool
  1813. r reflect.Value
  1814. }
  1815. type boolRvSlice []boolRv
  1816. type stringRv struct {
  1817. v string
  1818. r reflect.Value
  1819. }
  1820. type stringRvSlice []stringRv
  1821. type bytesRv struct {
  1822. v []byte
  1823. r reflect.Value
  1824. }
  1825. type bytesRvSlice []bytesRv
  1826. type timeRv struct {
  1827. v time.Time
  1828. r reflect.Value
  1829. }
  1830. type timeRvSlice []timeRv
  1831. func (p intRvSlice) Len() int { return len(p) }
  1832. func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1833. func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1834. func (p uintRvSlice) Len() int { return len(p) }
  1835. func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1836. func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1837. func (p floatRvSlice) Len() int { return len(p) }
  1838. func (p floatRvSlice) Less(i, j int) bool {
  1839. return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
  1840. }
  1841. func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1842. func (p stringRvSlice) Len() int { return len(p) }
  1843. func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1844. func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1845. func (p bytesRvSlice) Len() int { return len(p) }
  1846. func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1847. func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1848. func (p boolRvSlice) Len() int { return len(p) }
  1849. func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
  1850. func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1851. func (p timeRvSlice) Len() int { return len(p) }
  1852. func (p timeRvSlice) Less(i, j int) bool { return p[i].v.Before(p[j].v) }
  1853. func (p timeRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1854. // -----------------
  1855. type bytesI struct {
  1856. v []byte
  1857. i interface{}
  1858. }
  1859. type bytesISlice []bytesI
  1860. func (p bytesISlice) Len() int { return len(p) }
  1861. func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1862. func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1863. // -----------------
  1864. type set []uintptr
  1865. func (s *set) add(v uintptr) (exists bool) {
  1866. // e.ci is always nil, or len >= 1
  1867. x := *s
  1868. if x == nil {
  1869. x = make([]uintptr, 1, 8)
  1870. x[0] = v
  1871. *s = x
  1872. return
  1873. }
  1874. // typically, length will be 1. make this perform.
  1875. if len(x) == 1 {
  1876. if j := x[0]; j == 0 {
  1877. x[0] = v
  1878. } else if j == v {
  1879. exists = true
  1880. } else {
  1881. x = append(x, v)
  1882. *s = x
  1883. }
  1884. return
  1885. }
  1886. // check if it exists
  1887. for _, j := range x {
  1888. if j == v {
  1889. exists = true
  1890. return
  1891. }
  1892. }
  1893. // try to replace a "deleted" slot
  1894. for i, j := range x {
  1895. if j == 0 {
  1896. x[i] = v
  1897. return
  1898. }
  1899. }
  1900. // if unable to replace deleted slot, just append it.
  1901. x = append(x, v)
  1902. *s = x
  1903. return
  1904. }
  1905. func (s *set) remove(v uintptr) (exists bool) {
  1906. x := *s
  1907. if len(x) == 0 {
  1908. return
  1909. }
  1910. if len(x) == 1 {
  1911. if x[0] == v {
  1912. x[0] = 0
  1913. }
  1914. return
  1915. }
  1916. for i, j := range x {
  1917. if j == v {
  1918. exists = true
  1919. x[i] = 0 // set it to 0, as way to delete it.
  1920. // copy(x[i:], x[i+1:])
  1921. // x = x[:len(x)-1]
  1922. return
  1923. }
  1924. }
  1925. return
  1926. }
  1927. // ------
  1928. // bitset types are better than [256]bool, because they permit the whole
  1929. // bitset array being on a single cache line and use less memory.
  1930. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  1931. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  1932. type bitset256 [32]byte
  1933. func (x *bitset256) isset(pos byte) bool {
  1934. return x[pos>>3]&(1<<(pos&7)) != 0
  1935. }
  1936. func (x *bitset256) issetv(pos byte) byte {
  1937. return x[pos>>3] & (1 << (pos & 7))
  1938. }
  1939. func (x *bitset256) set(pos byte) {
  1940. x[pos>>3] |= (1 << (pos & 7))
  1941. }
  1942. // func (x *bitset256) unset(pos byte) {
  1943. // x[pos>>3] &^= (1 << (pos & 7))
  1944. // }
  1945. type bitset128 [16]byte
  1946. func (x *bitset128) isset(pos byte) bool {
  1947. return x[pos>>3]&(1<<(pos&7)) != 0
  1948. }
  1949. func (x *bitset128) set(pos byte) {
  1950. x[pos>>3] |= (1 << (pos & 7))
  1951. }
  1952. // func (x *bitset128) unset(pos byte) {
  1953. // x[pos>>3] &^= (1 << (pos & 7))
  1954. // }
  1955. type bitset32 [4]byte
  1956. func (x *bitset32) isset(pos byte) bool {
  1957. return x[pos>>3]&(1<<(pos&7)) != 0
  1958. }
  1959. func (x *bitset32) set(pos byte) {
  1960. x[pos>>3] |= (1 << (pos & 7))
  1961. }
  1962. // func (x *bitset32) unset(pos byte) {
  1963. // x[pos>>3] &^= (1 << (pos & 7))
  1964. // }
  1965. // type bit2set256 [64]byte
  1966. // func (x *bit2set256) set(pos byte, v1, v2 bool) {
  1967. // var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6
  1968. // if v1 {
  1969. // x[pos>>2] |= 1 << (pos2 + 1)
  1970. // }
  1971. // if v2 {
  1972. // x[pos>>2] |= 1 << pos2
  1973. // }
  1974. // }
  1975. // func (x *bit2set256) get(pos byte) uint8 {
  1976. // var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6
  1977. // return x[pos>>2] << (6 - pos2) >> 6 // 11000000 -> 00000011
  1978. // }
  1979. // ------------
  1980. type pooler struct {
  1981. dn sync.Pool // for decNaked
  1982. cfn sync.Pool // for codecFner
  1983. tiload sync.Pool
  1984. strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool // for stringRV
  1985. }
  1986. func (p *pooler) init() {
  1987. p.strRv8.New = func() interface{} { return new([8]stringRv) }
  1988. p.strRv16.New = func() interface{} { return new([16]stringRv) }
  1989. p.strRv32.New = func() interface{} { return new([32]stringRv) }
  1990. p.strRv64.New = func() interface{} { return new([64]stringRv) }
  1991. p.strRv128.New = func() interface{} { return new([128]stringRv) }
  1992. p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
  1993. p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
  1994. p.cfn.New = func() interface{} { return new(codecFner) }
  1995. }
  1996. func (p *pooler) stringRv8() (sp *sync.Pool, v interface{}) {
  1997. return &p.strRv8, p.strRv8.Get()
  1998. }
  1999. func (p *pooler) stringRv16() (sp *sync.Pool, v interface{}) {
  2000. return &p.strRv16, p.strRv16.Get()
  2001. }
  2002. func (p *pooler) stringRv32() (sp *sync.Pool, v interface{}) {
  2003. return &p.strRv32, p.strRv32.Get()
  2004. }
  2005. func (p *pooler) stringRv64() (sp *sync.Pool, v interface{}) {
  2006. return &p.strRv64, p.strRv64.Get()
  2007. }
  2008. func (p *pooler) stringRv128() (sp *sync.Pool, v interface{}) {
  2009. return &p.strRv128, p.strRv128.Get()
  2010. }
  2011. func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
  2012. return &p.dn, p.dn.Get()
  2013. }
  2014. func (p *pooler) codecFner() (sp *sync.Pool, v interface{}) {
  2015. return &p.cfn, p.cfn.Get()
  2016. }
  2017. func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
  2018. return &p.tiload, p.tiload.Get()
  2019. }
  2020. // func (p *pooler) decNaked() (v *decNaked, f func(*decNaked) ) {
  2021. // sp := &(p.dn)
  2022. // vv := sp.Get()
  2023. // return vv.(*decNaked), func(x *decNaked) { sp.Put(vv) }
  2024. // }
  2025. // func (p *pooler) decNakedGet() (v interface{}) {
  2026. // return p.dn.Get()
  2027. // }
  2028. // func (p *pooler) codecFnerGet() (v interface{}) {
  2029. // return p.cfn.Get()
  2030. // }
  2031. // func (p *pooler) tiLoadGet() (v interface{}) {
  2032. // return p.tiload.Get()
  2033. // }
  2034. // func (p *pooler) decNakedPut(v interface{}) {
  2035. // p.dn.Put(v)
  2036. // }
  2037. // func (p *pooler) codecFnerPut(v interface{}) {
  2038. // p.cfn.Put(v)
  2039. // }
  2040. // func (p *pooler) tiLoadPut(v interface{}) {
  2041. // p.tiload.Put(v)
  2042. // }
  2043. type panicHdl struct{}
  2044. func (panicHdl) errorv(err error) {
  2045. if err != nil {
  2046. panic(err)
  2047. }
  2048. }
  2049. func (panicHdl) errorstr(message string) {
  2050. if message != "" {
  2051. panic(message)
  2052. }
  2053. }
  2054. func (panicHdl) errorf(format string, params ...interface{}) {
  2055. if format != "" {
  2056. if len(params) == 0 {
  2057. panic(format)
  2058. } else {
  2059. panic(fmt.Sprintf(format, params...))
  2060. }
  2061. }
  2062. }
  2063. type errstrDecorator interface {
  2064. wrapErrstr(interface{}, *error)
  2065. }
  2066. type errstrDecoratorDef struct{}
  2067. func (errstrDecoratorDef) wrapErrstr(v interface{}, e *error) { *e = fmt.Errorf("%v", v) }
  2068. type must struct{}
  2069. func (must) String(s string, err error) string {
  2070. if err != nil {
  2071. panicv.errorv(err)
  2072. }
  2073. return s
  2074. }
  2075. func (must) Int(s int64, err error) int64 {
  2076. if err != nil {
  2077. panicv.errorv(err)
  2078. }
  2079. return s
  2080. }
  2081. func (must) Uint(s uint64, err error) uint64 {
  2082. if err != nil {
  2083. panicv.errorv(err)
  2084. }
  2085. return s
  2086. }
  2087. func (must) Float(s float64, err error) float64 {
  2088. if err != nil {
  2089. panicv.errorv(err)
  2090. }
  2091. return s
  2092. }
  2093. // xdebugf prints the message in red on the terminal.
  2094. // Use it in place of fmt.Printf (which it calls internally)
  2095. func xdebugf(pattern string, args ...interface{}) {
  2096. var delim string
  2097. if len(pattern) > 0 && pattern[len(pattern)-1] != '\n' {
  2098. delim = "\n"
  2099. }
  2100. fmt.Printf("\033[1;31m"+pattern+delim+"\033[0m", args...)
  2101. }
  2102. // func isImmutableKind(k reflect.Kind) (v bool) {
  2103. // return false ||
  2104. // k == reflect.Int ||
  2105. // k == reflect.Int8 ||
  2106. // k == reflect.Int16 ||
  2107. // k == reflect.Int32 ||
  2108. // k == reflect.Int64 ||
  2109. // k == reflect.Uint ||
  2110. // k == reflect.Uint8 ||
  2111. // k == reflect.Uint16 ||
  2112. // k == reflect.Uint32 ||
  2113. // k == reflect.Uint64 ||
  2114. // k == reflect.Uintptr ||
  2115. // k == reflect.Float32 ||
  2116. // k == reflect.Float64 ||
  2117. // k == reflect.Bool ||
  2118. // k == reflect.String
  2119. // }
  2120. // func timeLocUTCName(tzint int16) string {
  2121. // if tzint == 0 {
  2122. // return "UTC"
  2123. // }
  2124. // var tzname = []byte("UTC+00:00")
  2125. // //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf. inline below.
  2126. // //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first
  2127. // var tzhr, tzmin int16
  2128. // if tzint < 0 {
  2129. // tzname[3] = '-' // (TODO: verify. this works here)
  2130. // tzhr, tzmin = -tzint/60, (-tzint)%60
  2131. // } else {
  2132. // tzhr, tzmin = tzint/60, tzint%60
  2133. // }
  2134. // tzname[4] = timeDigits[tzhr/10]
  2135. // tzname[5] = timeDigits[tzhr%10]
  2136. // tzname[7] = timeDigits[tzmin/10]
  2137. // tzname[8] = timeDigits[tzmin%10]
  2138. // return string(tzname)
  2139. // //return time.FixedZone(string(tzname), int(tzint)*60)
  2140. // }