helper.go 79 KB

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