helper.go 76 KB

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