helper.go 80 KB

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