helper.go 65 KB

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