另客网go项目公用的代码库

helper.go 75KB

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