helper.go 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928
  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. "sync/atomic"
  109. "time"
  110. )
  111. const (
  112. scratchByteArrayLen = 32
  113. // initCollectionCap = 16 // 32 is defensive. 16 is preferred.
  114. // Support encoding.(Binary|Text)(Unm|M)arshaler.
  115. // This constant flag will enable or disable it.
  116. supportMarshalInterfaces = true
  117. // for debugging, set this to false, to catch panic traces.
  118. // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
  119. recoverPanicToErr = true
  120. // arrayCacheLen is the length of the cache used in encoder or decoder for
  121. // allowing zero-alloc initialization.
  122. // arrayCacheLen = 8
  123. // size of the cacheline: defaulting to value for archs: amd64, arm64, 386
  124. // should use "runtime/internal/sys".CacheLineSize, but that is not exposed.
  125. cacheLineSize = 64
  126. wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize
  127. wordSize = wordSizeBits / 8
  128. // so structFieldInfo fits into 8 bytes
  129. maxLevelsEmbedding = 14
  130. // useFinalizers=true configures finalizers to release pool'ed resources
  131. // acquired by Encoder/Decoder during their GC.
  132. //
  133. // Note that calling SetFinalizer is always expensive,
  134. // as code must be run on the systemstack even for SetFinalizer(t, nil).
  135. //
  136. // We document that folks SHOULD call Release() when done, or they can
  137. // explicitly call SetFinalizer themselves e.g.
  138. // runtime.SetFinalizer(e, (*Encoder).Release)
  139. // runtime.SetFinalizer(d, (*Decoder).Release)
  140. useFinalizers = false
  141. // xdebug controls whether xdebugf prints any output
  142. xdebug = true
  143. )
  144. var (
  145. oneByteArr [1]byte
  146. zeroByteSlice = oneByteArr[:0:0]
  147. codecgen bool
  148. pool pooler
  149. panicv panicHdl
  150. refBitset bitset32
  151. isnilBitset bitset32
  152. scalarBitset bitset32
  153. )
  154. var (
  155. errMapTypeNotMapKind = errors.New("MapType MUST be of Map Kind")
  156. errSliceTypeNotSliceKind = errors.New("SliceType MUST be of Slice Kind")
  157. )
  158. func init() {
  159. pool.init()
  160. refBitset = refBitset.
  161. set(byte(reflect.Map)).
  162. set(byte(reflect.Ptr)).
  163. set(byte(reflect.Func)).
  164. set(byte(reflect.Chan)).
  165. set(byte(reflect.UnsafePointer))
  166. isnilBitset = isnilBitset.
  167. set(byte(reflect.Map)).
  168. set(byte(reflect.Ptr)).
  169. set(byte(reflect.Func)).
  170. set(byte(reflect.Chan)).
  171. set(byte(reflect.UnsafePointer)).
  172. set(byte(reflect.Interface)).
  173. set(byte(reflect.Slice))
  174. scalarBitset = scalarBitset.
  175. set(byte(reflect.Bool)).
  176. set(byte(reflect.Int)).
  177. set(byte(reflect.Int8)).
  178. set(byte(reflect.Int16)).
  179. set(byte(reflect.Int32)).
  180. set(byte(reflect.Int64)).
  181. set(byte(reflect.Uint)).
  182. set(byte(reflect.Uint8)).
  183. set(byte(reflect.Uint16)).
  184. set(byte(reflect.Uint32)).
  185. set(byte(reflect.Uint64)).
  186. set(byte(reflect.Uintptr)).
  187. set(byte(reflect.Float32)).
  188. set(byte(reflect.Float64)).
  189. set(byte(reflect.Complex64)).
  190. set(byte(reflect.Complex128)).
  191. set(byte(reflect.String))
  192. // xdebugf("bitsets: ref: %b, isnil: %b, scalar: %b", refBitset, isnilBitset, scalarBitset)
  193. }
  194. type handleFlag uint8
  195. const (
  196. initedHandleFlag handleFlag = 1 << iota
  197. binaryHandleFlag
  198. jsonHandleFlag
  199. )
  200. type clsErr struct {
  201. closed bool // is it closed?
  202. errClosed error // error on closing
  203. }
  204. // type entryType uint8
  205. // const (
  206. // entryTypeBytes entryType = iota // make this 0, so a comparison is cheap
  207. // entryTypeIo
  208. // entryTypeBufio
  209. // entryTypeUnset = 255
  210. // )
  211. type charEncoding uint8
  212. const (
  213. _ charEncoding = iota // make 0 unset
  214. cUTF8
  215. cUTF16LE
  216. cUTF16BE
  217. cUTF32LE
  218. cUTF32BE
  219. // Deprecated: not a true char encoding value
  220. cRAW charEncoding = 255
  221. )
  222. // valueType is the stream type
  223. type valueType uint8
  224. const (
  225. valueTypeUnset valueType = iota
  226. valueTypeNil
  227. valueTypeInt
  228. valueTypeUint
  229. valueTypeFloat
  230. valueTypeBool
  231. valueTypeString
  232. valueTypeSymbol
  233. valueTypeBytes
  234. valueTypeMap
  235. valueTypeArray
  236. valueTypeTime
  237. valueTypeExt
  238. // valueTypeInvalid = 0xff
  239. )
  240. var valueTypeStrings = [...]string{
  241. "Unset",
  242. "Nil",
  243. "Int",
  244. "Uint",
  245. "Float",
  246. "Bool",
  247. "String",
  248. "Symbol",
  249. "Bytes",
  250. "Map",
  251. "Array",
  252. "Timestamp",
  253. "Ext",
  254. }
  255. func (x valueType) String() string {
  256. if int(x) < len(valueTypeStrings) {
  257. return valueTypeStrings[x]
  258. }
  259. return strconv.FormatInt(int64(x), 10)
  260. }
  261. type seqType uint8
  262. const (
  263. _ seqType = iota
  264. seqTypeArray
  265. seqTypeSlice
  266. seqTypeChan
  267. )
  268. // note that containerMapStart and containerArraySend are not sent.
  269. // This is because the ReadXXXStart and EncodeXXXStart already does these.
  270. type containerState uint8
  271. const (
  272. _ containerState = iota
  273. containerMapStart
  274. containerMapKey
  275. containerMapValue
  276. containerMapEnd
  277. containerArrayStart
  278. containerArrayElem
  279. containerArrayEnd
  280. )
  281. // // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
  282. // type sfiIdx struct {
  283. // name string
  284. // index int
  285. // }
  286. // do not recurse if a containing type refers to an embedded type
  287. // which refers back to its containing type (via a pointer).
  288. // The second time this back-reference happens, break out,
  289. // so as not to cause an infinite loop.
  290. const rgetMaxRecursion = 2
  291. // Anecdotally, we believe most types have <= 12 fields.
  292. // - even Java's PMD rules set TooManyFields threshold to 15.
  293. // However, go has embedded fields, which should be regarded as
  294. // top level, allowing structs to possibly double or triple.
  295. // In addition, we don't want to keep creating transient arrays,
  296. // especially for the sfi index tracking, and the evtypes tracking.
  297. //
  298. // So - try to keep typeInfoLoadArray within 2K bytes
  299. const (
  300. typeInfoLoadArraySfisLen = 16
  301. typeInfoLoadArraySfiidxLen = 8 * 112
  302. typeInfoLoadArrayEtypesLen = 12
  303. typeInfoLoadArrayBLen = 8 * 4
  304. )
  305. // typeInfoLoad is a transient object used while loading up a typeInfo.
  306. type typeInfoLoad struct {
  307. // fNames []string
  308. // encNames []string
  309. etypes []uintptr
  310. sfis []structFieldInfo
  311. }
  312. // typeInfoLoadArray is a cache object used to efficiently load up a typeInfo without
  313. // much allocation.
  314. type typeInfoLoadArray struct {
  315. // fNames [typeInfoLoadArrayLen]string
  316. // encNames [typeInfoLoadArrayLen]string
  317. sfis [typeInfoLoadArraySfisLen]structFieldInfo
  318. sfiidx [typeInfoLoadArraySfiidxLen]byte
  319. etypes [typeInfoLoadArrayEtypesLen]uintptr
  320. b [typeInfoLoadArrayBLen]byte // scratch - used for struct field names
  321. }
  322. // // cacheLineSafer denotes that a type is safe for cache-line access.
  323. // // This could mean that
  324. // type cacheLineSafer interface {
  325. // cacheLineSafe()
  326. // }
  327. // mirror json.Marshaler and json.Unmarshaler here,
  328. // so we don't import the encoding/json package
  329. type jsonMarshaler interface {
  330. MarshalJSON() ([]byte, error)
  331. }
  332. type jsonUnmarshaler interface {
  333. UnmarshalJSON([]byte) error
  334. }
  335. type isZeroer interface {
  336. IsZero() bool
  337. }
  338. type codecError struct {
  339. name string
  340. err interface{}
  341. }
  342. func (e codecError) Cause() error {
  343. switch xerr := e.err.(type) {
  344. case nil:
  345. return nil
  346. case error:
  347. return xerr
  348. case string:
  349. return errors.New(xerr)
  350. case fmt.Stringer:
  351. return errors.New(xerr.String())
  352. default:
  353. return fmt.Errorf("%v", e.err)
  354. }
  355. }
  356. func (e codecError) Error() string {
  357. return fmt.Sprintf("%s error: %v", e.name, e.err)
  358. }
  359. // type byteAccepter func(byte) bool
  360. var (
  361. bigen = binary.BigEndian
  362. structInfoFieldName = "_struct"
  363. mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  364. mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
  365. intfSliceTyp = reflect.TypeOf([]interface{}(nil))
  366. intfTyp = intfSliceTyp.Elem()
  367. reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem()
  368. stringTyp = reflect.TypeOf("")
  369. timeTyp = reflect.TypeOf(time.Time{})
  370. rawExtTyp = reflect.TypeOf(RawExt{})
  371. rawTyp = reflect.TypeOf(Raw{})
  372. uintptrTyp = reflect.TypeOf(uintptr(0))
  373. uint8Typ = reflect.TypeOf(uint8(0))
  374. uint8SliceTyp = reflect.TypeOf([]uint8(nil))
  375. uintTyp = reflect.TypeOf(uint(0))
  376. intTyp = reflect.TypeOf(int(0))
  377. mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
  378. binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  379. binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  380. textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  381. textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  382. jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  383. jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  384. selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
  385. missingFielderTyp = reflect.TypeOf((*MissingFielder)(nil)).Elem()
  386. iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem()
  387. uint8TypId = rt2id(uint8Typ)
  388. uint8SliceTypId = rt2id(uint8SliceTyp)
  389. rawExtTypId = rt2id(rawExtTyp)
  390. rawTypId = rt2id(rawTyp)
  391. intfTypId = rt2id(intfTyp)
  392. timeTypId = rt2id(timeTyp)
  393. stringTypId = rt2id(stringTyp)
  394. mapStrIntfTypId = rt2id(mapStrIntfTyp)
  395. mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
  396. intfSliceTypId = rt2id(intfSliceTyp)
  397. // mapBySliceTypId = rt2id(mapBySliceTyp)
  398. intBitsize = uint8(intTyp.Bits())
  399. uintBitsize = uint8(uintTyp.Bits())
  400. // bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
  401. bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  402. chkOvf checkOverflow
  403. errNoFieldNameToStructFieldInfo = errors.New("no field name passed to parseStructFieldInfo")
  404. )
  405. var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
  406. var immutableKindsSet = [32]bool{
  407. // reflect.Invalid: ,
  408. reflect.Bool: true,
  409. reflect.Int: true,
  410. reflect.Int8: true,
  411. reflect.Int16: true,
  412. reflect.Int32: true,
  413. reflect.Int64: true,
  414. reflect.Uint: true,
  415. reflect.Uint8: true,
  416. reflect.Uint16: true,
  417. reflect.Uint32: true,
  418. reflect.Uint64: true,
  419. reflect.Uintptr: true,
  420. reflect.Float32: true,
  421. reflect.Float64: true,
  422. reflect.Complex64: true,
  423. reflect.Complex128: true,
  424. // reflect.Array
  425. // reflect.Chan
  426. // reflect.Func: true,
  427. // reflect.Interface
  428. // reflect.Map
  429. // reflect.Ptr
  430. // reflect.Slice
  431. reflect.String: true,
  432. // reflect.Struct
  433. // reflect.UnsafePointer
  434. }
  435. // SelfExt is a sentinel extension signifying that types
  436. // registered with it SHOULD be encoded and decoded
  437. // based on the naive mode of the format.
  438. //
  439. // This allows users to define a tag for an extension,
  440. // but signify that the types should be encoded/decoded as the native encoding.
  441. // This way, users need not also define how to encode or decode the extension.
  442. var SelfExt = &extFailWrapper{}
  443. // Selfer defines methods by which a value can encode or decode itself.
  444. //
  445. // Any type which implements Selfer will be able to encode or decode itself.
  446. // Consequently, during (en|de)code, this takes precedence over
  447. // (text|binary)(M|Unm)arshal or extension support.
  448. //
  449. // By definition, it is not allowed for a Selfer to directly call Encode or Decode on itself.
  450. // If that is done, Encode/Decode will rightfully fail with a Stack Overflow style error.
  451. // For example, the snippet below will cause such an error.
  452. // type testSelferRecur struct{}
  453. // func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) { e.MustEncode(s) }
  454. // func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) { d.MustDecode(s) }
  455. //
  456. // Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
  457. // This is because, during each decode, we first check the the next set of bytes
  458. // represent nil, and if so, we just set the value to nil.
  459. type Selfer interface {
  460. CodecEncodeSelf(*Encoder)
  461. CodecDecodeSelf(*Decoder)
  462. }
  463. // MissingFielder defines the interface allowing structs to internally decode or encode
  464. // values which do not map to struct fields.
  465. //
  466. // We expect that this interface is bound to a pointer type (so the mutation function works).
  467. //
  468. // A use-case is if a version of a type unexports a field, but you want compatibility between
  469. // both versions during encoding and decoding.
  470. //
  471. // Note that the interface is completely ignored during codecgen.
  472. type MissingFielder interface {
  473. // CodecMissingField is called to set a missing field and value pair.
  474. //
  475. // It returns true if the missing field was set on the struct.
  476. CodecMissingField(field []byte, value interface{}) bool
  477. // CodecMissingFields returns the set of fields which are not struct fields
  478. CodecMissingFields() map[string]interface{}
  479. }
  480. // MapBySlice is a tag interface that denotes wrapped slice should encode as a map in the stream.
  481. // The slice contains a sequence of key-value pairs.
  482. // This affords storing a map in a specific sequence in the stream.
  483. //
  484. // Example usage:
  485. // type T1 []string // or []int or []Point or any other "slice" type
  486. // func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map
  487. // type T2 struct { KeyValues T1 }
  488. //
  489. // var kvs = []string{"one", "1", "two", "2", "three", "3"}
  490. // var v2 = T2{ KeyValues: T1(kvs) }
  491. // // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} }
  492. //
  493. // The support of MapBySlice affords the following:
  494. // - A slice type which implements MapBySlice will be encoded as a map
  495. // - A slice can be decoded from a map in the stream
  496. // - It MUST be a slice type (not a pointer receiver) that implements MapBySlice
  497. type MapBySlice interface {
  498. MapBySlice()
  499. }
  500. // BasicHandle encapsulates the common options and extension functions.
  501. //
  502. // Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
  503. type BasicHandle struct {
  504. // BasicHandle is always a part of a different type.
  505. // It doesn't have to fit into it own cache lines.
  506. // TypeInfos is used to get the type info for any type.
  507. //
  508. // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
  509. TypeInfos *TypeInfos
  510. // Note: BasicHandle is not comparable, due to these slices here (extHandle, intf2impls).
  511. // If *[]T is used instead, this becomes comparable, at the cost of extra indirection.
  512. // Thses slices are used all the time, so keep as slices (not pointers).
  513. extHandle
  514. rtidFns atomicRtidFnSlice
  515. rtidFnsNoExt atomicRtidFnSlice
  516. // ---- cache line
  517. DecodeOptions
  518. // ---- cache line
  519. EncodeOptions
  520. intf2impls
  521. mu sync.Mutex
  522. inited uint32 // holds if inited, and also handle flags (binary encoding, json handler, etc)
  523. RPCOptions
  524. // TimeNotBuiltin configures whether time.Time should be treated as a builtin type.
  525. //
  526. // All Handlers should know how to encode/decode time.Time as part of the core
  527. // format specification, or as a standard extension defined by the format.
  528. //
  529. // However, users can elect to handle time.Time as a custom extension, or via the
  530. // standard library's encoding.Binary(M|Unm)arshaler or Text(M|Unm)arshaler interface.
  531. // To elect this behavior, users can set TimeNotBuiltin=true.
  532. //
  533. // Note: Setting TimeNotBuiltin=true can be used to enable the legacy behavior
  534. // (for Cbor and Msgpack), where time.Time was not a builtin supported type.
  535. //
  536. // Note: DO NOT CHANGE AFTER FIRST USE.
  537. //
  538. // Once a Handle has been used, do not modify this option.
  539. // It will lead to unexpected behaviour during encoding and decoding.
  540. TimeNotBuiltin bool
  541. // ExplicitRelease configures whether Release() is implicitly called after an encode or
  542. // decode call.
  543. //
  544. // If you will hold onto an Encoder or Decoder for re-use, by calling Reset(...)
  545. // on it or calling (Must)Encode repeatedly into a given []byte or io.Writer,
  546. // then you do not want it to be implicitly closed after each Encode/Decode call.
  547. // Doing so will unnecessarily return resources to the shared pool, only for you to
  548. // grab them right after again to do another Encode/Decode call.
  549. //
  550. // Instead, you configure ExplicitRelease=true, and you explicitly call Release() when
  551. // you are truly done.
  552. //
  553. // As an alternative, you can explicitly set a finalizer - so its resources
  554. // are returned to the shared pool before it is garbage-collected. Do it as below:
  555. // runtime.SetFinalizer(e, (*Encoder).Release)
  556. // runtime.SetFinalizer(d, (*Decoder).Release)
  557. ExplicitRelease bool
  558. // flags handleFlag // holds flag for if binaryEncoding, jsonHandler, etc
  559. // be bool // is handle a binary encoding?
  560. // js bool // is handle javascript handler?
  561. // n byte // first letter of handle name
  562. // _ uint16 // padding
  563. // ---- cache line
  564. // noBuiltInTypeChecker
  565. // _ uint32 // padding
  566. // r []uintptr // rtids mapped to s above
  567. }
  568. // basicHandle returns an initialized BasicHandle from the Handle.
  569. func basicHandle(hh Handle) (x *BasicHandle) {
  570. x = hh.getBasicHandle()
  571. // ** We need to simulate once.Do, to ensure no data race within the block.
  572. // ** Consequently, below would not work.
  573. // if atomic.CompareAndSwapUint32(&x.inited, 0, 1) {
  574. // x.be = hh.isBinary()
  575. // _, x.js = hh.(*JsonHandle)
  576. // x.n = hh.Name()[0]
  577. // }
  578. // simulate once.Do using our own stored flag and mutex as a CompareAndSwap
  579. // is not sufficient, since a race condition can occur within init(Handle) function.
  580. // init is made noinline, so that this function can be inlined by its caller.
  581. if atomic.LoadUint32(&x.inited) == 0 {
  582. x.init(hh)
  583. }
  584. return
  585. }
  586. func (x *BasicHandle) isJs() bool {
  587. return handleFlag(x.inited)&jsonHandleFlag != 0
  588. }
  589. func (x *BasicHandle) isBe() bool {
  590. return handleFlag(x.inited)&binaryHandleFlag != 0
  591. }
  592. //go:noinline
  593. func (x *BasicHandle) init(hh Handle) {
  594. // make it uninlineable, as it is called at most once
  595. x.mu.Lock()
  596. if x.inited == 0 {
  597. var f = initedHandleFlag
  598. if hh.isBinary() {
  599. f |= binaryHandleFlag
  600. }
  601. if _, b := hh.(*JsonHandle); b {
  602. f |= jsonHandleFlag
  603. }
  604. // _, x.js = hh.(*JsonHandle)
  605. // x.n = hh.Name()[0]
  606. atomic.StoreUint32(&x.inited, uint32(f))
  607. // ensure MapType and SliceType are of correct type
  608. if x.MapType != nil && x.MapType.Kind() != reflect.Map {
  609. panic(errMapTypeNotMapKind)
  610. }
  611. if x.SliceType != nil && x.SliceType.Kind() != reflect.Slice {
  612. panic(errSliceTypeNotSliceKind)
  613. }
  614. }
  615. x.mu.Unlock()
  616. }
  617. func (x *BasicHandle) getBasicHandle() *BasicHandle {
  618. return x
  619. }
  620. func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  621. if x.TypeInfos == nil {
  622. return defTypeInfos.get(rtid, rt)
  623. }
  624. return x.TypeInfos.get(rtid, rt)
  625. }
  626. func findFn(s []codecRtidFn, rtid uintptr) (i uint, fn *codecFn) {
  627. // binary search. adapted from sort/search.go.
  628. // Note: we use goto (instead of for loop) so this can be inlined.
  629. // h, i, j := 0, 0, len(s)
  630. var h uint // var h, i uint
  631. var j = uint(len(s))
  632. LOOP:
  633. if i < j {
  634. h = i + (j-i)/2
  635. if s[h].rtid < rtid {
  636. i = h + 1
  637. } else {
  638. j = h
  639. }
  640. goto LOOP
  641. }
  642. if i < uint(len(s)) && s[i].rtid == rtid {
  643. fn = s[i].fn
  644. }
  645. return
  646. }
  647. func (x *BasicHandle) fn(rt reflect.Type) (fn *codecFn) {
  648. return x.fnVia(rt, &x.rtidFns, true)
  649. }
  650. func (x *BasicHandle) fnNoExt(rt reflect.Type) (fn *codecFn) {
  651. return x.fnVia(rt, &x.rtidFnsNoExt, false)
  652. }
  653. func (x *BasicHandle) fnVia(rt reflect.Type, fs *atomicRtidFnSlice, checkExt bool) (fn *codecFn) {
  654. rtid := rt2id(rt)
  655. sp := fs.load()
  656. if sp != nil {
  657. if _, fn = findFn(sp, rtid); fn != nil {
  658. return
  659. }
  660. }
  661. fn = x.fnLoad(rt, rtid, checkExt)
  662. x.mu.Lock()
  663. var sp2 []codecRtidFn
  664. sp = fs.load()
  665. if sp == nil {
  666. sp2 = []codecRtidFn{{rtid, fn}}
  667. fs.store(sp2)
  668. } else {
  669. idx, fn2 := findFn(sp, rtid)
  670. if fn2 == nil {
  671. sp2 = make([]codecRtidFn, len(sp)+1)
  672. copy(sp2, sp[:idx])
  673. copy(sp2[idx+1:], sp[idx:])
  674. sp2[idx] = codecRtidFn{rtid, fn}
  675. fs.store(sp2)
  676. }
  677. }
  678. x.mu.Unlock()
  679. return
  680. }
  681. func (x *BasicHandle) fnLoad(rt reflect.Type, rtid uintptr, checkExt bool) (fn *codecFn) {
  682. fn = new(codecFn)
  683. fi := &(fn.i)
  684. ti := x.getTypeInfo(rtid, rt)
  685. fi.ti = ti
  686. rk := reflect.Kind(ti.kind)
  687. // anything can be an extension except the built-in ones: time, raw and rawext
  688. if rtid == timeTypId && !x.TimeNotBuiltin {
  689. fn.fe = (*Encoder).kTime
  690. fn.fd = (*Decoder).kTime
  691. } else if rtid == rawTypId {
  692. fn.fe = (*Encoder).raw
  693. fn.fd = (*Decoder).raw
  694. } else if rtid == rawExtTypId {
  695. fn.fe = (*Encoder).rawExt
  696. fn.fd = (*Decoder).rawExt
  697. fi.addrF = true
  698. fi.addrD = true
  699. fi.addrE = true
  700. } else if xfFn := x.getExt(rtid, checkExt); xfFn != nil {
  701. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  702. fn.fe = (*Encoder).ext
  703. fn.fd = (*Decoder).ext
  704. fi.addrF = true
  705. fi.addrD = true
  706. if rk == reflect.Struct || rk == reflect.Array {
  707. fi.addrE = true
  708. }
  709. } else if ti.isFlag(tiflagSelfer) || ti.isFlag(tiflagSelferPtr) {
  710. fn.fe = (*Encoder).selferMarshal
  711. fn.fd = (*Decoder).selferUnmarshal
  712. fi.addrF = true
  713. fi.addrD = ti.isFlag(tiflagSelferPtr)
  714. fi.addrE = ti.isFlag(tiflagSelferPtr)
  715. } else if supportMarshalInterfaces && x.isBe() &&
  716. (ti.isFlag(tiflagBinaryMarshaler) || ti.isFlag(tiflagBinaryMarshalerPtr)) &&
  717. (ti.isFlag(tiflagBinaryUnmarshaler) || ti.isFlag(tiflagBinaryUnmarshalerPtr)) {
  718. fn.fe = (*Encoder).binaryMarshal
  719. fn.fd = (*Decoder).binaryUnmarshal
  720. fi.addrF = true
  721. fi.addrD = ti.isFlag(tiflagBinaryUnmarshalerPtr)
  722. fi.addrE = ti.isFlag(tiflagBinaryMarshalerPtr)
  723. } else if supportMarshalInterfaces && !x.isBe() && x.isJs() &&
  724. (ti.isFlag(tiflagJsonMarshaler) || ti.isFlag(tiflagJsonMarshalerPtr)) &&
  725. (ti.isFlag(tiflagJsonUnmarshaler) || ti.isFlag(tiflagJsonUnmarshalerPtr)) {
  726. //If JSON, we should check JSONMarshal before textMarshal
  727. fn.fe = (*Encoder).jsonMarshal
  728. fn.fd = (*Decoder).jsonUnmarshal
  729. fi.addrF = true
  730. fi.addrD = ti.isFlag(tiflagJsonUnmarshalerPtr)
  731. fi.addrE = ti.isFlag(tiflagJsonMarshalerPtr)
  732. } else if supportMarshalInterfaces && !x.isBe() &&
  733. (ti.isFlag(tiflagTextMarshaler) || ti.isFlag(tiflagTextMarshalerPtr)) &&
  734. (ti.isFlag(tiflagTextUnmarshaler) || ti.isFlag(tiflagTextUnmarshalerPtr)) {
  735. fn.fe = (*Encoder).textMarshal
  736. fn.fd = (*Decoder).textUnmarshal
  737. fi.addrF = true
  738. fi.addrD = ti.isFlag(tiflagTextUnmarshalerPtr)
  739. fi.addrE = ti.isFlag(tiflagTextMarshalerPtr)
  740. } else {
  741. if fastpathEnabled && (rk == reflect.Map || rk == reflect.Slice) {
  742. if ti.pkgpath == "" { // un-named slice or map
  743. if idx := fastpathAV.index(rtid); idx != -1 {
  744. fn.fe = fastpathAV[idx].encfn
  745. fn.fd = fastpathAV[idx].decfn
  746. fi.addrD = true
  747. fi.addrF = false
  748. }
  749. } else {
  750. // use mapping for underlying type if there
  751. var rtu reflect.Type
  752. if rk == reflect.Map {
  753. rtu = reflect.MapOf(ti.key, ti.elem)
  754. } else {
  755. rtu = reflect.SliceOf(ti.elem)
  756. }
  757. rtuid := rt2id(rtu)
  758. if idx := fastpathAV.index(rtuid); idx != -1 {
  759. xfnf := fastpathAV[idx].encfn
  760. xrt := fastpathAV[idx].rt
  761. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  762. xfnf(e, xf, rvconvert(xrv, xrt))
  763. }
  764. fi.addrD = true
  765. fi.addrF = false // meaning it can be an address(ptr) or a value
  766. xfnf2 := fastpathAV[idx].decfn
  767. xptr2rt := reflect.PtrTo(xrt)
  768. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  769. // xdebug2f("fd: convert from %v to %v", xrv.Type(), xrt)
  770. if xrv.Kind() == reflect.Ptr {
  771. xfnf2(d, xf, rvconvert(xrv, xptr2rt))
  772. } else {
  773. xfnf2(d, xf, rvconvert(xrv, xrt))
  774. }
  775. }
  776. }
  777. }
  778. }
  779. if fn.fe == nil && fn.fd == nil {
  780. switch rk {
  781. case reflect.Bool:
  782. fn.fe = (*Encoder).kBool
  783. fn.fd = (*Decoder).kBool
  784. case reflect.String:
  785. // Do not check this here, as it will statically set the function for a string
  786. // type, and if the Handle is modified thereafter, behaviour is non-deterministic.
  787. //
  788. // if x.StringToRaw {
  789. // fn.fe = (*Encoder).kStringToRaw
  790. // } else {
  791. // fn.fe = (*Encoder).kStringEnc
  792. // }
  793. fn.fe = (*Encoder).kString
  794. fn.fd = (*Decoder).kString
  795. case reflect.Int:
  796. fn.fd = (*Decoder).kInt
  797. fn.fe = (*Encoder).kInt
  798. case reflect.Int8:
  799. fn.fe = (*Encoder).kInt8
  800. fn.fd = (*Decoder).kInt8
  801. case reflect.Int16:
  802. fn.fe = (*Encoder).kInt16
  803. fn.fd = (*Decoder).kInt16
  804. case reflect.Int32:
  805. fn.fe = (*Encoder).kInt32
  806. fn.fd = (*Decoder).kInt32
  807. case reflect.Int64:
  808. fn.fe = (*Encoder).kInt64
  809. fn.fd = (*Decoder).kInt64
  810. case reflect.Uint:
  811. fn.fd = (*Decoder).kUint
  812. fn.fe = (*Encoder).kUint
  813. case reflect.Uint8:
  814. fn.fe = (*Encoder).kUint8
  815. fn.fd = (*Decoder).kUint8
  816. case reflect.Uint16:
  817. fn.fe = (*Encoder).kUint16
  818. fn.fd = (*Decoder).kUint16
  819. case reflect.Uint32:
  820. fn.fe = (*Encoder).kUint32
  821. fn.fd = (*Decoder).kUint32
  822. case reflect.Uint64:
  823. fn.fe = (*Encoder).kUint64
  824. fn.fd = (*Decoder).kUint64
  825. case reflect.Uintptr:
  826. fn.fe = (*Encoder).kUintptr
  827. fn.fd = (*Decoder).kUintptr
  828. case reflect.Float32:
  829. fn.fe = (*Encoder).kFloat32
  830. fn.fd = (*Decoder).kFloat32
  831. case reflect.Float64:
  832. fn.fe = (*Encoder).kFloat64
  833. fn.fd = (*Decoder).kFloat64
  834. case reflect.Invalid:
  835. fn.fe = (*Encoder).kInvalid
  836. fn.fd = (*Decoder).kErr
  837. case reflect.Chan:
  838. fi.seq = seqTypeChan
  839. fn.fe = (*Encoder).kSlice
  840. fn.fd = (*Decoder).kSliceForChan
  841. case reflect.Slice:
  842. fi.seq = seqTypeSlice
  843. fn.fe = (*Encoder).kSlice
  844. fn.fd = (*Decoder).kSlice
  845. case reflect.Array:
  846. fi.seq = seqTypeArray
  847. fn.fe = (*Encoder).kSlice
  848. fi.addrF = false
  849. fi.addrD = false
  850. rt2 := reflect.SliceOf(ti.elem)
  851. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  852. d.h.fn(rt2).fd(d, xf, xrv.Slice(0, xrv.Len()))
  853. }
  854. // fn.fd = (*Decoder).kArray
  855. case reflect.Struct:
  856. if ti.anyOmitEmpty ||
  857. ti.isFlag(tiflagMissingFielder) ||
  858. ti.isFlag(tiflagMissingFielderPtr) {
  859. fn.fe = (*Encoder).kStruct
  860. } else {
  861. fn.fe = (*Encoder).kStructNoOmitempty
  862. }
  863. fn.fd = (*Decoder).kStruct
  864. case reflect.Map:
  865. fn.fe = (*Encoder).kMap
  866. fn.fd = (*Decoder).kMap
  867. case reflect.Interface:
  868. // encode: reflect.Interface are handled already by preEncodeValue
  869. fn.fd = (*Decoder).kInterface
  870. fn.fe = (*Encoder).kErr
  871. default:
  872. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  873. fn.fe = (*Encoder).kErr
  874. fn.fd = (*Decoder).kErr
  875. }
  876. }
  877. }
  878. return
  879. }
  880. // Handle defines a specific encoding format. It also stores any runtime state
  881. // used during an Encoding or Decoding session e.g. stored state about Types, etc.
  882. //
  883. // Once a handle is configured, it can be shared across multiple Encoders and Decoders.
  884. //
  885. // Note that a Handle is NOT safe for concurrent modification.
  886. //
  887. // A Handle also should not be modified after it is configured and has
  888. // been used at least once. This is because stored state may be out of sync with the
  889. // new configuration, and a data race can occur when multiple goroutines access it.
  890. // i.e. multiple Encoders or Decoders in different goroutines.
  891. //
  892. // Consequently, the typical usage model is that a Handle is pre-configured
  893. // before first time use, and not modified while in use.
  894. // Such a pre-configured Handle is safe for concurrent access.
  895. type Handle interface {
  896. Name() string
  897. // return the basic handle. It may not have been inited.
  898. // Prefer to use basicHandle() helper function that ensures it has been inited.
  899. getBasicHandle() *BasicHandle
  900. recreateEncDriver(encDriver) bool
  901. newEncDriver(w *Encoder) encDriver
  902. newDecDriver(r *Decoder) decDriver
  903. isBinary() bool
  904. hasElemSeparators() bool
  905. // IsBuiltinType(rtid uintptr) bool
  906. }
  907. // Raw represents raw formatted bytes.
  908. // We "blindly" store it during encode and retrieve the raw bytes during decode.
  909. // Note: it is dangerous during encode, so we may gate the behaviour
  910. // behind an Encode flag which must be explicitly set.
  911. type Raw []byte
  912. // RawExt represents raw unprocessed extension data.
  913. // Some codecs will decode extension data as a *RawExt
  914. // if there is no registered extension for the tag.
  915. //
  916. // Only one of Data or Value is nil.
  917. // If Data is nil, then the content of the RawExt is in the Value.
  918. type RawExt struct {
  919. Tag uint64
  920. // Data is the []byte which represents the raw ext. If nil, ext is exposed in Value.
  921. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of types
  922. Data []byte
  923. // Value represents the extension, if Data is nil.
  924. // Value is used by codecs (e.g. cbor, json) which leverage the format to do
  925. // custom serialization of the types.
  926. Value interface{}
  927. }
  928. // BytesExt handles custom (de)serialization of types to/from []byte.
  929. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  930. type BytesExt interface {
  931. // WriteExt converts a value to a []byte.
  932. //
  933. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  934. WriteExt(v interface{}) []byte
  935. // ReadExt updates a value from a []byte.
  936. //
  937. // Note: dst is always a pointer kind to the registered extension type.
  938. ReadExt(dst interface{}, src []byte)
  939. }
  940. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  941. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  942. //
  943. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of types.
  944. type InterfaceExt interface {
  945. // ConvertExt converts a value into a simpler interface for easy encoding
  946. // e.g. convert time.Time to int64.
  947. //
  948. // Note: v is a pointer iff the registered extension type is a struct or array kind.
  949. ConvertExt(v interface{}) interface{}
  950. // UpdateExt updates a value from a simpler interface for easy decoding
  951. // e.g. convert int64 to time.Time.
  952. //
  953. // Note: dst is always a pointer kind to the registered extension type.
  954. UpdateExt(dst interface{}, src interface{})
  955. }
  956. // Ext handles custom (de)serialization of custom types / extensions.
  957. type Ext interface {
  958. BytesExt
  959. InterfaceExt
  960. }
  961. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  962. type addExtWrapper struct {
  963. encFn func(reflect.Value) ([]byte, error)
  964. decFn func(reflect.Value, []byte) error
  965. }
  966. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  967. bs, err := x.encFn(reflect.ValueOf(v))
  968. if err != nil {
  969. panic(err)
  970. }
  971. return bs
  972. }
  973. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  974. if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
  975. panic(err)
  976. }
  977. }
  978. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  979. return x.WriteExt(v)
  980. }
  981. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  982. x.ReadExt(dest, v.([]byte))
  983. }
  984. type bytesExtFailer struct{}
  985. func (bytesExtFailer) WriteExt(v interface{}) []byte {
  986. panicv.errorstr("BytesExt.WriteExt is not supported")
  987. return nil
  988. }
  989. func (bytesExtFailer) ReadExt(v interface{}, bs []byte) {
  990. panicv.errorstr("BytesExt.ReadExt is not supported")
  991. }
  992. type interfaceExtFailer struct{}
  993. func (interfaceExtFailer) ConvertExt(v interface{}) interface{} {
  994. panicv.errorstr("InterfaceExt.ConvertExt is not supported")
  995. return nil
  996. }
  997. func (interfaceExtFailer) UpdateExt(dest interface{}, v interface{}) {
  998. panicv.errorstr("InterfaceExt.UpdateExt is not supported")
  999. }
  1000. // type extWrapper struct {
  1001. // BytesExt
  1002. // InterfaceExt
  1003. // }
  1004. type bytesExtWrapper struct {
  1005. interfaceExtFailer
  1006. BytesExt
  1007. }
  1008. type interfaceExtWrapper struct {
  1009. bytesExtFailer
  1010. InterfaceExt
  1011. }
  1012. type extFailWrapper struct {
  1013. bytesExtFailer
  1014. interfaceExtFailer
  1015. }
  1016. type binaryEncodingType struct{}
  1017. func (binaryEncodingType) isBinary() bool { return true }
  1018. type textEncodingType struct{}
  1019. func (textEncodingType) isBinary() bool { return false }
  1020. // noBuiltInTypes is embedded into many types which do not support builtins
  1021. // e.g. msgpack, simple, cbor.
  1022. // type noBuiltInTypeChecker struct{}
  1023. // func (noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
  1024. // type noBuiltInTypes struct{ noBuiltInTypeChecker }
  1025. type noBuiltInTypes struct{}
  1026. func (noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  1027. func (noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  1028. // type noStreamingCodec struct{}
  1029. // func (noStreamingCodec) CheckBreak() bool { return false }
  1030. // func (noStreamingCodec) hasElemSeparators() bool { return false }
  1031. type noElemSeparators struct{}
  1032. func (noElemSeparators) hasElemSeparators() (v bool) { return }
  1033. func (noElemSeparators) recreateEncDriver(e encDriver) (v bool) { return }
  1034. // bigenHelper.
  1035. // Users must already slice the x completely, because we will not reslice.
  1036. type bigenHelper struct {
  1037. x []byte // must be correctly sliced to appropriate len. slicing is a cost.
  1038. w *encWriterSwitch
  1039. }
  1040. func (z bigenHelper) writeUint16(v uint16) {
  1041. bigen.PutUint16(z.x, v)
  1042. z.w.writeb(z.x)
  1043. }
  1044. func (z bigenHelper) writeUint32(v uint32) {
  1045. bigen.PutUint32(z.x, v)
  1046. z.w.writeb(z.x)
  1047. }
  1048. func (z bigenHelper) writeUint64(v uint64) {
  1049. bigen.PutUint64(z.x, v)
  1050. z.w.writeb(z.x)
  1051. }
  1052. type extTypeTagFn struct {
  1053. rtid uintptr
  1054. rtidptr uintptr
  1055. rt reflect.Type
  1056. tag uint64
  1057. ext Ext
  1058. // _ [1]uint64 // padding
  1059. }
  1060. type extHandle []extTypeTagFn
  1061. // AddExt registes an encode and decode function for a reflect.Type.
  1062. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  1063. //
  1064. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  1065. func (o *extHandle) AddExt(rt reflect.Type, tag byte,
  1066. encfn func(reflect.Value) ([]byte, error),
  1067. decfn func(reflect.Value, []byte) error) (err error) {
  1068. if encfn == nil || decfn == nil {
  1069. return o.SetExt(rt, uint64(tag), nil)
  1070. }
  1071. return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  1072. }
  1073. // SetExt will set the extension for a tag and reflect.Type.
  1074. // Note that the type must be a named type, and specifically not a pointer or Interface.
  1075. // An error is returned if that is not honored.
  1076. // To Deregister an ext, call SetExt with nil Ext.
  1077. //
  1078. // Deprecated: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  1079. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  1080. // o is a pointer, because we may need to initialize it
  1081. rk := rt.Kind()
  1082. for rk == reflect.Ptr {
  1083. rt = rt.Elem()
  1084. rk = rt.Kind()
  1085. }
  1086. if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr {
  1087. return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt)
  1088. }
  1089. rtid := rt2id(rt)
  1090. switch rtid {
  1091. case timeTypId, rawTypId, rawExtTypId:
  1092. // all natively supported type, so cannot have an extension
  1093. return // TODO: should we silently ignore, or return an error???
  1094. }
  1095. // if o == nil {
  1096. // return errors.New("codec.Handle.SetExt: extHandle not initialized")
  1097. // }
  1098. o2 := *o
  1099. // if o2 == nil {
  1100. // return errors.New("codec.Handle.SetExt: extHandle not initialized")
  1101. // }
  1102. for i := range o2 {
  1103. v := &o2[i]
  1104. if v.rtid == rtid {
  1105. v.tag, v.ext = tag, ext
  1106. return
  1107. }
  1108. }
  1109. rtidptr := rt2id(reflect.PtrTo(rt))
  1110. *o = append(o2, extTypeTagFn{rtid, rtidptr, rt, tag, ext}) // , [1]uint64{}})
  1111. return
  1112. }
  1113. func (o extHandle) getExt(rtid uintptr, check bool) (v *extTypeTagFn) {
  1114. if !check {
  1115. return
  1116. }
  1117. for i := range o {
  1118. v = &o[i]
  1119. if v.rtid == rtid || v.rtidptr == rtid {
  1120. return
  1121. }
  1122. }
  1123. return nil
  1124. }
  1125. func (o extHandle) getExtForTag(tag uint64) (v *extTypeTagFn) {
  1126. for i := range o {
  1127. v = &o[i]
  1128. if v.tag == tag {
  1129. return
  1130. }
  1131. }
  1132. return nil
  1133. }
  1134. type intf2impl struct {
  1135. rtid uintptr // for intf
  1136. impl reflect.Type
  1137. // _ [1]uint64 // padding // not-needed, as *intf2impl is never returned.
  1138. }
  1139. type intf2impls []intf2impl
  1140. // Intf2Impl maps an interface to an implementing type.
  1141. // This allows us support infering the concrete type
  1142. // and populating it when passed an interface.
  1143. // e.g. var v io.Reader can be decoded as a bytes.Buffer, etc.
  1144. //
  1145. // Passing a nil impl will clear the mapping.
  1146. func (o *intf2impls) Intf2Impl(intf, impl reflect.Type) (err error) {
  1147. if impl != nil && !impl.Implements(intf) {
  1148. return fmt.Errorf("Intf2Impl: %v does not implement %v", impl, intf)
  1149. }
  1150. rtid := rt2id(intf)
  1151. o2 := *o
  1152. for i := range o2 {
  1153. v := &o2[i]
  1154. if v.rtid == rtid {
  1155. v.impl = impl
  1156. return
  1157. }
  1158. }
  1159. *o = append(o2, intf2impl{rtid, impl})
  1160. return
  1161. }
  1162. func (o intf2impls) intf2impl(rtid uintptr) (rv reflect.Value) {
  1163. for i := range o {
  1164. v := &o[i]
  1165. if v.rtid == rtid {
  1166. if v.impl == nil {
  1167. return
  1168. }
  1169. vkind := v.impl.Kind()
  1170. if vkind == reflect.Ptr {
  1171. return reflect.New(v.impl.Elem())
  1172. }
  1173. return rvzeroaddrk(v.impl, vkind)
  1174. }
  1175. }
  1176. return
  1177. }
  1178. type structFieldInfoFlag uint8
  1179. const (
  1180. _ structFieldInfoFlag = 1 << iota
  1181. structFieldInfoFlagReady
  1182. structFieldInfoFlagOmitEmpty
  1183. )
  1184. func (x *structFieldInfoFlag) flagSet(f structFieldInfoFlag) {
  1185. *x = *x | f
  1186. }
  1187. func (x *structFieldInfoFlag) flagClr(f structFieldInfoFlag) {
  1188. *x = *x &^ f
  1189. }
  1190. func (x structFieldInfoFlag) flagGet(f structFieldInfoFlag) bool {
  1191. return x&f != 0
  1192. }
  1193. func (x structFieldInfoFlag) omitEmpty() bool {
  1194. return x.flagGet(structFieldInfoFlagOmitEmpty)
  1195. }
  1196. func (x structFieldInfoFlag) ready() bool {
  1197. return x.flagGet(structFieldInfoFlagReady)
  1198. }
  1199. type structFieldInfo struct {
  1200. encName string // encode name
  1201. fieldName string // field name
  1202. is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
  1203. nis uint8 // num levels of embedding. if 1, then it's not embedded.
  1204. encNameAsciiAlphaNum bool // the encName only contains ascii alphabet and numbers
  1205. structFieldInfoFlag
  1206. // _ [1]byte // padding
  1207. }
  1208. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  1209. if v, valid := si.field(v, false); valid {
  1210. v.Set(reflect.Zero(v.Type()))
  1211. }
  1212. }
  1213. // rv returns the field of the struct.
  1214. // If anonymous, it returns an Invalid
  1215. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
  1216. // replicate FieldByIndex
  1217. for i, x := range si.is {
  1218. if uint8(i) == si.nis {
  1219. break
  1220. }
  1221. if v, valid = baseStructRv(v, update); !valid {
  1222. return
  1223. }
  1224. v = v.Field(int(x))
  1225. }
  1226. return v, true
  1227. }
  1228. // func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
  1229. // v, _ = si.field(v, update)
  1230. // return v
  1231. // }
  1232. func parseStructInfo(stag string) (toArray, omitEmpty bool, keytype valueType) {
  1233. keytype = valueTypeString // default
  1234. if stag == "" {
  1235. return
  1236. }
  1237. for i, s := range strings.Split(stag, ",") {
  1238. if i == 0 {
  1239. } else {
  1240. switch s {
  1241. case "omitempty":
  1242. omitEmpty = true
  1243. case "toarray":
  1244. toArray = true
  1245. case "int":
  1246. keytype = valueTypeInt
  1247. case "uint":
  1248. keytype = valueTypeUint
  1249. case "float":
  1250. keytype = valueTypeFloat
  1251. // case "bool":
  1252. // keytype = valueTypeBool
  1253. case "string":
  1254. keytype = valueTypeString
  1255. }
  1256. }
  1257. }
  1258. return
  1259. }
  1260. func (si *structFieldInfo) parseTag(stag string) {
  1261. // if fname == "" {
  1262. // panic(errNoFieldNameToStructFieldInfo)
  1263. // }
  1264. if stag == "" {
  1265. return
  1266. }
  1267. for i, s := range strings.Split(stag, ",") {
  1268. if i == 0 {
  1269. if s != "" {
  1270. si.encName = s
  1271. }
  1272. } else {
  1273. switch s {
  1274. case "omitempty":
  1275. si.flagSet(structFieldInfoFlagOmitEmpty)
  1276. // si.omitEmpty = true
  1277. // case "toarray":
  1278. // si.toArray = true
  1279. }
  1280. }
  1281. }
  1282. }
  1283. type sfiSortedByEncName []*structFieldInfo
  1284. func (p sfiSortedByEncName) Len() int { return len(p) }
  1285. func (p sfiSortedByEncName) Less(i, j int) bool { return p[uint(i)].encName < p[uint(j)].encName }
  1286. func (p sfiSortedByEncName) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
  1287. const structFieldNodeNumToCache = 4
  1288. type structFieldNodeCache struct {
  1289. rv [structFieldNodeNumToCache]reflect.Value
  1290. idx [structFieldNodeNumToCache]uint32
  1291. num uint8
  1292. }
  1293. func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
  1294. for i, k := range &x.idx {
  1295. if uint8(i) == x.num {
  1296. return // break
  1297. }
  1298. if key == k {
  1299. return x.rv[i], true
  1300. }
  1301. }
  1302. return
  1303. }
  1304. func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
  1305. if x.num < structFieldNodeNumToCache {
  1306. x.rv[x.num] = fv
  1307. x.idx[x.num] = key
  1308. x.num++
  1309. return
  1310. }
  1311. }
  1312. type structFieldNode struct {
  1313. v reflect.Value
  1314. cache2 structFieldNodeCache
  1315. cache3 structFieldNodeCache
  1316. update bool
  1317. }
  1318. func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
  1319. // return si.fieldval(x.v, x.update)
  1320. // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
  1321. // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
  1322. var valid bool
  1323. switch si.nis {
  1324. case 1:
  1325. fv = x.v.Field(int(si.is[0]))
  1326. case 2:
  1327. if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
  1328. fv = fv.Field(int(si.is[1]))
  1329. return
  1330. }
  1331. fv = x.v.Field(int(si.is[0]))
  1332. if fv, valid = baseStructRv(fv, x.update); !valid {
  1333. return
  1334. }
  1335. x.cache2.tryAdd(fv, uint32(si.is[0]))
  1336. fv = fv.Field(int(si.is[1]))
  1337. case 3:
  1338. var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
  1339. if fv, valid = x.cache3.get(key); valid {
  1340. fv = fv.Field(int(si.is[2]))
  1341. return
  1342. }
  1343. fv = x.v.Field(int(si.is[0]))
  1344. if fv, valid = baseStructRv(fv, x.update); !valid {
  1345. return
  1346. }
  1347. fv = fv.Field(int(si.is[1]))
  1348. if fv, valid = baseStructRv(fv, x.update); !valid {
  1349. return
  1350. }
  1351. x.cache3.tryAdd(fv, key)
  1352. fv = fv.Field(int(si.is[2]))
  1353. default:
  1354. fv, _ = si.field(x.v, x.update)
  1355. }
  1356. return
  1357. }
  1358. func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
  1359. for v.Kind() == reflect.Ptr {
  1360. if rvisnil(v) {
  1361. if !update {
  1362. return
  1363. }
  1364. v.Set(reflect.New(v.Type().Elem()))
  1365. }
  1366. v = v.Elem()
  1367. }
  1368. return v, true
  1369. }
  1370. type tiflag uint32
  1371. const (
  1372. _ tiflag = 1 << iota
  1373. tiflagComparable
  1374. tiflagIsZeroer
  1375. tiflagIsZeroerPtr
  1376. tiflagBinaryMarshaler
  1377. tiflagBinaryMarshalerPtr
  1378. tiflagBinaryUnmarshaler
  1379. tiflagBinaryUnmarshalerPtr
  1380. tiflagTextMarshaler
  1381. tiflagTextMarshalerPtr
  1382. tiflagTextUnmarshaler
  1383. tiflagTextUnmarshalerPtr
  1384. tiflagJsonMarshaler
  1385. tiflagJsonMarshalerPtr
  1386. tiflagJsonUnmarshaler
  1387. tiflagJsonUnmarshalerPtr
  1388. tiflagSelfer
  1389. tiflagSelferPtr
  1390. tiflagMissingFielder
  1391. tiflagMissingFielderPtr
  1392. // tiflag
  1393. // tiflag
  1394. // tiflag
  1395. // tiflag
  1396. // tiflag
  1397. // tiflag
  1398. )
  1399. // typeInfo keeps static (non-changing readonly)information
  1400. // about each (non-ptr) type referenced in the encode/decode sequence.
  1401. //
  1402. // During an encode/decode sequence, we work as below:
  1403. // - If base is a built in type, en/decode base value
  1404. // - If base is registered as an extension, en/decode base value
  1405. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  1406. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  1407. // - Else decode appropriately based on the reflect.Kind
  1408. type typeInfo struct {
  1409. rt reflect.Type
  1410. elem reflect.Type
  1411. pkgpath string
  1412. rtid uintptr
  1413. // rv0 reflect.Value // saved zero value, used if immutableKind
  1414. numMeth uint16 // number of methods
  1415. kind uint8
  1416. chandir uint8
  1417. anyOmitEmpty bool // true if a struct, and any of the fields are tagged "omitempty"
  1418. toArray bool // whether this (struct) type should be encoded as an array
  1419. keyType valueType // if struct, how is the field name stored in a stream? default is string
  1420. mbs bool // base type (T or *T) is a MapBySlice
  1421. // ---- cpu cache line boundary?
  1422. sfiSort []*structFieldInfo // sorted. Used when enc/dec struct to map.
  1423. sfiSrc []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  1424. key reflect.Type
  1425. // ---- cpu cache line boundary?
  1426. // sfis []structFieldInfo // all sfi, in src order, as created.
  1427. sfiNamesSort []byte // all names, with indexes into the sfiSort
  1428. // rv0 is the zero value for the type.
  1429. // It is mostly beneficial for all non-reference kinds
  1430. // i.e. all but map/chan/func/ptr/unsafe.pointer
  1431. // so beneficial for intXX, bool, slices, structs, etc
  1432. rv0 reflect.Value
  1433. // format of marshal type fields below: [btj][mu]p? OR csp?
  1434. // bm bool // T is a binaryMarshaler
  1435. // bmp bool // *T is a binaryMarshaler
  1436. // bu bool // T is a binaryUnmarshaler
  1437. // bup bool // *T is a binaryUnmarshaler
  1438. // tm bool // T is a textMarshaler
  1439. // tmp bool // *T is a textMarshaler
  1440. // tu bool // T is a textUnmarshaler
  1441. // tup bool // *T is a textUnmarshaler
  1442. // jm bool // T is a jsonMarshaler
  1443. // jmp bool // *T is a jsonMarshaler
  1444. // ju bool // T is a jsonUnmarshaler
  1445. // jup bool // *T is a jsonUnmarshaler
  1446. // cs bool // T is a Selfer
  1447. // csp bool // *T is a Selfer
  1448. // mf bool // T is a MissingFielder
  1449. // mfp bool // *T is a MissingFielder
  1450. // other flags, with individual bits representing if set.
  1451. flags tiflag
  1452. infoFieldOmitempty bool
  1453. _ [3]byte // padding
  1454. _ [1]uint64 // padding
  1455. }
  1456. func (ti *typeInfo) isFlag(f tiflag) bool {
  1457. return ti.flags&f != 0
  1458. }
  1459. func (ti *typeInfo) flag(when bool, f tiflag) *typeInfo {
  1460. if when {
  1461. ti.flags |= f
  1462. }
  1463. return ti
  1464. }
  1465. func (ti *typeInfo) indexForEncName(name []byte) (index int16) {
  1466. var sn []byte
  1467. if len(name)+2 <= 32 {
  1468. var buf [32]byte // should not escape to heap
  1469. sn = buf[:len(name)+2]
  1470. } else {
  1471. sn = make([]byte, len(name)+2)
  1472. }
  1473. copy(sn[1:], name)
  1474. sn[0], sn[len(sn)-1] = tiSep2(name), 0xff
  1475. j := bytes.Index(ti.sfiNamesSort, sn)
  1476. if j < 0 {
  1477. return -1
  1478. }
  1479. index = int16(uint16(ti.sfiNamesSort[j+len(sn)+1]) | uint16(ti.sfiNamesSort[j+len(sn)])<<8)
  1480. return
  1481. }
  1482. type rtid2ti struct {
  1483. rtid uintptr
  1484. ti *typeInfo
  1485. }
  1486. // TypeInfos caches typeInfo for each type on first inspection.
  1487. //
  1488. // It is configured with a set of tag keys, which are used to get
  1489. // configuration for the type.
  1490. type TypeInfos struct {
  1491. // infos: formerly map[uintptr]*typeInfo, now *[]rtid2ti, 2 words expected
  1492. infos atomicTypeInfoSlice
  1493. mu sync.Mutex
  1494. _ uint64 // padding (cache-aligned)
  1495. tags []string
  1496. _ uint64 // padding (cache-aligned)
  1497. }
  1498. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  1499. //
  1500. // This allows users customize the struct tag keys which contain configuration
  1501. // of their types.
  1502. func NewTypeInfos(tags []string) *TypeInfos {
  1503. return &TypeInfos{tags: tags}
  1504. }
  1505. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  1506. // check for tags: codec, json, in that order.
  1507. // this allows seamless support for many configured structs.
  1508. for _, x := range x.tags {
  1509. s = t.Get(x)
  1510. if s != "" {
  1511. return s
  1512. }
  1513. }
  1514. return
  1515. }
  1516. func findTypeInfo(s []rtid2ti, rtid uintptr) (i uint, ti *typeInfo) {
  1517. // binary search. adapted from sort/search.go.
  1518. // Note: we use goto (instead of for loop) so this can be inlined.
  1519. // if sp == nil {
  1520. // return -1, nil
  1521. // }
  1522. // s := *sp
  1523. // h, i, j := 0, 0, len(s)
  1524. var h uint // var h, i uint
  1525. var j = uint(len(s))
  1526. LOOP:
  1527. if i < j {
  1528. h = i + (j-i)/2
  1529. if s[h].rtid < rtid {
  1530. i = h + 1
  1531. } else {
  1532. j = h
  1533. }
  1534. goto LOOP
  1535. }
  1536. if i < uint(len(s)) && s[i].rtid == rtid {
  1537. ti = s[i].ti
  1538. }
  1539. return
  1540. }
  1541. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  1542. sp := x.infos.load()
  1543. if sp != nil {
  1544. _, pti = findTypeInfo(sp, rtid)
  1545. if pti != nil {
  1546. return
  1547. }
  1548. }
  1549. rk := rt.Kind()
  1550. if rk == reflect.Ptr { // || (rk == reflect.Interface && rtid != intfTypId) {
  1551. panicv.errorf("invalid kind passed to TypeInfos.get: %v - %v", rk, rt)
  1552. }
  1553. // do not hold lock while computing this.
  1554. // it may lead to duplication, but that's ok.
  1555. ti := typeInfo{
  1556. rt: rt,
  1557. rtid: rtid,
  1558. kind: uint8(rk),
  1559. pkgpath: rt.PkgPath(),
  1560. keyType: valueTypeString, // default it - so it's never 0
  1561. }
  1562. ti.rv0 = reflect.Zero(rt)
  1563. // ti.comparable = rt.Comparable()
  1564. ti.numMeth = uint16(rt.NumMethod())
  1565. var b1, b2 bool
  1566. b1, b2 = implIntf(rt, binaryMarshalerTyp)
  1567. ti.flag(b1, tiflagBinaryMarshaler).flag(b2, tiflagBinaryMarshalerPtr)
  1568. b1, b2 = implIntf(rt, binaryUnmarshalerTyp)
  1569. ti.flag(b1, tiflagBinaryUnmarshaler).flag(b2, tiflagBinaryUnmarshalerPtr)
  1570. b1, b2 = implIntf(rt, textMarshalerTyp)
  1571. ti.flag(b1, tiflagTextMarshaler).flag(b2, tiflagTextMarshalerPtr)
  1572. b1, b2 = implIntf(rt, textUnmarshalerTyp)
  1573. ti.flag(b1, tiflagTextUnmarshaler).flag(b2, tiflagTextUnmarshalerPtr)
  1574. b1, b2 = implIntf(rt, jsonMarshalerTyp)
  1575. ti.flag(b1, tiflagJsonMarshaler).flag(b2, tiflagJsonMarshalerPtr)
  1576. b1, b2 = implIntf(rt, jsonUnmarshalerTyp)
  1577. ti.flag(b1, tiflagJsonUnmarshaler).flag(b2, tiflagJsonUnmarshalerPtr)
  1578. b1, b2 = implIntf(rt, selferTyp)
  1579. ti.flag(b1, tiflagSelfer).flag(b2, tiflagSelferPtr)
  1580. b1, b2 = implIntf(rt, missingFielderTyp)
  1581. ti.flag(b1, tiflagMissingFielder).flag(b2, tiflagMissingFielderPtr)
  1582. b1, b2 = implIntf(rt, iszeroTyp)
  1583. ti.flag(b1, tiflagIsZeroer).flag(b2, tiflagIsZeroerPtr)
  1584. b1 = rt.Comparable()
  1585. ti.flag(b1, tiflagComparable)
  1586. switch rk {
  1587. case reflect.Struct:
  1588. var omitEmpty bool
  1589. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  1590. ti.toArray, omitEmpty, ti.keyType = parseStructInfo(x.structTag(f.Tag))
  1591. ti.infoFieldOmitempty = omitEmpty
  1592. } else {
  1593. ti.keyType = valueTypeString
  1594. }
  1595. pp, pi := &pool.tiload, pool.tiload.Get() // pool.tiLoad()
  1596. pv := pi.(*typeInfoLoadArray)
  1597. pv.etypes[0] = ti.rtid
  1598. // vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  1599. vv := typeInfoLoad{pv.etypes[:1], pv.sfis[:0]}
  1600. x.rget(rt, rtid, omitEmpty, nil, &vv)
  1601. // ti.sfis = vv.sfis
  1602. ti.sfiSrc, ti.sfiSort, ti.sfiNamesSort, ti.anyOmitEmpty = rgetResolveSFI(rt, vv.sfis, pv)
  1603. pp.Put(pi)
  1604. case reflect.Map:
  1605. ti.elem = rt.Elem()
  1606. ti.key = rt.Key()
  1607. case reflect.Slice:
  1608. ti.mbs, _ = implIntf(rt, mapBySliceTyp)
  1609. ti.elem = rt.Elem()
  1610. case reflect.Chan:
  1611. ti.elem = rt.Elem()
  1612. ti.chandir = uint8(rt.ChanDir())
  1613. case reflect.Array, reflect.Ptr:
  1614. ti.elem = rt.Elem()
  1615. }
  1616. // sfi = sfiSrc
  1617. x.mu.Lock()
  1618. sp = x.infos.load()
  1619. var sp2 []rtid2ti
  1620. if sp == nil {
  1621. pti = &ti
  1622. sp2 = []rtid2ti{{rtid, pti}}
  1623. x.infos.store(sp2)
  1624. } else {
  1625. var idx uint
  1626. idx, pti = findTypeInfo(sp, rtid)
  1627. if pti == nil {
  1628. pti = &ti
  1629. sp2 = make([]rtid2ti, len(sp)+1)
  1630. copy(sp2, sp[:idx])
  1631. copy(sp2[idx+1:], sp[idx:])
  1632. sp2[idx] = rtid2ti{rtid, pti}
  1633. x.infos.store(sp2)
  1634. }
  1635. }
  1636. x.mu.Unlock()
  1637. return
  1638. }
  1639. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  1640. indexstack []uint16, pv *typeInfoLoad) {
  1641. // Read up fields and store how to access the value.
  1642. //
  1643. // It uses go's rules for message selectors,
  1644. // which say that the field with the shallowest depth is selected.
  1645. //
  1646. // Note: we consciously use slices, not a map, to simulate a set.
  1647. // Typically, types have < 16 fields,
  1648. // and iteration using equals is faster than maps there
  1649. flen := rt.NumField()
  1650. if flen > (1<<maxLevelsEmbedding - 1) {
  1651. panicv.errorf("codec: types with > %v fields are not supported - has %v fields",
  1652. (1<<maxLevelsEmbedding - 1), flen)
  1653. }
  1654. // pv.sfis = make([]structFieldInfo, flen)
  1655. LOOP:
  1656. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  1657. f := rt.Field(int(j))
  1658. fkind := f.Type.Kind()
  1659. // skip if a func type, or is unexported, or structTag value == "-"
  1660. switch fkind {
  1661. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  1662. continue LOOP
  1663. }
  1664. isUnexported := f.PkgPath != ""
  1665. if isUnexported && !f.Anonymous {
  1666. continue
  1667. }
  1668. stag := x.structTag(f.Tag)
  1669. if stag == "-" {
  1670. continue
  1671. }
  1672. var si structFieldInfo
  1673. var parsed bool
  1674. // if anonymous and no struct tag (or it's blank),
  1675. // and a struct (or pointer to struct), inline it.
  1676. if f.Anonymous && fkind != reflect.Interface {
  1677. // ^^ redundant but ok: per go spec, an embedded pointer type cannot be to an interface
  1678. ft := f.Type
  1679. isPtr := ft.Kind() == reflect.Ptr
  1680. for ft.Kind() == reflect.Ptr {
  1681. ft = ft.Elem()
  1682. }
  1683. isStruct := ft.Kind() == reflect.Struct
  1684. // Ignore embedded fields of unexported non-struct types.
  1685. // Also, from go1.10, ignore pointers to unexported struct types
  1686. // because unmarshal cannot assign a new struct to an unexported field.
  1687. // See https://golang.org/issue/21357
  1688. if (isUnexported && !isStruct) || (!allowSetUnexportedEmbeddedPtr && isUnexported && isPtr) {
  1689. continue
  1690. }
  1691. doInline := stag == ""
  1692. if !doInline {
  1693. si.parseTag(stag)
  1694. parsed = true
  1695. doInline = si.encName == ""
  1696. // doInline = si.isZero()
  1697. }
  1698. if doInline && isStruct {
  1699. // if etypes contains this, don't call rget again (as fields are already seen here)
  1700. ftid := rt2id(ft)
  1701. // We cannot recurse forever, but we need to track other field depths.
  1702. // So - we break if we see a type twice (not the first time).
  1703. // This should be sufficient to handle an embedded type that refers to its
  1704. // owning type, which then refers to its embedded type.
  1705. processIt := true
  1706. numk := 0
  1707. for _, k := range pv.etypes {
  1708. if k == ftid {
  1709. numk++
  1710. if numk == rgetMaxRecursion {
  1711. processIt = false
  1712. break
  1713. }
  1714. }
  1715. }
  1716. if processIt {
  1717. pv.etypes = append(pv.etypes, ftid)
  1718. indexstack2 := make([]uint16, len(indexstack)+1)
  1719. copy(indexstack2, indexstack)
  1720. indexstack2[len(indexstack)] = j
  1721. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  1722. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  1723. }
  1724. continue
  1725. }
  1726. }
  1727. // after the anonymous dance: if an unexported field, skip
  1728. if isUnexported {
  1729. continue
  1730. }
  1731. if f.Name == "" {
  1732. panic(errNoFieldNameToStructFieldInfo)
  1733. }
  1734. // pv.fNames = append(pv.fNames, f.Name)
  1735. // if si.encName == "" {
  1736. if !parsed {
  1737. si.encName = f.Name
  1738. si.parseTag(stag)
  1739. parsed = true
  1740. } else if si.encName == "" {
  1741. si.encName = f.Name
  1742. }
  1743. si.encNameAsciiAlphaNum = true
  1744. for i := len(si.encName) - 1; i >= 0; i-- { // bounds-check elimination
  1745. b := si.encName[i]
  1746. if (b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') {
  1747. continue
  1748. }
  1749. si.encNameAsciiAlphaNum = false
  1750. break
  1751. }
  1752. si.fieldName = f.Name
  1753. si.flagSet(structFieldInfoFlagReady)
  1754. // pv.encNames = append(pv.encNames, si.encName)
  1755. // si.ikind = int(f.Type.Kind())
  1756. if len(indexstack) > maxLevelsEmbedding-1 {
  1757. panicv.errorf("codec: only supports up to %v depth of embedding - type has %v depth",
  1758. maxLevelsEmbedding-1, len(indexstack))
  1759. }
  1760. si.nis = uint8(len(indexstack)) + 1
  1761. copy(si.is[:], indexstack)
  1762. si.is[len(indexstack)] = j
  1763. if omitEmpty {
  1764. si.flagSet(structFieldInfoFlagOmitEmpty)
  1765. }
  1766. pv.sfis = append(pv.sfis, si)
  1767. }
  1768. }
  1769. func tiSep(name string) uint8 {
  1770. // (xn[0]%64) // (between 192-255 - outside ascii BMP)
  1771. // return 0xfe - (name[0] & 63)
  1772. // return 0xfe - (name[0] & 63) - uint8(len(name))
  1773. // return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1774. // return ((0xfe - (name[0] & 63)) & 0xf8) | (uint8(len(name) & 0x07))
  1775. return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1776. }
  1777. func tiSep2(name []byte) uint8 {
  1778. return 0xfe - (name[0] & 63) - uint8(len(name)&63)
  1779. }
  1780. // resolves the struct field info got from a call to rget.
  1781. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  1782. func rgetResolveSFI(rt reflect.Type, x []structFieldInfo, pv *typeInfoLoadArray) (
  1783. y, z []*structFieldInfo, ss []byte, anyOmitEmpty bool) {
  1784. sa := pv.sfiidx[:0]
  1785. sn := pv.b[:]
  1786. n := len(x)
  1787. var xn string
  1788. var ui uint16
  1789. var sep byte
  1790. for i := range x {
  1791. ui = uint16(i)
  1792. xn = x[i].encName // fieldName or encName? use encName for now.
  1793. if len(xn)+2 > cap(sn) {
  1794. sn = make([]byte, len(xn)+2)
  1795. } else {
  1796. sn = sn[:len(xn)+2]
  1797. }
  1798. // use a custom sep, so that misses are less frequent,
  1799. // since the sep (first char in search) is as unique as first char in field name.
  1800. sep = tiSep(xn)
  1801. sn[0], sn[len(sn)-1] = sep, 0xff
  1802. copy(sn[1:], xn)
  1803. j := bytes.Index(sa, sn)
  1804. if j == -1 {
  1805. sa = append(sa, sep)
  1806. sa = append(sa, xn...)
  1807. sa = append(sa, 0xff, byte(ui>>8), byte(ui))
  1808. } else {
  1809. index := uint16(sa[j+len(sn)+1]) | uint16(sa[j+len(sn)])<<8
  1810. // one of them must be cleared (reset to nil),
  1811. // and the index updated appropriately
  1812. i2clear := ui // index to be cleared
  1813. if x[i].nis < x[index].nis { // this one is shallower
  1814. // update the index to point to this later one.
  1815. sa[j+len(sn)], sa[j+len(sn)+1] = byte(ui>>8), byte(ui)
  1816. // clear the earlier one, as this later one is shallower.
  1817. i2clear = index
  1818. }
  1819. if x[i2clear].ready() {
  1820. x[i2clear].flagClr(structFieldInfoFlagReady)
  1821. n--
  1822. }
  1823. }
  1824. }
  1825. var w []structFieldInfo
  1826. sharingArray := len(x) <= typeInfoLoadArraySfisLen // sharing array with typeInfoLoadArray
  1827. if sharingArray {
  1828. w = make([]structFieldInfo, n)
  1829. }
  1830. // remove all the nils (non-ready)
  1831. y = make([]*structFieldInfo, n)
  1832. n = 0
  1833. var sslen int
  1834. for i := range x {
  1835. if !x[i].ready() {
  1836. continue
  1837. }
  1838. if !anyOmitEmpty && x[i].omitEmpty() {
  1839. anyOmitEmpty = true
  1840. }
  1841. if sharingArray {
  1842. w[n] = x[i]
  1843. y[n] = &w[n]
  1844. } else {
  1845. y[n] = &x[i]
  1846. }
  1847. sslen = sslen + len(x[i].encName) + 4
  1848. n++
  1849. }
  1850. if n != len(y) {
  1851. panicv.errorf("failure reading struct %v - expecting %d of %d valid fields, got %d",
  1852. rt, len(y), len(x), n)
  1853. }
  1854. z = make([]*structFieldInfo, len(y))
  1855. copy(z, y)
  1856. sort.Sort(sfiSortedByEncName(z))
  1857. sharingArray = len(sa) <= typeInfoLoadArraySfiidxLen
  1858. if sharingArray {
  1859. ss = make([]byte, 0, sslen)
  1860. } else {
  1861. ss = sa[:0] // reuse the newly made sa array if necessary
  1862. }
  1863. for i := range z {
  1864. xn = z[i].encName
  1865. sep = tiSep(xn)
  1866. ui = uint16(i)
  1867. ss = append(ss, sep)
  1868. ss = append(ss, xn...)
  1869. ss = append(ss, 0xff, byte(ui>>8), byte(ui))
  1870. }
  1871. return
  1872. }
  1873. func implIntf(rt, iTyp reflect.Type) (base bool, indir bool) {
  1874. return rt.Implements(iTyp), reflect.PtrTo(rt).Implements(iTyp)
  1875. }
  1876. // isEmptyStruct is only called from isEmptyValue, and checks if a struct is empty:
  1877. // - does it implement IsZero() bool
  1878. // - is it comparable, and can i compare directly using ==
  1879. // - if checkStruct, then walk through the encodable fields
  1880. // and check if they are empty or not.
  1881. func isEmptyStruct(v reflect.Value, tinfos *TypeInfos, deref, checkStruct bool) bool {
  1882. // v is a struct kind - no need to check again.
  1883. // We only check isZero on a struct kind, to reduce the amount of times
  1884. // that we lookup the rtid and typeInfo for each type as we walk the tree.
  1885. vt := v.Type()
  1886. rtid := rt2id(vt)
  1887. if tinfos == nil {
  1888. tinfos = defTypeInfos
  1889. }
  1890. ti := tinfos.get(rtid, vt)
  1891. if ti.rtid == timeTypId {
  1892. return rv2i(v).(time.Time).IsZero()
  1893. }
  1894. if ti.isFlag(tiflagIsZeroerPtr) && v.CanAddr() {
  1895. return rv2i(v.Addr()).(isZeroer).IsZero()
  1896. }
  1897. if ti.isFlag(tiflagIsZeroer) {
  1898. return rv2i(v).(isZeroer).IsZero()
  1899. }
  1900. if ti.isFlag(tiflagComparable) {
  1901. return rv2i(v) == rv2i(reflect.Zero(vt))
  1902. }
  1903. if !checkStruct {
  1904. return false
  1905. }
  1906. // We only care about what we can encode/decode,
  1907. // so that is what we use to check omitEmpty.
  1908. for _, si := range ti.sfiSrc {
  1909. sfv, valid := si.field(v, false)
  1910. if valid && !isEmptyValue(sfv, tinfos, deref, checkStruct) {
  1911. return false
  1912. }
  1913. }
  1914. return true
  1915. }
  1916. // func roundFloat(x float64) float64 {
  1917. // t := math.Trunc(x)
  1918. // if math.Abs(x-t) >= 0.5 {
  1919. // return t + math.Copysign(1, x)
  1920. // }
  1921. // return t
  1922. // }
  1923. func panicToErr(h errDecorator, err *error) {
  1924. // Note: This method MUST be called directly from defer i.e. defer panicToErr ...
  1925. // else it seems the recover is not fully handled
  1926. if recoverPanicToErr {
  1927. if x := recover(); x != nil {
  1928. // fmt.Printf("panic'ing with: %v\n", x)
  1929. // debug.PrintStack()
  1930. panicValToErr(h, x, err)
  1931. }
  1932. }
  1933. }
  1934. func panicValToErr(h errDecorator, v interface{}, err *error) {
  1935. switch xerr := v.(type) {
  1936. case nil:
  1937. case error:
  1938. switch xerr {
  1939. case nil:
  1940. case io.EOF, io.ErrUnexpectedEOF, errEncoderNotInitialized, errDecoderNotInitialized:
  1941. // treat as special (bubble up)
  1942. *err = xerr
  1943. default:
  1944. h.wrapErr(xerr, err)
  1945. }
  1946. case string:
  1947. if xerr != "" {
  1948. h.wrapErr(xerr, err)
  1949. }
  1950. case fmt.Stringer:
  1951. if xerr != nil {
  1952. h.wrapErr(xerr, err)
  1953. }
  1954. default:
  1955. h.wrapErr(v, err)
  1956. }
  1957. }
  1958. func isImmutableKind(k reflect.Kind) (v bool) {
  1959. // return immutableKindsSet[k]
  1960. // since we know reflect.Kind is in range 0..31, then use the k%32 == k constraint
  1961. return immutableKindsSet[k%reflect.Kind(len(immutableKindsSet))] // bounds-check-elimination
  1962. }
  1963. func usableByteSlice(bs []byte, slen int) []byte {
  1964. if cap(bs) >= slen {
  1965. if bs == nil {
  1966. return []byte{}
  1967. }
  1968. return bs[:slen]
  1969. }
  1970. return make([]byte, slen)
  1971. }
  1972. // ----
  1973. type codecFnInfo struct {
  1974. ti *typeInfo
  1975. xfFn Ext
  1976. xfTag uint64
  1977. seq seqType
  1978. addrD bool
  1979. addrF bool // if addrD, this says whether decode function can take a value or a ptr
  1980. addrE bool
  1981. }
  1982. // codecFn encapsulates the captured variables and the encode function.
  1983. // This way, we only do some calculations one times, and pass to the
  1984. // code block that should be called (encapsulated in a function)
  1985. // instead of executing the checks every time.
  1986. type codecFn struct {
  1987. i codecFnInfo
  1988. fe func(*Encoder, *codecFnInfo, reflect.Value)
  1989. fd func(*Decoder, *codecFnInfo, reflect.Value)
  1990. _ [1]uint64 // padding (cache-aligned)
  1991. }
  1992. type codecRtidFn struct {
  1993. rtid uintptr
  1994. fn *codecFn
  1995. }
  1996. func makeExt(ext interface{}) Ext {
  1997. if ext == nil {
  1998. return &extFailWrapper{}
  1999. }
  2000. switch t := ext.(type) {
  2001. case nil:
  2002. return &extFailWrapper{}
  2003. case Ext:
  2004. return t
  2005. case BytesExt:
  2006. return &bytesExtWrapper{BytesExt: t}
  2007. case InterfaceExt:
  2008. return &interfaceExtWrapper{InterfaceExt: t}
  2009. }
  2010. return &extFailWrapper{}
  2011. }
  2012. func baseRV(v interface{}) (rv reflect.Value) {
  2013. for rv = reflect.ValueOf(v); rv.Kind() == reflect.Ptr; rv = rv.Elem() {
  2014. }
  2015. return
  2016. }
  2017. // func newAddressableRV(t reflect.Type, k reflect.Kind) reflect.Value {
  2018. // if k == reflect.Ptr {
  2019. // return reflect.New(t.Elem()) // this is not addressable???
  2020. // }
  2021. // return reflect.New(t).Elem()
  2022. // }
  2023. // func newAddressableRV(t reflect.Type) reflect.Value {
  2024. // return reflect.New(t).Elem()
  2025. // }
  2026. // ----
  2027. // these "checkOverflow" functions must be inlinable, and not call anybody.
  2028. // Overflow means that the value cannot be represented without wrapping/overflow.
  2029. // Overflow=false does not mean that the value can be represented without losing precision
  2030. // (especially for floating point).
  2031. type checkOverflow struct{}
  2032. // func (checkOverflow) Float16(f float64) (overflow bool) {
  2033. // panicv.errorf("unimplemented")
  2034. // if f < 0 {
  2035. // f = -f
  2036. // }
  2037. // return math.MaxFloat32 < f && f <= math.MaxFloat64
  2038. // }
  2039. func (checkOverflow) Float32(v float64) (overflow bool) {
  2040. if v < 0 {
  2041. v = -v
  2042. }
  2043. return math.MaxFloat32 < v && v <= math.MaxFloat64
  2044. }
  2045. func (checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  2046. if bitsize == 0 || bitsize >= 64 || v == 0 {
  2047. return
  2048. }
  2049. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  2050. overflow = true
  2051. }
  2052. return
  2053. }
  2054. func (checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  2055. if bitsize == 0 || bitsize >= 64 || v == 0 {
  2056. return
  2057. }
  2058. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  2059. overflow = true
  2060. }
  2061. return
  2062. }
  2063. func (checkOverflow) SignedInt(v uint64) (overflow bool) {
  2064. //e.g. -127 to 128 for int8
  2065. pos := (v >> 63) == 0
  2066. ui2 := v & 0x7fffffffffffffff
  2067. if pos {
  2068. if ui2 > math.MaxInt64 {
  2069. overflow = true
  2070. }
  2071. } else {
  2072. if ui2 > math.MaxInt64-1 {
  2073. overflow = true
  2074. }
  2075. }
  2076. return
  2077. }
  2078. func (x checkOverflow) Float32V(v float64) float64 {
  2079. if x.Float32(v) {
  2080. panicv.errorf("float32 overflow: %v", v)
  2081. }
  2082. return v
  2083. }
  2084. func (x checkOverflow) UintV(v uint64, bitsize uint8) uint64 {
  2085. if x.Uint(v, bitsize) {
  2086. panicv.errorf("uint64 overflow: %v", v)
  2087. }
  2088. return v
  2089. }
  2090. func (x checkOverflow) IntV(v int64, bitsize uint8) int64 {
  2091. if x.Int(v, bitsize) {
  2092. panicv.errorf("int64 overflow: %v", v)
  2093. }
  2094. return v
  2095. }
  2096. func (x checkOverflow) SignedIntV(v uint64) int64 {
  2097. if x.SignedInt(v) {
  2098. panicv.errorf("uint64 to int64 overflow: %v", v)
  2099. }
  2100. return int64(v)
  2101. }
  2102. // ------------------ FLOATING POINT -----------------
  2103. func isNaN64(f float64) bool { return f != f }
  2104. func isNaN32(f float32) bool { return f != f }
  2105. func abs32(f float32) float32 {
  2106. return math.Float32frombits(math.Float32bits(f) &^ (1 << 31))
  2107. }
  2108. // Per go spec, floats are represented in memory as
  2109. // IEEE single or double precision floating point values.
  2110. //
  2111. // We also looked at the source for stdlib math/modf.go,
  2112. // reviewed https://github.com/chewxy/math32
  2113. // and read wikipedia documents describing the formats.
  2114. //
  2115. // It became clear that we could easily look at the bits to determine
  2116. // whether any fraction exists.
  2117. //
  2118. // This is all we need for now.
  2119. func noFrac64(f float64) (v bool) {
  2120. x := math.Float64bits(f)
  2121. e := uint64(x>>52)&0x7FF - 1023 // uint(x>>shift)&mask - bias
  2122. // clear top 12+e bits, the integer part; if the rest is 0, then no fraction.
  2123. if e < 52 {
  2124. // return x&((1<<64-1)>>(12+e)) == 0
  2125. return x<<(12+e) == 0
  2126. }
  2127. return
  2128. }
  2129. func noFrac32(f float32) (v bool) {
  2130. x := math.Float32bits(f)
  2131. e := uint32(x>>23)&0xFF - 127 // uint(x>>shift)&mask - bias
  2132. // clear top 9+e bits, the integer part; if the rest is 0, then no fraction.
  2133. if e < 23 {
  2134. // return x&((1<<32-1)>>(9+e)) == 0
  2135. return x<<(9+e) == 0
  2136. }
  2137. return
  2138. }
  2139. // func noFrac(f float64) bool {
  2140. // _, frac := math.Modf(float64(f))
  2141. // return frac == 0
  2142. // }
  2143. // -----------------------
  2144. type ioFlusher interface {
  2145. Flush() error
  2146. }
  2147. type ioPeeker interface {
  2148. Peek(int) ([]byte, error)
  2149. }
  2150. type ioBuffered interface {
  2151. Buffered() int
  2152. }
  2153. // -----------------------
  2154. type sfiRv struct {
  2155. v *structFieldInfo
  2156. r reflect.Value
  2157. }
  2158. // -----------------
  2159. type set []interface{}
  2160. func (s *set) add(v interface{}) (exists bool) {
  2161. // e.ci is always nil, or len >= 1
  2162. x := *s
  2163. if x == nil {
  2164. x = make([]interface{}, 1, 8)
  2165. x[0] = v
  2166. *s = x
  2167. return
  2168. }
  2169. // typically, length will be 1. make this perform.
  2170. if len(x) == 1 {
  2171. if j := x[0]; j == 0 {
  2172. x[0] = v
  2173. } else if j == v {
  2174. exists = true
  2175. } else {
  2176. x = append(x, v)
  2177. *s = x
  2178. }
  2179. return
  2180. }
  2181. // check if it exists
  2182. for _, j := range x {
  2183. if j == v {
  2184. exists = true
  2185. return
  2186. }
  2187. }
  2188. // try to replace a "deleted" slot
  2189. for i, j := range x {
  2190. if j == 0 {
  2191. x[i] = v
  2192. return
  2193. }
  2194. }
  2195. // if unable to replace deleted slot, just append it.
  2196. x = append(x, v)
  2197. *s = x
  2198. return
  2199. }
  2200. func (s *set) remove(v interface{}) (exists bool) {
  2201. x := *s
  2202. if len(x) == 0 {
  2203. return
  2204. }
  2205. if len(x) == 1 {
  2206. if x[0] == v {
  2207. x[0] = 0
  2208. }
  2209. return
  2210. }
  2211. for i, j := range x {
  2212. if j == v {
  2213. exists = true
  2214. x[i] = 0 // set it to 0, as way to delete it.
  2215. // copy(x[i:], x[i+1:])
  2216. // x = x[:len(x)-1]
  2217. return
  2218. }
  2219. }
  2220. return
  2221. }
  2222. // ------
  2223. // bitset types are better than [256]bool, because they permit the whole
  2224. // bitset array being on a single cache line and use less memory.
  2225. //
  2226. // Also, since pos is a byte (0-255), there's no bounds checks on indexing (cheap).
  2227. //
  2228. // We previously had bitset128 [16]byte, and bitset32 [4]byte, but those introduces
  2229. // bounds checking, so we discarded them, and everyone uses bitset256.
  2230. //
  2231. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  2232. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  2233. type bitset256 [32]byte
  2234. func (x *bitset256) isset(pos byte) bool {
  2235. return x[pos>>3]&(1<<(pos&7)) != 0
  2236. }
  2237. // func (x *bitset256) issetv(pos byte) byte {
  2238. // return x[pos>>3] & (1 << (pos & 7))
  2239. // }
  2240. func (x *bitset256) set(pos byte) {
  2241. x[pos>>3] |= (1 << (pos & 7))
  2242. }
  2243. type bitset32 uint32
  2244. func (x bitset32) set(pos byte) bitset32 {
  2245. return x | (1 << pos)
  2246. }
  2247. func (x bitset32) isset(pos byte) bool {
  2248. return x&(1<<pos) != 0
  2249. }
  2250. // func (x *bitset256) unset(pos byte) {
  2251. // x[pos>>3] &^= (1 << (pos & 7))
  2252. // }
  2253. // type bit2set256 [64]byte
  2254. // func (x *bit2set256) set(pos byte, v1, v2 bool) {
  2255. // var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6
  2256. // if v1 {
  2257. // x[pos>>2] |= 1 << (pos2 + 1)
  2258. // }
  2259. // if v2 {
  2260. // x[pos>>2] |= 1 << pos2
  2261. // }
  2262. // }
  2263. // func (x *bit2set256) get(pos byte) uint8 {
  2264. // var pos2 uint8 = (pos & 3) << 1 // returning 0, 2, 4 or 6
  2265. // return x[pos>>2] << (6 - pos2) >> 6 // 11000000 -> 00000011
  2266. // }
  2267. // ------------
  2268. // type strBytes struct {
  2269. // s string
  2270. // b []byte
  2271. // // i uint16
  2272. // }
  2273. // ------------
  2274. type pooler struct {
  2275. // function-scoped pooled resources
  2276. tiload sync.Pool // for type info loading
  2277. sfiRv8, sfiRv16, sfiRv32, sfiRv64, sfiRv128 sync.Pool // for struct encoding
  2278. // lifetime-scoped pooled resources
  2279. // dn sync.Pool // for decNaked
  2280. buf1k, buf2k, buf4k, buf8k, buf16k, buf32k, buf64k sync.Pool // for [N]byte
  2281. mapStrU16, mapU16Str, mapU16Bytes sync.Pool // for Binc
  2282. // mapU16StrBytes sync.Pool // for Binc
  2283. }
  2284. func (p *pooler) init() {
  2285. p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
  2286. p.sfiRv8.New = func() interface{} { return new([8]sfiRv) }
  2287. p.sfiRv16.New = func() interface{} { return new([16]sfiRv) }
  2288. p.sfiRv32.New = func() interface{} { return new([32]sfiRv) }
  2289. p.sfiRv64.New = func() interface{} { return new([64]sfiRv) }
  2290. p.sfiRv128.New = func() interface{} { return new([128]sfiRv) }
  2291. // p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
  2292. p.buf1k.New = func() interface{} { return new([1 * 1024]byte) }
  2293. p.buf2k.New = func() interface{} { return new([2 * 1024]byte) }
  2294. p.buf4k.New = func() interface{} { return new([4 * 1024]byte) }
  2295. p.buf8k.New = func() interface{} { return new([8 * 1024]byte) }
  2296. p.buf16k.New = func() interface{} { return new([16 * 1024]byte) }
  2297. p.buf32k.New = func() interface{} { return new([32 * 1024]byte) }
  2298. p.buf64k.New = func() interface{} { return new([64 * 1024]byte) }
  2299. p.mapStrU16.New = func() interface{} { return make(map[string]uint16, 16) }
  2300. p.mapU16Str.New = func() interface{} { return make(map[uint16]string, 16) }
  2301. p.mapU16Bytes.New = func() interface{} { return make(map[uint16][]byte, 16) }
  2302. // p.mapU16StrBytes.New = func() interface{} { return make(map[uint16]strBytes, 16) }
  2303. }
  2304. // func (p *pooler) sfiRv8() (sp *sync.Pool, v interface{}) {
  2305. // return &p.strRv8, p.strRv8.Get()
  2306. // }
  2307. // func (p *pooler) sfiRv16() (sp *sync.Pool, v interface{}) {
  2308. // return &p.strRv16, p.strRv16.Get()
  2309. // }
  2310. // func (p *pooler) sfiRv32() (sp *sync.Pool, v interface{}) {
  2311. // return &p.strRv32, p.strRv32.Get()
  2312. // }
  2313. // func (p *pooler) sfiRv64() (sp *sync.Pool, v interface{}) {
  2314. // return &p.strRv64, p.strRv64.Get()
  2315. // }
  2316. // func (p *pooler) sfiRv128() (sp *sync.Pool, v interface{}) {
  2317. // return &p.strRv128, p.strRv128.Get()
  2318. // }
  2319. // func (p *pooler) bytes1k() (sp *sync.Pool, v interface{}) {
  2320. // return &p.buf1k, p.buf1k.Get()
  2321. // }
  2322. // func (p *pooler) bytes2k() (sp *sync.Pool, v interface{}) {
  2323. // return &p.buf2k, p.buf2k.Get()
  2324. // }
  2325. // func (p *pooler) bytes4k() (sp *sync.Pool, v interface{}) {
  2326. // return &p.buf4k, p.buf4k.Get()
  2327. // }
  2328. // func (p *pooler) bytes8k() (sp *sync.Pool, v interface{}) {
  2329. // return &p.buf8k, p.buf8k.Get()
  2330. // }
  2331. // func (p *pooler) bytes16k() (sp *sync.Pool, v interface{}) {
  2332. // return &p.buf16k, p.buf16k.Get()
  2333. // }
  2334. // func (p *pooler) bytes32k() (sp *sync.Pool, v interface{}) {
  2335. // return &p.buf32k, p.buf32k.Get()
  2336. // }
  2337. // func (p *pooler) bytes64k() (sp *sync.Pool, v interface{}) {
  2338. // return &p.buf64k, p.buf64k.Get()
  2339. // }
  2340. // func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
  2341. // return &p.tiload, p.tiload.Get()
  2342. // }
  2343. // func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
  2344. // return &p.dn, p.dn.Get()
  2345. // }
  2346. // func (p *pooler) decNaked() (v *decNaked, f func(*decNaked) ) {
  2347. // sp := &(p.dn)
  2348. // vv := sp.Get()
  2349. // return vv.(*decNaked), func(x *decNaked) { sp.Put(vv) }
  2350. // }
  2351. // func (p *pooler) decNakedGet() (v interface{}) {
  2352. // return p.dn.Get()
  2353. // }
  2354. // func (p *pooler) tiLoadGet() (v interface{}) {
  2355. // return p.tiload.Get()
  2356. // }
  2357. // func (p *pooler) decNakedPut(v interface{}) {
  2358. // p.dn.Put(v)
  2359. // }
  2360. // func (p *pooler) tiLoadPut(v interface{}) {
  2361. // p.tiload.Put(v)
  2362. // }
  2363. // ----------------------------------------------------
  2364. type panicHdl struct{}
  2365. func (panicHdl) errorv(err error) {
  2366. if err != nil {
  2367. panic(err)
  2368. }
  2369. }
  2370. func (panicHdl) errorstr(message string) {
  2371. if message != "" {
  2372. panic(message)
  2373. }
  2374. }
  2375. func (panicHdl) errorf(format string, params ...interface{}) {
  2376. if len(params) != 0 {
  2377. panic(fmt.Sprintf(format, params...))
  2378. }
  2379. if len(params) == 0 {
  2380. panic(format)
  2381. }
  2382. panic("undefined error")
  2383. }
  2384. // ----------------------------------------------------
  2385. type errDecorator interface {
  2386. wrapErr(in interface{}, out *error)
  2387. }
  2388. type errDecoratorDef struct{}
  2389. func (errDecoratorDef) wrapErr(v interface{}, e *error) { *e = fmt.Errorf("%v", v) }
  2390. // ----------------------------------------------------
  2391. type must struct{}
  2392. func (must) String(s string, err error) string {
  2393. if err != nil {
  2394. panicv.errorv(err)
  2395. }
  2396. return s
  2397. }
  2398. func (must) Int(s int64, err error) int64 {
  2399. if err != nil {
  2400. panicv.errorv(err)
  2401. }
  2402. return s
  2403. }
  2404. func (must) Uint(s uint64, err error) uint64 {
  2405. if err != nil {
  2406. panicv.errorv(err)
  2407. }
  2408. return s
  2409. }
  2410. func (must) Float(s float64, err error) float64 {
  2411. if err != nil {
  2412. panicv.errorv(err)
  2413. }
  2414. return s
  2415. }
  2416. // -------------------
  2417. type bytesBufPooler struct {
  2418. pool *sync.Pool
  2419. poolbuf interface{}
  2420. }
  2421. func (z *bytesBufPooler) end() {
  2422. if z.pool != nil {
  2423. z.pool.Put(z.poolbuf)
  2424. z.pool, z.poolbuf = nil, nil
  2425. }
  2426. }
  2427. func (z *bytesBufPooler) get(bufsize int) (buf []byte) {
  2428. // ensure an end is called first (if necessary)
  2429. if z.pool != nil {
  2430. z.pool.Put(z.poolbuf)
  2431. z.pool, z.poolbuf = nil, nil
  2432. }
  2433. // // Try to use binary search.
  2434. // // This is not optimal, as most folks select 1k or 2k buffers
  2435. // // so a linear search is better (sequence of if/else blocks)
  2436. // if bufsize < 1 {
  2437. // bufsize = 0
  2438. // } else {
  2439. // bufsize--
  2440. // bufsize /= 1024
  2441. // }
  2442. // switch bufsize {
  2443. // case 0:
  2444. // z.pool, z.poolbuf = pool.bytes1k()
  2445. // buf = z.poolbuf.(*[1 * 1024]byte)[:]
  2446. // case 1:
  2447. // z.pool, z.poolbuf = pool.bytes2k()
  2448. // buf = z.poolbuf.(*[2 * 1024]byte)[:]
  2449. // case 2, 3:
  2450. // z.pool, z.poolbuf = pool.bytes4k()
  2451. // buf = z.poolbuf.(*[4 * 1024]byte)[:]
  2452. // case 4, 5, 6, 7:
  2453. // z.pool, z.poolbuf = pool.bytes8k()
  2454. // buf = z.poolbuf.(*[8 * 1024]byte)[:]
  2455. // case 8, 9, 10, 11, 12, 13, 14, 15:
  2456. // z.pool, z.poolbuf = pool.bytes16k()
  2457. // buf = z.poolbuf.(*[16 * 1024]byte)[:]
  2458. // case 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31:
  2459. // z.pool, z.poolbuf = pool.bytes32k()
  2460. // buf = z.poolbuf.(*[32 * 1024]byte)[:]
  2461. // default:
  2462. // z.pool, z.poolbuf = pool.bytes64k()
  2463. // buf = z.poolbuf.(*[64 * 1024]byte)[:]
  2464. // }
  2465. // return
  2466. if bufsize <= 1*1024 {
  2467. z.pool, z.poolbuf = &pool.buf1k, pool.buf1k.Get() // pool.bytes1k()
  2468. buf = z.poolbuf.(*[1 * 1024]byte)[:]
  2469. } else if bufsize <= 2*1024 {
  2470. z.pool, z.poolbuf = &pool.buf2k, pool.buf2k.Get() // pool.bytes2k()
  2471. buf = z.poolbuf.(*[2 * 1024]byte)[:]
  2472. } else if bufsize <= 4*1024 {
  2473. z.pool, z.poolbuf = &pool.buf4k, pool.buf4k.Get() // pool.bytes4k()
  2474. buf = z.poolbuf.(*[4 * 1024]byte)[:]
  2475. } else if bufsize <= 8*1024 {
  2476. z.pool, z.poolbuf = &pool.buf8k, pool.buf8k.Get() // pool.bytes8k()
  2477. buf = z.poolbuf.(*[8 * 1024]byte)[:]
  2478. } else if bufsize <= 16*1024 {
  2479. z.pool, z.poolbuf = &pool.buf16k, pool.buf16k.Get() // pool.bytes16k()
  2480. buf = z.poolbuf.(*[16 * 1024]byte)[:]
  2481. } else if bufsize <= 32*1024 {
  2482. z.pool, z.poolbuf = &pool.buf32k, pool.buf32k.Get() // pool.bytes32k()
  2483. buf = z.poolbuf.(*[32 * 1024]byte)[:]
  2484. } else {
  2485. z.pool, z.poolbuf = &pool.buf64k, pool.buf64k.Get() // pool.bytes64k()
  2486. buf = z.poolbuf.(*[64 * 1024]byte)[:]
  2487. }
  2488. return
  2489. }
  2490. // ----------------
  2491. type sfiRvPooler struct {
  2492. pool *sync.Pool
  2493. poolv interface{}
  2494. }
  2495. func (z *sfiRvPooler) end() {
  2496. if z.pool != nil {
  2497. z.pool.Put(z.poolv)
  2498. z.pool, z.poolv = nil, nil
  2499. }
  2500. }
  2501. func (z *sfiRvPooler) get(newlen int) (fkvs []sfiRv) {
  2502. if newlen < 0 { // bounds-check-elimination
  2503. // cannot happen // here for bounds-check-elimination
  2504. } else if newlen <= 8 {
  2505. z.pool, z.poolv = &pool.sfiRv8, pool.sfiRv8.Get() // pool.sfiRv8()
  2506. fkvs = z.poolv.(*[8]sfiRv)[:newlen]
  2507. } else if newlen <= 16 {
  2508. z.pool, z.poolv = &pool.sfiRv16, pool.sfiRv16.Get() // pool.sfiRv16()
  2509. fkvs = z.poolv.(*[16]sfiRv)[:newlen]
  2510. } else if newlen <= 32 {
  2511. z.pool, z.poolv = &pool.sfiRv32, pool.sfiRv32.Get() // pool.sfiRv32()
  2512. fkvs = z.poolv.(*[32]sfiRv)[:newlen]
  2513. } else if newlen <= 64 {
  2514. z.pool, z.poolv = &pool.sfiRv64, pool.sfiRv64.Get() // pool.sfiRv64()
  2515. fkvs = z.poolv.(*[64]sfiRv)[:newlen]
  2516. } else if newlen <= 128 {
  2517. z.pool, z.poolv = &pool.sfiRv128, pool.sfiRv128.Get() // pool.sfiRv128()
  2518. fkvs = z.poolv.(*[128]sfiRv)[:newlen]
  2519. } else {
  2520. fkvs = make([]sfiRv, newlen)
  2521. }
  2522. return
  2523. }
  2524. // xdebugf printf. the message in red on the terminal.
  2525. // Use it in place of fmt.Printf (which it calls internally)
  2526. func xdebugf(pattern string, args ...interface{}) {
  2527. xdebugAnyf("31", pattern, args...)
  2528. }
  2529. // xdebug2f printf. the message in blue on the terminal.
  2530. // Use it in place of fmt.Printf (which it calls internally)
  2531. func xdebug2f(pattern string, args ...interface{}) {
  2532. xdebugAnyf("34", pattern, args...)
  2533. }
  2534. func xdebugAnyf(colorcode, pattern string, args ...interface{}) {
  2535. if !xdebug {
  2536. return
  2537. }
  2538. var delim string
  2539. if len(pattern) > 0 && pattern[len(pattern)-1] != '\n' {
  2540. delim = "\n"
  2541. }
  2542. fmt.Printf("\033[1;"+colorcode+"m"+pattern+delim+"\033[0m", args...)
  2543. // os.Stderr.Flush()
  2544. }
  2545. // register these here, so that staticcheck stops barfing
  2546. var _ = xdebug2f
  2547. var _ = xdebugf
  2548. var _ = isNaN32
  2549. // func isImmutableKind(k reflect.Kind) (v bool) {
  2550. // return false ||
  2551. // k == reflect.Int ||
  2552. // k == reflect.Int8 ||
  2553. // k == reflect.Int16 ||
  2554. // k == reflect.Int32 ||
  2555. // k == reflect.Int64 ||
  2556. // k == reflect.Uint ||
  2557. // k == reflect.Uint8 ||
  2558. // k == reflect.Uint16 ||
  2559. // k == reflect.Uint32 ||
  2560. // k == reflect.Uint64 ||
  2561. // k == reflect.Uintptr ||
  2562. // k == reflect.Float32 ||
  2563. // k == reflect.Float64 ||
  2564. // k == reflect.Bool ||
  2565. // k == reflect.String
  2566. // }
  2567. // func timeLocUTCName(tzint int16) string {
  2568. // if tzint == 0 {
  2569. // return "UTC"
  2570. // }
  2571. // var tzname = []byte("UTC+00:00")
  2572. // //tzname := fmt.Sprintf("UTC%s%02d:%02d", tzsign, tz/60, tz%60) //perf issue using Sprintf.. inline below.
  2573. // //tzhr, tzmin := tz/60, tz%60 //faster if u convert to int first
  2574. // var tzhr, tzmin int16
  2575. // if tzint < 0 {
  2576. // tzname[3] = '-' // (TODO: verify. this works here)
  2577. // tzhr, tzmin = -tzint/60, (-tzint)%60
  2578. // } else {
  2579. // tzhr, tzmin = tzint/60, tzint%60
  2580. // }
  2581. // tzname[4] = timeDigits[tzhr/10]
  2582. // tzname[5] = timeDigits[tzhr%10]
  2583. // tzname[7] = timeDigits[tzmin/10]
  2584. // tzname[8] = timeDigits[tzmin%10]
  2585. // return string(tzname)
  2586. // //return time.FixedZone(string(tzname), int(tzint)*60)
  2587. // }