helper.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  1. // Copyright (c) 2012-2015 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. "math"
  102. "os"
  103. "reflect"
  104. "sort"
  105. "strconv"
  106. "strings"
  107. "sync"
  108. "time"
  109. )
  110. const (
  111. scratchByteArrayLen = 32
  112. // initCollectionCap = 16 // 32 is defensive. 16 is preferred.
  113. // Support encoding.(Binary|Text)(Unm|M)arshaler.
  114. // This constant flag will enable or disable it.
  115. supportMarshalInterfaces = true
  116. // for debugging, set this to false, to catch panic traces.
  117. // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
  118. recoverPanicToErr = true
  119. // arrayCacheLen is the length of the cache used in encoder or decoder for
  120. // allowing zero-alloc initialization.
  121. arrayCacheLen = 8
  122. // We tried an optimization, where we detect if a type is one of the known types
  123. // we optimized for (e.g. int, []uint64, etc).
  124. //
  125. // However, we notice some worse performance when using this optimization.
  126. // So we hide it behind a flag, to turn on if needed.
  127. useLookupRecognizedTypes = false
  128. // using recognized allows us to do d.decode(interface{}) instead of d.decodeValue(reflect.Value)
  129. // when we can infer that the kind of the interface{} is one of the ones hard-coded in the
  130. // type switch for known types or the ones defined by fast-path.
  131. //
  132. // However, it seems we get better performance when we don't recognize, and just let
  133. // reflection handle it.
  134. //
  135. // Reasoning is as below:
  136. // typeswitch is a binary search with a branch to a code-point.
  137. // getdecfn is a binary search with a call to a function pointer.
  138. //
  139. // both are about the same.
  140. //
  141. // so: why prefer typeswitch?
  142. //
  143. // is recognized does the following:
  144. // - lookup rtid
  145. // - check if in sorted list
  146. // - calls decode(type switch)
  147. // - 1 or 2 binary search to a point in code
  148. // - branch there
  149. //
  150. // vs getdecfn
  151. // - lookup rtid
  152. // - check in sorted list for a function pointer
  153. // - calls it to decode using reflection (optimized)
  154. // always set xDebug = false before releasing software
  155. xDebug = true
  156. )
  157. var (
  158. oneByteArr = [1]byte{0}
  159. zeroByteSlice = oneByteArr[:0:0]
  160. )
  161. var pool pooler
  162. func init() {
  163. pool.init()
  164. }
  165. // type findCodecFnMode uint8
  166. // const (
  167. // findCodecFnModeMap findCodecFnMode = iota
  168. // findCodecFnModeBinarySearch
  169. // findCodecFnModeLinearSearch
  170. // )
  171. type charEncoding uint8
  172. const (
  173. c_RAW charEncoding = iota
  174. c_UTF8
  175. c_UTF16LE
  176. c_UTF16BE
  177. c_UTF32LE
  178. c_UTF32BE
  179. )
  180. // valueType is the stream type
  181. type valueType uint8
  182. const (
  183. valueTypeUnset valueType = iota
  184. valueTypeNil
  185. valueTypeInt
  186. valueTypeUint
  187. valueTypeFloat
  188. valueTypeBool
  189. valueTypeString
  190. valueTypeSymbol
  191. valueTypeBytes
  192. valueTypeMap
  193. valueTypeArray
  194. valueTypeTimestamp
  195. valueTypeExt
  196. // valueTypeInvalid = 0xff
  197. )
  198. func (x valueType) String() string {
  199. switch x {
  200. case valueTypeNil:
  201. return "Nil"
  202. case valueTypeInt:
  203. return "Int"
  204. case valueTypeUint:
  205. return "Uint"
  206. case valueTypeFloat:
  207. return "Float"
  208. case valueTypeBool:
  209. return "Bool"
  210. case valueTypeString:
  211. return "String"
  212. case valueTypeSymbol:
  213. return "Symbol"
  214. case valueTypeBytes:
  215. return "Bytes"
  216. case valueTypeMap:
  217. return "Map"
  218. case valueTypeArray:
  219. return "Array"
  220. case valueTypeTimestamp:
  221. return "Timestamp"
  222. case valueTypeExt:
  223. return "Ext"
  224. }
  225. return strconv.FormatInt(int64(x), 10)
  226. }
  227. type seqType uint8
  228. const (
  229. _ seqType = iota
  230. seqTypeArray
  231. seqTypeSlice
  232. seqTypeChan
  233. )
  234. // note that containerMapStart and containerArraySend are not sent.
  235. // This is because the ReadXXXStart and EncodeXXXStart already does these.
  236. type containerState uint8
  237. const (
  238. _ containerState = iota
  239. containerMapStart // slot left open, since Driver method already covers it
  240. containerMapKey
  241. containerMapValue
  242. containerMapEnd
  243. containerArrayStart // slot left open, since Driver methods already cover it
  244. containerArrayElem
  245. containerArrayEnd
  246. )
  247. // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
  248. type sfiIdx struct {
  249. name string
  250. index int
  251. }
  252. // do not recurse if a containing type refers to an embedded type
  253. // which refers back to its containing type (via a pointer).
  254. // The second time this back-reference happens, break out,
  255. // so as not to cause an infinite loop.
  256. const rgetMaxRecursion = 2
  257. // Anecdotally, we believe most types have <= 12 fields.
  258. // Java's PMD rules set TooManyFields threshold to 15.
  259. const typeInfoLoadArrayLen = 12
  260. type typeInfoLoad struct {
  261. fNames []string
  262. encNames []string
  263. etypes []uintptr
  264. sfis []*structFieldInfo
  265. }
  266. type typeInfoLoadArray struct {
  267. fNames [typeInfoLoadArrayLen]string
  268. encNames [typeInfoLoadArrayLen]string
  269. etypes [typeInfoLoadArrayLen]uintptr
  270. sfis [typeInfoLoadArrayLen]*structFieldInfo
  271. sfiidx [typeInfoLoadArrayLen]sfiIdx
  272. }
  273. type containerStateRecv interface {
  274. sendContainerState(containerState)
  275. }
  276. // mirror json.Marshaler and json.Unmarshaler here,
  277. // so we don't import the encoding/json package
  278. type jsonMarshaler interface {
  279. MarshalJSON() ([]byte, error)
  280. }
  281. type jsonUnmarshaler interface {
  282. UnmarshalJSON([]byte) error
  283. }
  284. // type byteAccepter func(byte) bool
  285. var (
  286. bigen = binary.BigEndian
  287. structInfoFieldName = "_struct"
  288. mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  289. mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
  290. intfSliceTyp = reflect.TypeOf([]interface{}(nil))
  291. intfTyp = intfSliceTyp.Elem()
  292. stringTyp = reflect.TypeOf("")
  293. timeTyp = reflect.TypeOf(time.Time{})
  294. rawExtTyp = reflect.TypeOf(RawExt{})
  295. rawTyp = reflect.TypeOf(Raw{})
  296. uint8SliceTyp = reflect.TypeOf([]uint8(nil))
  297. mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
  298. binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  299. binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  300. textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  301. textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  302. jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  303. jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  304. selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
  305. uint8SliceTypId = rt2id(uint8SliceTyp)
  306. rawExtTypId = rt2id(rawExtTyp)
  307. rawTypId = rt2id(rawTyp)
  308. intfTypId = rt2id(intfTyp)
  309. timeTypId = rt2id(timeTyp)
  310. stringTypId = rt2id(stringTyp)
  311. mapStrIntfTypId = rt2id(mapStrIntfTyp)
  312. mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
  313. intfSliceTypId = rt2id(intfSliceTyp)
  314. // mapBySliceTypId = rt2id(mapBySliceTyp)
  315. intBitsize uint8 = uint8(reflect.TypeOf(int(0)).Bits())
  316. uintBitsize uint8 = uint8(reflect.TypeOf(uint(0)).Bits())
  317. bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
  318. bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  319. chkOvf checkOverflow
  320. noFieldNameToStructFieldInfoErr = errors.New("no field name passed to parseStructFieldInfo")
  321. )
  322. var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
  323. var immutableKindsSet = [32]bool{
  324. // reflect.Invalid: ,
  325. reflect.Bool: true,
  326. reflect.Int: true,
  327. reflect.Int8: true,
  328. reflect.Int16: true,
  329. reflect.Int32: true,
  330. reflect.Int64: true,
  331. reflect.Uint: true,
  332. reflect.Uint8: true,
  333. reflect.Uint16: true,
  334. reflect.Uint32: true,
  335. reflect.Uint64: true,
  336. reflect.Uintptr: true,
  337. reflect.Float32: true,
  338. reflect.Float64: true,
  339. reflect.Complex64: true,
  340. reflect.Complex128: true,
  341. // reflect.Array
  342. // reflect.Chan
  343. // reflect.Func: true,
  344. // reflect.Interface
  345. // reflect.Map
  346. // reflect.Ptr
  347. // reflect.Slice
  348. reflect.String: true,
  349. // reflect.Struct
  350. // reflect.UnsafePointer
  351. }
  352. var recognizedRtids []uintptr
  353. var recognizedRtidPtrs []uintptr
  354. var recognizedRtidOrPtrs []uintptr
  355. func init() {
  356. if !useLookupRecognizedTypes {
  357. return
  358. }
  359. for _, v := range [...]interface{}{
  360. float32(0),
  361. float64(0),
  362. uintptr(0),
  363. uint(0),
  364. uint8(0),
  365. uint16(0),
  366. uint32(0),
  367. uint64(0),
  368. uintptr(0),
  369. int(0),
  370. int8(0),
  371. int16(0),
  372. int32(0),
  373. int64(0),
  374. bool(false),
  375. string(""),
  376. Raw{},
  377. []byte(nil),
  378. } {
  379. rt := reflect.TypeOf(v)
  380. recognizedRtids = append(recognizedRtids, rt2id(rt))
  381. recognizedRtidPtrs = append(recognizedRtidPtrs, rt2id(reflect.PtrTo(rt)))
  382. }
  383. }
  384. func containsU(s []uintptr, v uintptr) bool {
  385. // return false // TODO: REMOVE
  386. h, i, j := 0, 0, len(s)
  387. for i < j {
  388. h = i + (j-i)/2
  389. if s[h] < v {
  390. i = h + 1
  391. } else {
  392. j = h
  393. }
  394. }
  395. if i < len(s) && s[i] == v {
  396. return true
  397. }
  398. return false
  399. }
  400. func isRecognizedRtid(rtid uintptr) bool {
  401. return containsU(recognizedRtids, rtid)
  402. }
  403. func isRecognizedRtidPtr(rtid uintptr) bool {
  404. return containsU(recognizedRtidPtrs, rtid)
  405. }
  406. func isRecognizedRtidOrPtr(rtid uintptr) bool {
  407. return containsU(recognizedRtidOrPtrs, rtid)
  408. }
  409. // Selfer defines methods by which a value can encode or decode itself.
  410. //
  411. // Any type which implements Selfer will be able to encode or decode itself.
  412. // Consequently, during (en|de)code, this takes precedence over
  413. // (text|binary)(M|Unm)arshal or extension support.
  414. type Selfer interface {
  415. CodecEncodeSelf(*Encoder)
  416. CodecDecodeSelf(*Decoder)
  417. }
  418. // MapBySlice represents a slice which should be encoded as a map in the stream.
  419. // The slice contains a sequence of key-value pairs.
  420. // This affords storing a map in a specific sequence in the stream.
  421. //
  422. // The support of MapBySlice affords the following:
  423. // - A slice type which implements MapBySlice will be encoded as a map
  424. // - A slice can be decoded from a map in the stream
  425. type MapBySlice interface {
  426. MapBySlice()
  427. }
  428. // WARNING: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
  429. //
  430. // BasicHandle encapsulates the common options and extension functions.
  431. type BasicHandle struct {
  432. // TypeInfos is used to get the type info for any type.
  433. //
  434. // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
  435. TypeInfos *TypeInfos
  436. extHandle
  437. EncodeOptions
  438. DecodeOptions
  439. noBuiltInTypeChecker
  440. }
  441. func (x *BasicHandle) getBasicHandle() *BasicHandle {
  442. return x
  443. }
  444. func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  445. if x.TypeInfos == nil {
  446. return defTypeInfos.get(rtid, rt)
  447. }
  448. return x.TypeInfos.get(rtid, rt)
  449. }
  450. // Handle is the interface for a specific encoding format.
  451. //
  452. // Typically, a Handle is pre-configured before first time use,
  453. // and not modified while in use. Such a pre-configured Handle
  454. // is safe for concurrent access.
  455. type Handle interface {
  456. getBasicHandle() *BasicHandle
  457. newEncDriver(w *Encoder) encDriver
  458. newDecDriver(r *Decoder) decDriver
  459. isBinary() bool
  460. IsBuiltinType(rtid uintptr) bool
  461. }
  462. // Raw represents raw formatted bytes.
  463. // We "blindly" store it during encode and store the raw bytes during decode.
  464. // Note: it is dangerous during encode, so we may gate the behaviour behind an Encode flag which must be explicitly set.
  465. type Raw []byte
  466. // RawExt represents raw unprocessed extension data.
  467. // Some codecs will decode extension data as a *RawExt if there is no registered extension for the tag.
  468. //
  469. // Only one of Data or Value is nil. If Data is nil, then the content of the RawExt is in the Value.
  470. type RawExt struct {
  471. Tag uint64
  472. // Data is the []byte which represents the raw ext. If Data is nil, ext is exposed in Value.
  473. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types
  474. Data []byte
  475. // Value represents the extension, if Data is nil.
  476. // Value is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  477. Value interface{}
  478. }
  479. // BytesExt handles custom (de)serialization of types to/from []byte.
  480. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  481. type BytesExt interface {
  482. // WriteExt converts a value to a []byte.
  483. //
  484. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  485. WriteExt(v interface{}) []byte
  486. // ReadExt updates a value from a []byte.
  487. ReadExt(dst interface{}, src []byte)
  488. }
  489. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  490. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  491. //
  492. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  493. type InterfaceExt interface {
  494. // ConvertExt converts a value into a simpler interface for easy encoding e.g. convert time.Time to int64.
  495. //
  496. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  497. ConvertExt(v interface{}) interface{}
  498. // UpdateExt updates a value from a simpler interface for easy decoding e.g. convert int64 to time.Time.
  499. UpdateExt(dst interface{}, src interface{})
  500. }
  501. // Ext handles custom (de)serialization of custom types / extensions.
  502. type Ext interface {
  503. BytesExt
  504. InterfaceExt
  505. }
  506. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  507. type addExtWrapper struct {
  508. encFn func(reflect.Value) ([]byte, error)
  509. decFn func(reflect.Value, []byte) error
  510. }
  511. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  512. bs, err := x.encFn(reflect.ValueOf(v))
  513. if err != nil {
  514. panic(err)
  515. }
  516. return bs
  517. }
  518. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  519. if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
  520. panic(err)
  521. }
  522. }
  523. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  524. return x.WriteExt(v)
  525. }
  526. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  527. x.ReadExt(dest, v.([]byte))
  528. }
  529. type setExtWrapper struct {
  530. b BytesExt
  531. i InterfaceExt
  532. }
  533. func (x *setExtWrapper) WriteExt(v interface{}) []byte {
  534. if x.b == nil {
  535. panic("BytesExt.WriteExt is not supported")
  536. }
  537. return x.b.WriteExt(v)
  538. }
  539. func (x *setExtWrapper) ReadExt(v interface{}, bs []byte) {
  540. if x.b == nil {
  541. panic("BytesExt.WriteExt is not supported")
  542. }
  543. x.b.ReadExt(v, bs)
  544. }
  545. func (x *setExtWrapper) ConvertExt(v interface{}) interface{} {
  546. if x.i == nil {
  547. panic("InterfaceExt.ConvertExt is not supported")
  548. }
  549. return x.i.ConvertExt(v)
  550. }
  551. func (x *setExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  552. if x.i == nil {
  553. panic("InterfaceExxt.UpdateExt is not supported")
  554. }
  555. x.i.UpdateExt(dest, v)
  556. }
  557. type binaryEncodingType struct{}
  558. func (_ binaryEncodingType) isBinary() bool { return true }
  559. type textEncodingType struct{}
  560. func (_ textEncodingType) isBinary() bool { return false }
  561. // noBuiltInTypes is embedded into many types which do not support builtins
  562. // e.g. msgpack, simple, cbor.
  563. type noBuiltInTypeChecker struct{}
  564. func (_ noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
  565. type noBuiltInTypes struct{ noBuiltInTypeChecker }
  566. func (_ noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  567. func (_ noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  568. type noStreamingCodec struct{}
  569. func (_ noStreamingCodec) CheckBreak() bool { return false }
  570. // bigenHelper.
  571. // Users must already slice the x completely, because we will not reslice.
  572. type bigenHelper struct {
  573. x []byte // must be correctly sliced to appropriate len. slicing is a cost.
  574. w encWriter
  575. }
  576. func (z bigenHelper) writeUint16(v uint16) {
  577. bigen.PutUint16(z.x, v)
  578. z.w.writeb(z.x)
  579. }
  580. func (z bigenHelper) writeUint32(v uint32) {
  581. bigen.PutUint32(z.x, v)
  582. z.w.writeb(z.x)
  583. }
  584. func (z bigenHelper) writeUint64(v uint64) {
  585. bigen.PutUint64(z.x, v)
  586. z.w.writeb(z.x)
  587. }
  588. type extTypeTagFn struct {
  589. rtid uintptr
  590. rt reflect.Type
  591. tag uint64
  592. ext Ext
  593. }
  594. type extHandle []extTypeTagFn
  595. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  596. //
  597. // AddExt registes an encode and decode function for a reflect.Type.
  598. // AddExt internally calls SetExt.
  599. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  600. func (o *extHandle) AddExt(
  601. rt reflect.Type, tag byte,
  602. encfn func(reflect.Value) ([]byte, error), decfn func(reflect.Value, []byte) error,
  603. ) (err error) {
  604. if encfn == nil || decfn == nil {
  605. return o.SetExt(rt, uint64(tag), nil)
  606. }
  607. return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  608. }
  609. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  610. //
  611. // Note that the type must be a named type, and specifically not
  612. // a pointer or Interface. An error is returned if that is not honored.
  613. //
  614. // To Deregister an ext, call SetExt with nil Ext
  615. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  616. // o is a pointer, because we may need to initialize it
  617. if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
  618. err = fmt.Errorf("codec.Handle.AddExt: Takes named type, not a pointer or interface: %T",
  619. reflect.Zero(rt).Interface())
  620. return
  621. }
  622. rtid := rt2id(rt)
  623. for _, v := range *o {
  624. if v.rtid == rtid {
  625. v.tag, v.ext = tag, ext
  626. return
  627. }
  628. }
  629. if *o == nil {
  630. *o = make([]extTypeTagFn, 0, 4)
  631. }
  632. *o = append(*o, extTypeTagFn{rtid, rt, tag, ext})
  633. return
  634. }
  635. func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
  636. var v *extTypeTagFn
  637. for i := range o {
  638. v = &o[i]
  639. if v.rtid == rtid {
  640. return v
  641. }
  642. }
  643. return nil
  644. }
  645. func (o extHandle) getExtForTag(tag uint64) *extTypeTagFn {
  646. var v *extTypeTagFn
  647. for i := range o {
  648. v = &o[i]
  649. if v.tag == tag {
  650. return v
  651. }
  652. }
  653. return nil
  654. }
  655. const maxLevelsEmbedding = 16
  656. type structFieldInfo struct {
  657. encName string // encode name
  658. fieldName string // field name
  659. is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
  660. nis uint8 // num levels of embedding. if 1, then it's not embedded.
  661. omitEmpty bool
  662. toArray bool // if field is _struct, is the toArray set?
  663. }
  664. // func (si *structFieldInfo) isZero() bool {
  665. // return si.encName == "" && len(si.is) == 0 && si.i == 0 && !si.omitEmpty && !si.toArray
  666. // }
  667. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  668. if v, valid := si.field(v, false); valid {
  669. v.Set(reflect.Zero(v.Type()))
  670. }
  671. }
  672. // rv returns the field of the struct.
  673. // If anonymous, it returns an Invalid
  674. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
  675. // replicate FieldByIndex
  676. for i, x := range si.is {
  677. if uint8(i) == si.nis {
  678. break
  679. }
  680. if v, valid = baseStructRv(v, update); !valid {
  681. return
  682. }
  683. v = v.Field(int(x))
  684. }
  685. return v, true
  686. }
  687. func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
  688. v, _ = si.field(v, update)
  689. return v
  690. }
  691. func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
  692. // if fname == "" {
  693. // panic(noFieldNameToStructFieldInfoErr)
  694. // }
  695. si := structFieldInfo{
  696. encName: fname,
  697. }
  698. if stag != "" {
  699. for i, s := range strings.Split(stag, ",") {
  700. if i == 0 {
  701. if s != "" {
  702. si.encName = s
  703. }
  704. } else {
  705. if s == "omitempty" {
  706. si.omitEmpty = true
  707. } else if s == "toarray" {
  708. si.toArray = true
  709. }
  710. }
  711. }
  712. }
  713. // si.encNameBs = []byte(si.encName)
  714. return &si
  715. }
  716. type sfiSortedByEncName []*structFieldInfo
  717. func (p sfiSortedByEncName) Len() int {
  718. return len(p)
  719. }
  720. func (p sfiSortedByEncName) Less(i, j int) bool {
  721. return p[i].encName < p[j].encName
  722. }
  723. func (p sfiSortedByEncName) Swap(i, j int) {
  724. p[i], p[j] = p[j], p[i]
  725. }
  726. const structFieldNodeNumToCache = 4
  727. type structFieldNodeCache struct {
  728. rv [structFieldNodeNumToCache]reflect.Value
  729. idx [structFieldNodeNumToCache]uint32
  730. num uint8
  731. }
  732. func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
  733. // defer func() { fmt.Printf(">>>> found in cache2? %v\n", valid) }()
  734. for i, k := range &x.idx {
  735. if uint8(i) == x.num {
  736. return // break
  737. }
  738. if key == k {
  739. return x.rv[i], true
  740. }
  741. }
  742. return
  743. }
  744. func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
  745. if x.num < structFieldNodeNumToCache {
  746. x.rv[x.num] = fv
  747. x.idx[x.num] = key
  748. x.num++
  749. return
  750. }
  751. }
  752. type structFieldNode struct {
  753. v reflect.Value
  754. cache2 structFieldNodeCache
  755. cache3 structFieldNodeCache
  756. update bool
  757. }
  758. func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
  759. // return si.fieldval(x.v, x.update)
  760. // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
  761. // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
  762. var valid bool
  763. switch si.nis {
  764. case 1:
  765. fv = x.v.Field(int(si.is[0]))
  766. case 2:
  767. if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
  768. fv = fv.Field(int(si.is[1]))
  769. return
  770. }
  771. fv = x.v.Field(int(si.is[0]))
  772. if fv, valid = baseStructRv(fv, x.update); !valid {
  773. return
  774. }
  775. x.cache2.tryAdd(fv, uint32(si.is[0]))
  776. fv = fv.Field(int(si.is[1]))
  777. case 3:
  778. var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
  779. if fv, valid = x.cache3.get(key); valid {
  780. fv = fv.Field(int(si.is[2]))
  781. return
  782. }
  783. fv = x.v.Field(int(si.is[0]))
  784. if fv, valid = baseStructRv(fv, x.update); !valid {
  785. return
  786. }
  787. fv = fv.Field(int(si.is[1]))
  788. if fv, valid = baseStructRv(fv, x.update); !valid {
  789. return
  790. }
  791. x.cache3.tryAdd(fv, key)
  792. fv = fv.Field(int(si.is[2]))
  793. default:
  794. fv, _ = si.field(x.v, x.update)
  795. }
  796. return
  797. }
  798. func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
  799. for v.Kind() == reflect.Ptr {
  800. if v.IsNil() {
  801. if !update {
  802. return
  803. }
  804. v.Set(reflect.New(v.Type().Elem()))
  805. }
  806. v = v.Elem()
  807. }
  808. return v, true
  809. }
  810. // typeInfo keeps information about each type referenced in the encode/decode sequence.
  811. //
  812. // During an encode/decode sequence, we work as below:
  813. // - If base is a built in type, en/decode base value
  814. // - If base is registered as an extension, en/decode base value
  815. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  816. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  817. // - Else decode appropriately based on the reflect.Kind
  818. type typeInfo struct {
  819. sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
  820. sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  821. rt reflect.Type
  822. rtid uintptr
  823. // rv0 reflect.Value // saved zero value, used if immutableKind
  824. numMeth uint16 // number of methods
  825. // baseId gives pointer to the base reflect.Type, after deferencing
  826. // the pointers. E.g. base type of ***time.Time is time.Time.
  827. base reflect.Type
  828. baseId uintptr
  829. baseIndir int8 // number of indirections to get to base
  830. anyOmitEmpty bool
  831. mbs bool // base type (T or *T) is a MapBySlice
  832. bm bool // base type (T or *T) is a binaryMarshaler
  833. bunm bool // base type (T or *T) is a binaryUnmarshaler
  834. bmIndir int8 // number of indirections to get to binaryMarshaler type
  835. bunmIndir int8 // number of indirections to get to binaryUnmarshaler type
  836. tm bool // base type (T or *T) is a textMarshaler
  837. tunm bool // base type (T or *T) is a textUnmarshaler
  838. tmIndir int8 // number of indirections to get to textMarshaler type
  839. tunmIndir int8 // number of indirections to get to textUnmarshaler type
  840. jm bool // base type (T or *T) is a jsonMarshaler
  841. junm bool // base type (T or *T) is a jsonUnmarshaler
  842. jmIndir int8 // number of indirections to get to jsonMarshaler type
  843. junmIndir int8 // number of indirections to get to jsonUnmarshaler type
  844. cs bool // base type (T or *T) is a Selfer
  845. csIndir int8 // number of indirections to get to Selfer type
  846. toArray bool // whether this (struct) type should be encoded as an array
  847. }
  848. // define length beyond which we do a binary search instead of a linear search.
  849. // From our testing, linear search seems faster than binary search up to 16-field structs.
  850. // However, we set to 8 similar to what python does for hashtables.
  851. const indexForEncNameBinarySearchThreshold = 8
  852. func (ti *typeInfo) indexForEncName(name string) int {
  853. // NOTE: name may be a stringView, so don't pass it to another function.
  854. //tisfi := ti.sfi
  855. sfilen := len(ti.sfi)
  856. if sfilen < indexForEncNameBinarySearchThreshold {
  857. for i, si := range ti.sfi {
  858. if si.encName == name {
  859. return i
  860. }
  861. }
  862. return -1
  863. }
  864. // binary search. adapted from sort/search.go.
  865. h, i, j := 0, 0, sfilen
  866. for i < j {
  867. h = i + (j-i)/2
  868. if ti.sfi[h].encName < name {
  869. i = h + 1
  870. } else {
  871. j = h
  872. }
  873. }
  874. if i < sfilen && ti.sfi[i].encName == name {
  875. return i
  876. }
  877. return -1
  878. }
  879. type rtid2ti struct {
  880. rtid uintptr
  881. ti *typeInfo
  882. }
  883. // TypeInfos caches typeInfo for each type on first inspection.
  884. //
  885. // It is configured with a set of tag keys, which are used to get
  886. // configuration for the type.
  887. type TypeInfos struct {
  888. infos atomicTypeInfoSlice // formerly map[uintptr]*typeInfo, now *[]rtid2ti
  889. mu sync.Mutex
  890. tags []string
  891. }
  892. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  893. //
  894. // This allows users customize the struct tag keys which contain configuration
  895. // of their types.
  896. func NewTypeInfos(tags []string) *TypeInfos {
  897. return &TypeInfos{tags: tags}
  898. }
  899. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  900. // check for tags: codec, json, in that order.
  901. // this allows seamless support for many configured structs.
  902. for _, x := range x.tags {
  903. s = t.Get(x)
  904. if s != "" {
  905. return s
  906. }
  907. }
  908. return
  909. }
  910. func (x *TypeInfos) find(sp *[]rtid2ti, rtid uintptr) (idx int, ti *typeInfo) {
  911. // binary search. adapted from sort/search.go.
  912. // if sp == nil {
  913. // return -1, nil
  914. // }
  915. s := *sp
  916. h, i, j := 0, 0, len(s)
  917. for i < j {
  918. h = i + (j-i)/2
  919. if s[h].rtid < rtid {
  920. i = h + 1
  921. } else {
  922. j = h
  923. }
  924. }
  925. if i < len(s) && s[i].rtid == rtid {
  926. return i, s[i].ti
  927. }
  928. return i, nil
  929. }
  930. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  931. sp := x.infos.load()
  932. var idx int
  933. if sp != nil {
  934. idx, pti = x.find(sp, rtid)
  935. if pti != nil {
  936. return
  937. }
  938. }
  939. // do not hold lock while computing this.
  940. // it may lead to duplication, but that's ok.
  941. ti := typeInfo{rt: rt, rtid: rtid}
  942. // ti.rv0 = reflect.Zero(rt)
  943. ti.numMeth = uint16(rt.NumMethod())
  944. var ok bool
  945. var indir int8
  946. if ok, indir = implementsIntf(rt, binaryMarshalerTyp); ok {
  947. ti.bm, ti.bmIndir = true, indir
  948. }
  949. if ok, indir = implementsIntf(rt, binaryUnmarshalerTyp); ok {
  950. ti.bunm, ti.bunmIndir = true, indir
  951. }
  952. if ok, indir = implementsIntf(rt, textMarshalerTyp); ok {
  953. ti.tm, ti.tmIndir = true, indir
  954. }
  955. if ok, indir = implementsIntf(rt, textUnmarshalerTyp); ok {
  956. ti.tunm, ti.tunmIndir = true, indir
  957. }
  958. if ok, indir = implementsIntf(rt, jsonMarshalerTyp); ok {
  959. ti.jm, ti.jmIndir = true, indir
  960. }
  961. if ok, indir = implementsIntf(rt, jsonUnmarshalerTyp); ok {
  962. ti.junm, ti.junmIndir = true, indir
  963. }
  964. if ok, indir = implementsIntf(rt, selferTyp); ok {
  965. ti.cs, ti.csIndir = true, indir
  966. }
  967. if ok, _ = implementsIntf(rt, mapBySliceTyp); ok {
  968. ti.mbs = true
  969. }
  970. pt := rt
  971. var ptIndir int8
  972. // for ; pt.Kind() == reflect.Ptr; pt, ptIndir = pt.Elem(), ptIndir+1 { }
  973. for pt.Kind() == reflect.Ptr {
  974. pt = pt.Elem()
  975. ptIndir++
  976. }
  977. if ptIndir == 0 {
  978. ti.base = rt
  979. ti.baseId = rtid
  980. } else {
  981. ti.base = pt
  982. ti.baseId = rt2id(pt)
  983. ti.baseIndir = ptIndir
  984. }
  985. if rt.Kind() == reflect.Struct {
  986. var omitEmpty bool
  987. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  988. siInfo := parseStructFieldInfo(structInfoFieldName, x.structTag(f.Tag))
  989. ti.toArray = siInfo.toArray
  990. omitEmpty = siInfo.omitEmpty
  991. }
  992. pp, pi := pool.tiLoad()
  993. pv := pi.(*typeInfoLoadArray)
  994. pv.etypes[0] = ti.baseId
  995. vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  996. x.rget(rt, rtid, omitEmpty, nil, &vv)
  997. ti.sfip, ti.sfi, ti.anyOmitEmpty = rgetResolveSFI(vv.sfis, pv.sfiidx[:0])
  998. pp.Put(pi)
  999. }
  1000. // sfi = sfip
  1001. var vs []rtid2ti
  1002. x.mu.Lock()
  1003. sp = x.infos.load()
  1004. if sp == nil {
  1005. pti = &ti
  1006. vs = []rtid2ti{{rtid, pti}}
  1007. x.infos.store(&vs)
  1008. } else {
  1009. idx, pti = x.find(sp, rtid)
  1010. if pti == nil {
  1011. s := *sp
  1012. pti = &ti
  1013. vs = make([]rtid2ti, len(s)+1)
  1014. copy(vs, s[:idx])
  1015. vs[idx] = rtid2ti{rtid, pti}
  1016. copy(vs[idx+1:], s[idx:])
  1017. x.infos.store(&vs)
  1018. }
  1019. }
  1020. x.mu.Unlock()
  1021. return
  1022. }
  1023. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  1024. indexstack []uint16, pv *typeInfoLoad,
  1025. ) {
  1026. // Read up fields and store how to access the value.
  1027. //
  1028. // It uses go's rules for message selectors,
  1029. // which say that the field with the shallowest depth is selected.
  1030. //
  1031. // Note: we consciously use slices, not a map, to simulate a set.
  1032. // Typically, types have < 16 fields,
  1033. // and iteration using equals is faster than maps there
  1034. flen := rt.NumField()
  1035. if flen > (1<<16 - 1) {
  1036. panic(fmt.Errorf("codec: types with more than %v fields are not supported - has %v fields", (1<<16 - 1), flen))
  1037. }
  1038. LOOP:
  1039. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  1040. f := rt.Field(int(j))
  1041. fkind := f.Type.Kind()
  1042. // skip if a func type, or is unexported, or structTag value == "-"
  1043. switch fkind {
  1044. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  1045. continue LOOP
  1046. }
  1047. // if r1, _ := utf8.DecodeRuneInString(f.Name);
  1048. // r1 == utf8.RuneError || !unicode.IsUpper(r1) {
  1049. if f.PkgPath != "" && !f.Anonymous { // unexported, not embedded
  1050. continue
  1051. }
  1052. stag := x.structTag(f.Tag)
  1053. if stag == "-" {
  1054. continue
  1055. }
  1056. var si *structFieldInfo
  1057. // if anonymous and no struct tag (or it's blank),
  1058. // and a struct (or pointer to struct), inline it.
  1059. if f.Anonymous && fkind != reflect.Interface {
  1060. doInline := stag == ""
  1061. if !doInline {
  1062. si = parseStructFieldInfo("", stag)
  1063. doInline = si.encName == ""
  1064. // doInline = si.isZero()
  1065. }
  1066. if doInline {
  1067. ft := f.Type
  1068. for ft.Kind() == reflect.Ptr {
  1069. ft = ft.Elem()
  1070. }
  1071. if ft.Kind() == reflect.Struct {
  1072. // if etypes contains this, don't call rget again (as fields are already seen here)
  1073. ftid := rt2id(ft)
  1074. // We cannot recurse forever, but we need to track other field depths.
  1075. // So - we break if we see a type twice (not the first time).
  1076. // This should be sufficient to handle an embedded type that refers to its
  1077. // owning type, which then refers to its embedded type.
  1078. processIt := true
  1079. numk := 0
  1080. for _, k := range pv.etypes {
  1081. if k == ftid {
  1082. numk++
  1083. if numk == rgetMaxRecursion {
  1084. processIt = false
  1085. break
  1086. }
  1087. }
  1088. }
  1089. if processIt {
  1090. pv.etypes = append(pv.etypes, ftid)
  1091. indexstack2 := make([]uint16, len(indexstack)+1)
  1092. copy(indexstack2, indexstack)
  1093. indexstack2[len(indexstack)] = j
  1094. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  1095. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  1096. }
  1097. continue
  1098. }
  1099. }
  1100. }
  1101. // after the anonymous dance: if an unexported field, skip
  1102. if f.PkgPath != "" { // unexported
  1103. continue
  1104. }
  1105. if f.Name == "" {
  1106. panic(noFieldNameToStructFieldInfoErr)
  1107. }
  1108. pv.fNames = append(pv.fNames, f.Name)
  1109. if si == nil {
  1110. si = parseStructFieldInfo(f.Name, stag)
  1111. } else if si.encName == "" {
  1112. si.encName = f.Name
  1113. }
  1114. si.fieldName = f.Name
  1115. pv.encNames = append(pv.encNames, si.encName)
  1116. // si.ikind = int(f.Type.Kind())
  1117. if len(indexstack) > maxLevelsEmbedding-1 {
  1118. panic(fmt.Errorf("codec: only supports up to %v depth of embedding - type has %v depth", maxLevelsEmbedding-1, len(indexstack)))
  1119. }
  1120. si.nis = uint8(len(indexstack)) + 1
  1121. copy(si.is[:], indexstack)
  1122. si.is[len(indexstack)] = j
  1123. if omitEmpty {
  1124. si.omitEmpty = true
  1125. }
  1126. pv.sfis = append(pv.sfis, si)
  1127. }
  1128. }
  1129. // resolves the struct field info got from a call to rget.
  1130. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  1131. func rgetResolveSFI(x []*structFieldInfo, pv []sfiIdx) (y, z []*structFieldInfo, anyOmitEmpty bool) {
  1132. var n int
  1133. for i, v := range x {
  1134. xn := v.encName //TODO: fieldName or encName? use encName for now.
  1135. var found bool
  1136. for j, k := range pv {
  1137. if k.name == xn {
  1138. // one of them must be reset to nil, and the index updated appropriately to the other one
  1139. if len(v.is) == len(x[k.index].is) {
  1140. } else if len(v.is) < len(x[k.index].is) {
  1141. pv[j].index = i
  1142. if x[k.index] != nil {
  1143. x[k.index] = nil
  1144. n++
  1145. }
  1146. } else {
  1147. if x[i] != nil {
  1148. x[i] = nil
  1149. n++
  1150. }
  1151. }
  1152. found = true
  1153. break
  1154. }
  1155. }
  1156. if !found {
  1157. pv = append(pv, sfiIdx{xn, i})
  1158. }
  1159. }
  1160. // remove all the nils
  1161. y = make([]*structFieldInfo, len(x)-n)
  1162. n = 0
  1163. for _, v := range x {
  1164. if v == nil {
  1165. continue
  1166. }
  1167. if !anyOmitEmpty && v.omitEmpty {
  1168. anyOmitEmpty = true
  1169. }
  1170. y[n] = v
  1171. n++
  1172. }
  1173. z = make([]*structFieldInfo, len(y))
  1174. copy(z, y)
  1175. sort.Sort(sfiSortedByEncName(z))
  1176. return
  1177. }
  1178. func xprintf(format string, a ...interface{}) {
  1179. if xDebug {
  1180. fmt.Fprintf(os.Stderr, format, a...)
  1181. }
  1182. }
  1183. func panicToErr(err *error) {
  1184. if recoverPanicToErr {
  1185. if x := recover(); x != nil {
  1186. // if false && xDebug {
  1187. // fmt.Printf("panic'ing with: %v\n", x)
  1188. // debug.PrintStack()
  1189. // }
  1190. panicValToErr(x, err)
  1191. }
  1192. }
  1193. }
  1194. func panicToErrs2(err1, err2 *error) {
  1195. if recoverPanicToErr {
  1196. if x := recover(); x != nil {
  1197. panicValToErr(x, err1)
  1198. panicValToErr(x, err2)
  1199. }
  1200. }
  1201. }
  1202. // func doPanic(tag string, format string, params ...interface{}) {
  1203. // params2 := make([]interface{}, len(params)+1)
  1204. // params2[0] = tag
  1205. // copy(params2[1:], params)
  1206. // panic(fmt.Errorf("%s: "+format, params2...))
  1207. // }
  1208. func isImmutableKind(k reflect.Kind) (v bool) {
  1209. return immutableKindsSet[k]
  1210. // return false ||
  1211. // k == reflect.Int ||
  1212. // k == reflect.Int8 ||
  1213. // k == reflect.Int16 ||
  1214. // k == reflect.Int32 ||
  1215. // k == reflect.Int64 ||
  1216. // k == reflect.Uint ||
  1217. // k == reflect.Uint8 ||
  1218. // k == reflect.Uint16 ||
  1219. // k == reflect.Uint32 ||
  1220. // k == reflect.Uint64 ||
  1221. // k == reflect.Uintptr ||
  1222. // k == reflect.Float32 ||
  1223. // k == reflect.Float64 ||
  1224. // k == reflect.Bool ||
  1225. // k == reflect.String
  1226. }
  1227. // ----
  1228. type codecFnInfo struct {
  1229. ti *typeInfo
  1230. xfFn Ext
  1231. xfTag uint64
  1232. seq seqType
  1233. addr bool
  1234. }
  1235. // codecFn encapsulates the captured variables and the encode function.
  1236. // This way, we only do some calculations one times, and pass to the
  1237. // code block that should be called (encapsulated in a function)
  1238. // instead of executing the checks every time.
  1239. type codecFn struct {
  1240. i codecFnInfo
  1241. fe func(*Encoder, *codecFnInfo, reflect.Value)
  1242. fd func(*Decoder, *codecFnInfo, reflect.Value)
  1243. }
  1244. type codecRtidFn struct {
  1245. rtid uintptr
  1246. fn codecFn
  1247. }
  1248. type codecFner struct {
  1249. hh Handle
  1250. h *BasicHandle
  1251. cs [arrayCacheLen]*[arrayCacheLen]codecRtidFn
  1252. s []*[arrayCacheLen]codecRtidFn
  1253. sn uint32
  1254. be bool
  1255. js bool
  1256. cf [arrayCacheLen]codecRtidFn
  1257. }
  1258. func (c *codecFner) reset(hh Handle) {
  1259. c.hh = hh
  1260. c.h = hh.getBasicHandle()
  1261. _, c.js = hh.(*JsonHandle)
  1262. c.be = hh.isBinary()
  1263. }
  1264. func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
  1265. rtid := rt2id(rt)
  1266. var j uint32
  1267. var sn uint32 = c.sn
  1268. if sn == 0 {
  1269. c.s = c.cs[:1]
  1270. c.s[0] = &c.cf
  1271. c.cf[0].rtid = rtid
  1272. fn = &(c.cf[0].fn)
  1273. c.sn = 1
  1274. } else {
  1275. LOOP1:
  1276. for _, x := range c.s {
  1277. for i := range x {
  1278. if j == sn {
  1279. break LOOP1
  1280. }
  1281. if x[i].rtid == rtid {
  1282. fn = &(x[i].fn)
  1283. return
  1284. }
  1285. j++
  1286. }
  1287. }
  1288. sx, sy := sn/arrayCacheLen, sn%arrayCacheLen
  1289. if sy == 0 {
  1290. c.s = append(c.s, &[arrayCacheLen]codecRtidFn{})
  1291. }
  1292. c.s[sx][sy].rtid = rtid
  1293. fn = &(c.s[sx][sy].fn)
  1294. c.sn++
  1295. }
  1296. ti := c.h.getTypeInfo(rtid, rt)
  1297. fi := &(fn.i)
  1298. fi.ti = ti
  1299. if checkCodecSelfer && ti.cs {
  1300. fn.fe = (*Encoder).selferMarshal
  1301. fn.fd = (*Decoder).selferUnmarshal
  1302. } else if rtid == rawTypId {
  1303. fn.fe = (*Encoder).raw
  1304. fn.fd = (*Decoder).raw
  1305. } else if rtid == rawExtTypId {
  1306. fn.fe = (*Encoder).rawExt
  1307. fn.fd = (*Decoder).rawExt
  1308. fn.i.addr = true
  1309. } else if c.hh.IsBuiltinType(rtid) {
  1310. fn.fe = (*Encoder).builtin
  1311. fn.fd = (*Decoder).builtin
  1312. fn.i.addr = true
  1313. } else if xfFn := c.h.getExt(rtid); xfFn != nil {
  1314. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  1315. fn.fe = (*Encoder).ext
  1316. fn.fd = (*Decoder).ext
  1317. fn.i.addr = true
  1318. } else if supportMarshalInterfaces && c.be && ti.bm {
  1319. fn.fe = (*Encoder).binaryMarshal
  1320. fn.fd = (*Decoder).binaryUnmarshal
  1321. } else if supportMarshalInterfaces && !c.be && c.js && ti.jm {
  1322. //If JSON, we should check JSONMarshal before textMarshal
  1323. fn.fe = (*Encoder).jsonMarshal
  1324. fn.fd = (*Decoder).jsonUnmarshal
  1325. } else if supportMarshalInterfaces && !c.be && ti.tm {
  1326. fn.fe = (*Encoder).textMarshal
  1327. fn.fd = (*Decoder).textUnmarshal
  1328. } else {
  1329. rk := rt.Kind()
  1330. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  1331. if rt.PkgPath() == "" { // un-named slice or map
  1332. if idx := fastpathAV.index(rtid); idx != -1 {
  1333. fn.fe = fastpathAV[idx].encfn
  1334. fn.fd = fastpathAV[idx].decfn
  1335. fn.i.addr = true
  1336. }
  1337. } else {
  1338. // use mapping for underlying type if there
  1339. var rtu reflect.Type
  1340. if rk == reflect.Map {
  1341. rtu = reflect.MapOf(rt.Key(), rt.Elem())
  1342. } else {
  1343. rtu = reflect.SliceOf(rt.Elem())
  1344. }
  1345. rtuid := rt2id(rtu)
  1346. if idx := fastpathAV.index(rtuid); idx != -1 {
  1347. xfnf := fastpathAV[idx].encfn
  1348. xrt := fastpathAV[idx].rt
  1349. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  1350. xfnf(e, xf, xrv.Convert(xrt))
  1351. }
  1352. fn.i.addr = true
  1353. xfnf2 := fastpathAV[idx].decfn
  1354. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1355. xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
  1356. }
  1357. }
  1358. }
  1359. }
  1360. if fn.fe == nil && fn.fd == nil {
  1361. switch rk {
  1362. case reflect.Bool:
  1363. fn.fe = (*Encoder).kBool
  1364. fn.fd = (*Decoder).kBool
  1365. case reflect.String:
  1366. fn.fe = (*Encoder).kString
  1367. fn.fd = (*Decoder).kString
  1368. case reflect.Int:
  1369. fn.fd = (*Decoder).kInt
  1370. fn.fe = (*Encoder).kInt
  1371. case reflect.Int8:
  1372. fn.fe = (*Encoder).kInt
  1373. fn.fd = (*Decoder).kInt8
  1374. case reflect.Int16:
  1375. fn.fe = (*Encoder).kInt
  1376. fn.fd = (*Decoder).kInt16
  1377. case reflect.Int32:
  1378. fn.fe = (*Encoder).kInt
  1379. fn.fd = (*Decoder).kInt32
  1380. case reflect.Int64:
  1381. fn.fe = (*Encoder).kInt
  1382. fn.fd = (*Decoder).kInt64
  1383. case reflect.Uint:
  1384. fn.fd = (*Decoder).kUint
  1385. fn.fe = (*Encoder).kUint
  1386. case reflect.Uint8:
  1387. fn.fe = (*Encoder).kUint
  1388. fn.fd = (*Decoder).kUint8
  1389. case reflect.Uint16:
  1390. fn.fe = (*Encoder).kUint
  1391. fn.fd = (*Decoder).kUint16
  1392. case reflect.Uint32:
  1393. fn.fe = (*Encoder).kUint
  1394. fn.fd = (*Decoder).kUint32
  1395. case reflect.Uint64:
  1396. fn.fe = (*Encoder).kUint
  1397. fn.fd = (*Decoder).kUint64
  1398. // case reflect.Ptr:
  1399. // fn.fd = (*Decoder).kPtr
  1400. case reflect.Uintptr:
  1401. fn.fe = (*Encoder).kUint
  1402. fn.fd = (*Decoder).kUintptr
  1403. case reflect.Float32:
  1404. fn.fe = (*Encoder).kFloat32
  1405. fn.fd = (*Decoder).kFloat32
  1406. case reflect.Float64:
  1407. fn.fe = (*Encoder).kFloat64
  1408. fn.fd = (*Decoder).kFloat64
  1409. case reflect.Invalid:
  1410. fn.fe = (*Encoder).kInvalid
  1411. case reflect.Chan:
  1412. fi.seq = seqTypeChan
  1413. fn.fe = (*Encoder).kSlice
  1414. fn.fd = (*Decoder).kSlice
  1415. case reflect.Slice:
  1416. fi.seq = seqTypeSlice
  1417. fn.fe = (*Encoder).kSlice
  1418. fn.fd = (*Decoder).kSlice
  1419. case reflect.Array:
  1420. fi.seq = seqTypeArray
  1421. fn.fe = (*Encoder).kSlice
  1422. fi.addr = false
  1423. rt2 := reflect.SliceOf(rt.Elem())
  1424. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1425. // println(">>>>>> decoding an array ... ")
  1426. d.cf.get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
  1427. // println(">>>>>> decoding an array ... DONE")
  1428. }
  1429. // fn.fd = (*Decoder).kArray
  1430. case reflect.Struct:
  1431. if ti.anyOmitEmpty {
  1432. fn.fe = (*Encoder).kStruct
  1433. } else {
  1434. fn.fe = (*Encoder).kStructNoOmitempty
  1435. }
  1436. fn.fd = (*Decoder).kStruct
  1437. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  1438. // case reflect.Ptr:
  1439. // fn.fe = (*Encoder).kPtr
  1440. // case reflect.Interface:
  1441. // fn.fe = (*Encoder).kInterface
  1442. case reflect.Map:
  1443. fn.fe = (*Encoder).kMap
  1444. fn.fd = (*Decoder).kMap
  1445. case reflect.Interface:
  1446. // encode: reflect.Interface are handled already by preEncodeValue
  1447. fn.fd = (*Decoder).kInterface
  1448. default:
  1449. fn.fe = (*Encoder).kErr
  1450. fn.fd = (*Decoder).kErr
  1451. }
  1452. }
  1453. }
  1454. return
  1455. }
  1456. // ----
  1457. // these functions must be inlinable, and not call anybody
  1458. type checkOverflow struct{}
  1459. func (_ checkOverflow) Float32(f float64) (overflow bool) {
  1460. if f < 0 {
  1461. f = -f
  1462. }
  1463. return math.MaxFloat32 < f && f <= math.MaxFloat64
  1464. }
  1465. func (_ checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  1466. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1467. return
  1468. }
  1469. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1470. overflow = true
  1471. }
  1472. return
  1473. }
  1474. func (_ checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  1475. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1476. return
  1477. }
  1478. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1479. overflow = true
  1480. }
  1481. return
  1482. }
  1483. func (_ checkOverflow) SignedInt(v uint64) (i int64, overflow bool) {
  1484. //e.g. -127 to 128 for int8
  1485. pos := (v >> 63) == 0
  1486. ui2 := v & 0x7fffffffffffffff
  1487. if pos {
  1488. if ui2 > math.MaxInt64 {
  1489. overflow = true
  1490. return
  1491. }
  1492. } else {
  1493. if ui2 > math.MaxInt64-1 {
  1494. overflow = true
  1495. return
  1496. }
  1497. }
  1498. i = int64(v)
  1499. return
  1500. }
  1501. // ------------------ SORT -----------------
  1502. func isNaN(f float64) bool { return f != f }
  1503. // -----------------------
  1504. type intSlice []int64
  1505. type uintSlice []uint64
  1506. type uintptrSlice []uintptr
  1507. type floatSlice []float64
  1508. type boolSlice []bool
  1509. type stringSlice []string
  1510. type bytesSlice [][]byte
  1511. func (p intSlice) Len() int { return len(p) }
  1512. func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
  1513. func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1514. func (p uintSlice) Len() int { return len(p) }
  1515. func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
  1516. func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1517. func (p uintptrSlice) Len() int { return len(p) }
  1518. func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] }
  1519. func (p uintptrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1520. func (p floatSlice) Len() int { return len(p) }
  1521. func (p floatSlice) Less(i, j int) bool {
  1522. return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
  1523. }
  1524. func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1525. func (p stringSlice) Len() int { return len(p) }
  1526. func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
  1527. func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1528. func (p bytesSlice) Len() int { return len(p) }
  1529. func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
  1530. func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1531. func (p boolSlice) Len() int { return len(p) }
  1532. func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
  1533. func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1534. // ---------------------
  1535. type intRv struct {
  1536. v int64
  1537. r reflect.Value
  1538. }
  1539. type intRvSlice []intRv
  1540. type uintRv struct {
  1541. v uint64
  1542. r reflect.Value
  1543. }
  1544. type uintRvSlice []uintRv
  1545. type floatRv struct {
  1546. v float64
  1547. r reflect.Value
  1548. }
  1549. type floatRvSlice []floatRv
  1550. type boolRv struct {
  1551. v bool
  1552. r reflect.Value
  1553. }
  1554. type boolRvSlice []boolRv
  1555. type stringRv struct {
  1556. v string
  1557. r reflect.Value
  1558. }
  1559. type stringRvSlice []stringRv
  1560. type bytesRv struct {
  1561. v []byte
  1562. r reflect.Value
  1563. }
  1564. type bytesRvSlice []bytesRv
  1565. func (p intRvSlice) Len() int { return len(p) }
  1566. func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1567. func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1568. func (p uintRvSlice) Len() int { return len(p) }
  1569. func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1570. func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1571. func (p floatRvSlice) Len() int { return len(p) }
  1572. func (p floatRvSlice) Less(i, j int) bool {
  1573. return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
  1574. }
  1575. func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1576. func (p stringRvSlice) Len() int { return len(p) }
  1577. func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1578. func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1579. func (p bytesRvSlice) Len() int { return len(p) }
  1580. func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1581. func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1582. func (p boolRvSlice) Len() int { return len(p) }
  1583. func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
  1584. func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1585. // -----------------
  1586. type bytesI struct {
  1587. v []byte
  1588. i interface{}
  1589. }
  1590. type bytesISlice []bytesI
  1591. func (p bytesISlice) Len() int { return len(p) }
  1592. func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1593. func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1594. // -----------------
  1595. type set []uintptr
  1596. func (s *set) add(v uintptr) (exists bool) {
  1597. // e.ci is always nil, or len >= 1
  1598. x := *s
  1599. if x == nil {
  1600. x = make([]uintptr, 1, 8)
  1601. x[0] = v
  1602. *s = x
  1603. return
  1604. }
  1605. // typically, length will be 1. make this perform.
  1606. if len(x) == 1 {
  1607. if j := x[0]; j == 0 {
  1608. x[0] = v
  1609. } else if j == v {
  1610. exists = true
  1611. } else {
  1612. x = append(x, v)
  1613. *s = x
  1614. }
  1615. return
  1616. }
  1617. // check if it exists
  1618. for _, j := range x {
  1619. if j == v {
  1620. exists = true
  1621. return
  1622. }
  1623. }
  1624. // try to replace a "deleted" slot
  1625. for i, j := range x {
  1626. if j == 0 {
  1627. x[i] = v
  1628. return
  1629. }
  1630. }
  1631. // if unable to replace deleted slot, just append it.
  1632. x = append(x, v)
  1633. *s = x
  1634. return
  1635. }
  1636. func (s *set) remove(v uintptr) (exists bool) {
  1637. x := *s
  1638. if len(x) == 0 {
  1639. return
  1640. }
  1641. if len(x) == 1 {
  1642. if x[0] == v {
  1643. x[0] = 0
  1644. }
  1645. return
  1646. }
  1647. for i, j := range x {
  1648. if j == v {
  1649. exists = true
  1650. x[i] = 0 // set it to 0, as way to delete it.
  1651. // copy(x[i:], x[i+1:])
  1652. // x = x[:len(x)-1]
  1653. return
  1654. }
  1655. }
  1656. return
  1657. }
  1658. // ------
  1659. // bitset types are better than [256]bool, because they permit the whole
  1660. // bitset array being on a single cache line and use less memory.
  1661. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  1662. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  1663. type bitset256 [32]byte
  1664. func (x *bitset256) set(pos byte) {
  1665. x[pos>>3] |= (1 << (pos & 7))
  1666. }
  1667. func (x *bitset256) unset(pos byte) {
  1668. x[pos>>3] &^= (1 << (pos & 7))
  1669. }
  1670. func (x *bitset256) isset(pos byte) bool {
  1671. return x[pos>>3]&(1<<(pos&7)) != 0
  1672. }
  1673. type bitset128 [16]byte
  1674. func (x *bitset128) set(pos byte) {
  1675. x[pos>>3] |= (1 << (pos & 7))
  1676. }
  1677. func (x *bitset128) unset(pos byte) {
  1678. x[pos>>3] &^= (1 << (pos & 7))
  1679. }
  1680. func (x *bitset128) isset(pos byte) bool {
  1681. return x[pos>>3]&(1<<(pos&7)) != 0
  1682. }
  1683. // ------------
  1684. type pooler struct {
  1685. // for stringRV
  1686. strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool
  1687. // for the decNaked
  1688. dn sync.Pool
  1689. tiload sync.Pool
  1690. }
  1691. func (p *pooler) init() {
  1692. p.strRv8.New = func() interface{} { return new([8]stringRv) }
  1693. p.strRv16.New = func() interface{} { return new([16]stringRv) }
  1694. p.strRv32.New = func() interface{} { return new([32]stringRv) }
  1695. p.strRv64.New = func() interface{} { return new([64]stringRv) }
  1696. p.strRv128.New = func() interface{} { return new([128]stringRv) }
  1697. p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
  1698. p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
  1699. }
  1700. func (p *pooler) stringRv8() (sp *sync.Pool, v interface{}) {
  1701. return &p.strRv8, p.strRv8.Get()
  1702. }
  1703. func (p *pooler) stringRv16() (sp *sync.Pool, v interface{}) {
  1704. return &p.strRv16, p.strRv16.Get()
  1705. }
  1706. func (p *pooler) stringRv32() (sp *sync.Pool, v interface{}) {
  1707. return &p.strRv32, p.strRv32.Get()
  1708. }
  1709. func (p *pooler) stringRv64() (sp *sync.Pool, v interface{}) {
  1710. return &p.strRv64, p.strRv64.Get()
  1711. }
  1712. func (p *pooler) stringRv128() (sp *sync.Pool, v interface{}) {
  1713. return &p.strRv128, p.strRv128.Get()
  1714. }
  1715. func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
  1716. return &p.dn, p.dn.Get()
  1717. }
  1718. func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
  1719. return &p.tiload, p.tiload.Get()
  1720. }