helper.go 73 KB

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