helper.go 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944
  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. hasElemSeparators() bool
  461. IsBuiltinType(rtid uintptr) bool
  462. }
  463. // Raw represents raw formatted bytes.
  464. // We "blindly" store it during encode and store the raw bytes during decode.
  465. // Note: it is dangerous during encode, so we may gate the behaviour behind an Encode flag which must be explicitly set.
  466. type Raw []byte
  467. // RawExt represents raw unprocessed extension data.
  468. // Some codecs will decode extension data as a *RawExt if there is no registered extension for the tag.
  469. //
  470. // Only one of Data or Value is nil. If Data is nil, then the content of the RawExt is in the Value.
  471. type RawExt struct {
  472. Tag uint64
  473. // Data is the []byte which represents the raw ext. If Data is nil, ext is exposed in Value.
  474. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types
  475. Data []byte
  476. // Value represents the extension, if Data is nil.
  477. // Value is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  478. Value interface{}
  479. }
  480. // BytesExt handles custom (de)serialization of types to/from []byte.
  481. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  482. type BytesExt interface {
  483. // WriteExt converts a value to a []byte.
  484. //
  485. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  486. WriteExt(v interface{}) []byte
  487. // ReadExt updates a value from a []byte.
  488. ReadExt(dst interface{}, src []byte)
  489. }
  490. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  491. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  492. //
  493. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  494. type InterfaceExt interface {
  495. // ConvertExt converts a value into a simpler interface for easy encoding e.g. convert time.Time to int64.
  496. //
  497. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  498. ConvertExt(v interface{}) interface{}
  499. // UpdateExt updates a value from a simpler interface for easy decoding e.g. convert int64 to time.Time.
  500. UpdateExt(dst interface{}, src interface{})
  501. }
  502. // Ext handles custom (de)serialization of custom types / extensions.
  503. type Ext interface {
  504. BytesExt
  505. InterfaceExt
  506. }
  507. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  508. type addExtWrapper struct {
  509. encFn func(reflect.Value) ([]byte, error)
  510. decFn func(reflect.Value, []byte) error
  511. }
  512. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  513. bs, err := x.encFn(reflect.ValueOf(v))
  514. if err != nil {
  515. panic(err)
  516. }
  517. return bs
  518. }
  519. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  520. if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
  521. panic(err)
  522. }
  523. }
  524. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  525. return x.WriteExt(v)
  526. }
  527. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  528. x.ReadExt(dest, v.([]byte))
  529. }
  530. type setExtWrapper struct {
  531. b BytesExt
  532. i InterfaceExt
  533. }
  534. func (x *setExtWrapper) WriteExt(v interface{}) []byte {
  535. if x.b == nil {
  536. panic("BytesExt.WriteExt is not supported")
  537. }
  538. return x.b.WriteExt(v)
  539. }
  540. func (x *setExtWrapper) ReadExt(v interface{}, bs []byte) {
  541. if x.b == nil {
  542. panic("BytesExt.WriteExt is not supported")
  543. }
  544. x.b.ReadExt(v, bs)
  545. }
  546. func (x *setExtWrapper) ConvertExt(v interface{}) interface{} {
  547. if x.i == nil {
  548. panic("InterfaceExt.ConvertExt is not supported")
  549. }
  550. return x.i.ConvertExt(v)
  551. }
  552. func (x *setExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  553. if x.i == nil {
  554. panic("InterfaceExxt.UpdateExt is not supported")
  555. }
  556. x.i.UpdateExt(dest, v)
  557. }
  558. type binaryEncodingType struct{}
  559. func (_ binaryEncodingType) isBinary() bool { return true }
  560. type textEncodingType struct{}
  561. func (_ textEncodingType) isBinary() bool { return false }
  562. // noBuiltInTypes is embedded into many types which do not support builtins
  563. // e.g. msgpack, simple, cbor.
  564. type noBuiltInTypeChecker struct{}
  565. func (_ noBuiltInTypeChecker) IsBuiltinType(rt uintptr) bool { return false }
  566. type noBuiltInTypes struct{ noBuiltInTypeChecker }
  567. func (_ noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  568. func (_ noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  569. // type noStreamingCodec struct{}
  570. // func (_ noStreamingCodec) CheckBreak() bool { return false }
  571. // func (_ noStreamingCodec) hasElemSeparators() bool { return false }
  572. type noElemSeparators struct{}
  573. func (_ noElemSeparators) hasElemSeparators() (v bool) { return }
  574. // bigenHelper.
  575. // Users must already slice the x completely, because we will not reslice.
  576. type bigenHelper struct {
  577. x []byte // must be correctly sliced to appropriate len. slicing is a cost.
  578. w encWriter
  579. }
  580. func (z bigenHelper) writeUint16(v uint16) {
  581. bigen.PutUint16(z.x, v)
  582. z.w.writeb(z.x)
  583. }
  584. func (z bigenHelper) writeUint32(v uint32) {
  585. bigen.PutUint32(z.x, v)
  586. z.w.writeb(z.x)
  587. }
  588. func (z bigenHelper) writeUint64(v uint64) {
  589. bigen.PutUint64(z.x, v)
  590. z.w.writeb(z.x)
  591. }
  592. type extTypeTagFn struct {
  593. rtid uintptr
  594. rt reflect.Type
  595. tag uint64
  596. ext Ext
  597. }
  598. type extHandle []extTypeTagFn
  599. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  600. //
  601. // AddExt registes an encode and decode function for a reflect.Type.
  602. // AddExt internally calls SetExt.
  603. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  604. func (o *extHandle) AddExt(
  605. rt reflect.Type, tag byte,
  606. encfn func(reflect.Value) ([]byte, error), decfn func(reflect.Value, []byte) error,
  607. ) (err error) {
  608. if encfn == nil || decfn == nil {
  609. return o.SetExt(rt, uint64(tag), nil)
  610. }
  611. return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  612. }
  613. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  614. //
  615. // Note that the type must be a named type, and specifically not
  616. // a pointer or Interface. An error is returned if that is not honored.
  617. //
  618. // To Deregister an ext, call SetExt with nil Ext
  619. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  620. // o is a pointer, because we may need to initialize it
  621. if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
  622. err = fmt.Errorf("codec.Handle.AddExt: Takes named type, not a pointer or interface: %T",
  623. reflect.Zero(rt).Interface())
  624. return
  625. }
  626. rtid := rt2id(rt)
  627. for _, v := range *o {
  628. if v.rtid == rtid {
  629. v.tag, v.ext = tag, ext
  630. return
  631. }
  632. }
  633. if *o == nil {
  634. *o = make([]extTypeTagFn, 0, 4)
  635. }
  636. *o = append(*o, extTypeTagFn{rtid, rt, tag, ext})
  637. return
  638. }
  639. func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
  640. var v *extTypeTagFn
  641. for i := range o {
  642. v = &o[i]
  643. if v.rtid == rtid {
  644. return v
  645. }
  646. }
  647. return nil
  648. }
  649. func (o extHandle) getExtForTag(tag uint64) *extTypeTagFn {
  650. var v *extTypeTagFn
  651. for i := range o {
  652. v = &o[i]
  653. if v.tag == tag {
  654. return v
  655. }
  656. }
  657. return nil
  658. }
  659. const maxLevelsEmbedding = 16
  660. type structFieldInfo struct {
  661. encName string // encode name
  662. fieldName string // field name
  663. is [maxLevelsEmbedding]uint16 // (recursive/embedded) field index in struct
  664. nis uint8 // num levels of embedding. if 1, then it's not embedded.
  665. omitEmpty bool
  666. toArray bool // if field is _struct, is the toArray set?
  667. }
  668. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  669. if v, valid := si.field(v, false); valid {
  670. v.Set(reflect.Zero(v.Type()))
  671. }
  672. }
  673. // rv returns the field of the struct.
  674. // If anonymous, it returns an Invalid
  675. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value, valid bool) {
  676. // replicate FieldByIndex
  677. for i, x := range si.is {
  678. if uint8(i) == si.nis {
  679. break
  680. }
  681. if v, valid = baseStructRv(v, update); !valid {
  682. return
  683. }
  684. v = v.Field(int(x))
  685. }
  686. return v, true
  687. }
  688. func (si *structFieldInfo) fieldval(v reflect.Value, update bool) reflect.Value {
  689. v, _ = si.field(v, update)
  690. return v
  691. }
  692. func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
  693. // if fname == "" {
  694. // panic(noFieldNameToStructFieldInfoErr)
  695. // }
  696. si := structFieldInfo{
  697. encName: fname,
  698. }
  699. if stag != "" {
  700. for i, s := range strings.Split(stag, ",") {
  701. if i == 0 {
  702. if s != "" {
  703. si.encName = s
  704. }
  705. } else {
  706. if s == "omitempty" {
  707. si.omitEmpty = true
  708. } else if s == "toarray" {
  709. si.toArray = true
  710. }
  711. }
  712. }
  713. }
  714. // si.encNameBs = []byte(si.encName)
  715. return &si
  716. }
  717. type sfiSortedByEncName []*structFieldInfo
  718. func (p sfiSortedByEncName) Len() int {
  719. return len(p)
  720. }
  721. func (p sfiSortedByEncName) Less(i, j int) bool {
  722. return p[i].encName < p[j].encName
  723. }
  724. func (p sfiSortedByEncName) Swap(i, j int) {
  725. p[i], p[j] = p[j], p[i]
  726. }
  727. const structFieldNodeNumToCache = 4
  728. type structFieldNodeCache struct {
  729. rv [structFieldNodeNumToCache]reflect.Value
  730. idx [structFieldNodeNumToCache]uint32
  731. num uint8
  732. }
  733. func (x *structFieldNodeCache) get(key uint32) (fv reflect.Value, valid bool) {
  734. // defer func() { fmt.Printf(">>>> found in cache2? %v\n", valid) }()
  735. for i, k := range &x.idx {
  736. if uint8(i) == x.num {
  737. return // break
  738. }
  739. if key == k {
  740. return x.rv[i], true
  741. }
  742. }
  743. return
  744. }
  745. func (x *structFieldNodeCache) tryAdd(fv reflect.Value, key uint32) {
  746. if x.num < structFieldNodeNumToCache {
  747. x.rv[x.num] = fv
  748. x.idx[x.num] = key
  749. x.num++
  750. return
  751. }
  752. }
  753. type structFieldNode struct {
  754. v reflect.Value
  755. cache2 structFieldNodeCache
  756. cache3 structFieldNodeCache
  757. update bool
  758. }
  759. func (x *structFieldNode) field(si *structFieldInfo) (fv reflect.Value) {
  760. // return si.fieldval(x.v, x.update)
  761. // Note: we only cache if nis=2 or nis=3 i.e. up to 2 levels of embedding
  762. // This mostly saves us time on the repeated calls to v.Elem, v.Field, etc.
  763. var valid bool
  764. switch si.nis {
  765. case 1:
  766. fv = x.v.Field(int(si.is[0]))
  767. case 2:
  768. if fv, valid = x.cache2.get(uint32(si.is[0])); valid {
  769. fv = fv.Field(int(si.is[1]))
  770. return
  771. }
  772. fv = x.v.Field(int(si.is[0]))
  773. if fv, valid = baseStructRv(fv, x.update); !valid {
  774. return
  775. }
  776. x.cache2.tryAdd(fv, uint32(si.is[0]))
  777. fv = fv.Field(int(si.is[1]))
  778. case 3:
  779. var key uint32 = uint32(si.is[0])<<16 | uint32(si.is[1])
  780. if fv, valid = x.cache3.get(key); valid {
  781. fv = fv.Field(int(si.is[2]))
  782. return
  783. }
  784. fv = x.v.Field(int(si.is[0]))
  785. if fv, valid = baseStructRv(fv, x.update); !valid {
  786. return
  787. }
  788. fv = fv.Field(int(si.is[1]))
  789. if fv, valid = baseStructRv(fv, x.update); !valid {
  790. return
  791. }
  792. x.cache3.tryAdd(fv, key)
  793. fv = fv.Field(int(si.is[2]))
  794. default:
  795. fv, _ = si.field(x.v, x.update)
  796. }
  797. return
  798. }
  799. func baseStructRv(v reflect.Value, update bool) (v2 reflect.Value, valid bool) {
  800. for v.Kind() == reflect.Ptr {
  801. if v.IsNil() {
  802. if !update {
  803. return
  804. }
  805. v.Set(reflect.New(v.Type().Elem()))
  806. }
  807. v = v.Elem()
  808. }
  809. return v, true
  810. }
  811. // typeInfo keeps information about each type referenced in the encode/decode sequence.
  812. //
  813. // During an encode/decode sequence, we work as below:
  814. // - If base is a built in type, en/decode base value
  815. // - If base is registered as an extension, en/decode base value
  816. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  817. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  818. // - Else decode appropriately based on the reflect.Kind
  819. type typeInfo struct {
  820. sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
  821. sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  822. rt reflect.Type
  823. rtid uintptr
  824. // rv0 reflect.Value // saved zero value, used if immutableKind
  825. numMeth uint16 // number of methods
  826. // baseId gives pointer to the base reflect.Type, after deferencing
  827. // the pointers. E.g. base type of ***time.Time is time.Time.
  828. base reflect.Type
  829. baseId uintptr
  830. baseIndir int8 // number of indirections to get to base
  831. anyOmitEmpty bool
  832. mbs bool // base type (T or *T) is a MapBySlice
  833. bm bool // base type (T or *T) is a binaryMarshaler
  834. bunm bool // base type (T or *T) is a binaryUnmarshaler
  835. bmIndir int8 // number of indirections to get to binaryMarshaler type
  836. bunmIndir int8 // number of indirections to get to binaryUnmarshaler type
  837. tm bool // base type (T or *T) is a textMarshaler
  838. tunm bool // base type (T or *T) is a textUnmarshaler
  839. tmIndir int8 // number of indirections to get to textMarshaler type
  840. tunmIndir int8 // number of indirections to get to textUnmarshaler type
  841. jm bool // base type (T or *T) is a jsonMarshaler
  842. junm bool // base type (T or *T) is a jsonUnmarshaler
  843. jmIndir int8 // number of indirections to get to jsonMarshaler type
  844. junmIndir int8 // number of indirections to get to jsonUnmarshaler type
  845. cs bool // base type (T or *T) is a Selfer
  846. csIndir int8 // number of indirections to get to Selfer type
  847. toArray bool // whether this (struct) type should be encoded as an array
  848. }
  849. // define length beyond which we do a binary search instead of a linear search.
  850. // From our testing, linear search seems faster than binary search up to 16-field structs.
  851. // However, we set to 8 similar to what python does for hashtables.
  852. const indexForEncNameBinarySearchThreshold = 8
  853. func (ti *typeInfo) indexForEncName(name string) int {
  854. // NOTE: name may be a stringView, so don't pass it to another function.
  855. //tisfi := ti.sfi
  856. sfilen := len(ti.sfi)
  857. if sfilen < indexForEncNameBinarySearchThreshold {
  858. for i, si := range ti.sfi {
  859. if si.encName == name {
  860. return i
  861. }
  862. }
  863. return -1
  864. }
  865. // binary search. adapted from sort/search.go.
  866. h, i, j := 0, 0, sfilen
  867. for i < j {
  868. h = i + (j-i)/2
  869. if ti.sfi[h].encName < name {
  870. i = h + 1
  871. } else {
  872. j = h
  873. }
  874. }
  875. if i < sfilen && ti.sfi[i].encName == name {
  876. return i
  877. }
  878. return -1
  879. }
  880. type rtid2ti struct {
  881. rtid uintptr
  882. ti *typeInfo
  883. }
  884. // TypeInfos caches typeInfo for each type on first inspection.
  885. //
  886. // It is configured with a set of tag keys, which are used to get
  887. // configuration for the type.
  888. type TypeInfos struct {
  889. infos atomicTypeInfoSlice // formerly map[uintptr]*typeInfo, now *[]rtid2ti
  890. mu sync.Mutex
  891. tags []string
  892. }
  893. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  894. //
  895. // This allows users customize the struct tag keys which contain configuration
  896. // of their types.
  897. func NewTypeInfos(tags []string) *TypeInfos {
  898. return &TypeInfos{tags: tags}
  899. }
  900. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  901. // check for tags: codec, json, in that order.
  902. // this allows seamless support for many configured structs.
  903. for _, x := range x.tags {
  904. s = t.Get(x)
  905. if s != "" {
  906. return s
  907. }
  908. }
  909. return
  910. }
  911. func (x *TypeInfos) find(sp *[]rtid2ti, rtid uintptr) (idx int, ti *typeInfo) {
  912. // binary search. adapted from sort/search.go.
  913. // if sp == nil {
  914. // return -1, nil
  915. // }
  916. s := *sp
  917. h, i, j := 0, 0, len(s)
  918. for i < j {
  919. h = i + (j-i)/2
  920. if s[h].rtid < rtid {
  921. i = h + 1
  922. } else {
  923. j = h
  924. }
  925. }
  926. if i < len(s) && s[i].rtid == rtid {
  927. return i, s[i].ti
  928. }
  929. return i, nil
  930. }
  931. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  932. sp := x.infos.load()
  933. var idx int
  934. if sp != nil {
  935. idx, pti = x.find(sp, rtid)
  936. if pti != nil {
  937. return
  938. }
  939. }
  940. // do not hold lock while computing this.
  941. // it may lead to duplication, but that's ok.
  942. ti := typeInfo{rt: rt, rtid: rtid}
  943. // ti.rv0 = reflect.Zero(rt)
  944. ti.numMeth = uint16(rt.NumMethod())
  945. var ok bool
  946. var indir int8
  947. if ok, indir = implementsIntf(rt, binaryMarshalerTyp); ok {
  948. ti.bm, ti.bmIndir = true, indir
  949. }
  950. if ok, indir = implementsIntf(rt, binaryUnmarshalerTyp); ok {
  951. ti.bunm, ti.bunmIndir = true, indir
  952. }
  953. if ok, indir = implementsIntf(rt, textMarshalerTyp); ok {
  954. ti.tm, ti.tmIndir = true, indir
  955. }
  956. if ok, indir = implementsIntf(rt, textUnmarshalerTyp); ok {
  957. ti.tunm, ti.tunmIndir = true, indir
  958. }
  959. if ok, indir = implementsIntf(rt, jsonMarshalerTyp); ok {
  960. ti.jm, ti.jmIndir = true, indir
  961. }
  962. if ok, indir = implementsIntf(rt, jsonUnmarshalerTyp); ok {
  963. ti.junm, ti.junmIndir = true, indir
  964. }
  965. if ok, indir = implementsIntf(rt, selferTyp); ok {
  966. ti.cs, ti.csIndir = true, indir
  967. }
  968. if ok, _ = implementsIntf(rt, mapBySliceTyp); ok {
  969. ti.mbs = true
  970. }
  971. pt := rt
  972. var ptIndir int8
  973. // for ; pt.Kind() == reflect.Ptr; pt, ptIndir = pt.Elem(), ptIndir+1 { }
  974. for pt.Kind() == reflect.Ptr {
  975. pt = pt.Elem()
  976. ptIndir++
  977. }
  978. if ptIndir == 0 {
  979. ti.base = rt
  980. ti.baseId = rtid
  981. } else {
  982. ti.base = pt
  983. ti.baseId = rt2id(pt)
  984. ti.baseIndir = ptIndir
  985. }
  986. if rt.Kind() == reflect.Struct {
  987. var omitEmpty bool
  988. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  989. siInfo := parseStructFieldInfo(structInfoFieldName, x.structTag(f.Tag))
  990. ti.toArray = siInfo.toArray
  991. omitEmpty = siInfo.omitEmpty
  992. }
  993. pp, pi := pool.tiLoad()
  994. pv := pi.(*typeInfoLoadArray)
  995. pv.etypes[0] = ti.baseId
  996. vv := typeInfoLoad{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  997. x.rget(rt, rtid, omitEmpty, nil, &vv)
  998. ti.sfip, ti.sfi, ti.anyOmitEmpty = rgetResolveSFI(vv.sfis, pv.sfiidx[:0])
  999. pp.Put(pi)
  1000. }
  1001. // sfi = sfip
  1002. var vs []rtid2ti
  1003. x.mu.Lock()
  1004. sp = x.infos.load()
  1005. if sp == nil {
  1006. pti = &ti
  1007. vs = []rtid2ti{{rtid, pti}}
  1008. x.infos.store(&vs)
  1009. } else {
  1010. idx, pti = x.find(sp, rtid)
  1011. if pti == nil {
  1012. s := *sp
  1013. pti = &ti
  1014. vs = make([]rtid2ti, len(s)+1)
  1015. copy(vs, s[:idx])
  1016. vs[idx] = rtid2ti{rtid, pti}
  1017. copy(vs[idx+1:], s[idx:])
  1018. x.infos.store(&vs)
  1019. }
  1020. }
  1021. x.mu.Unlock()
  1022. return
  1023. }
  1024. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  1025. indexstack []uint16, pv *typeInfoLoad,
  1026. ) {
  1027. // Read up fields and store how to access the value.
  1028. //
  1029. // It uses go's rules for message selectors,
  1030. // which say that the field with the shallowest depth is selected.
  1031. //
  1032. // Note: we consciously use slices, not a map, to simulate a set.
  1033. // Typically, types have < 16 fields,
  1034. // and iteration using equals is faster than maps there
  1035. flen := rt.NumField()
  1036. if flen > (1<<maxLevelsEmbedding - 1) {
  1037. panic(fmt.Errorf("codec: types with more than %v fields are not supported - has %v fields", (1<<maxLevelsEmbedding - 1), flen))
  1038. }
  1039. LOOP:
  1040. for j, jlen := uint16(0), uint16(flen); j < jlen; j++ {
  1041. f := rt.Field(int(j))
  1042. fkind := f.Type.Kind()
  1043. // skip if a func type, or is unexported, or structTag value == "-"
  1044. switch fkind {
  1045. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  1046. continue LOOP
  1047. }
  1048. // if r1, _ := utf8.DecodeRuneInString(f.Name);
  1049. // r1 == utf8.RuneError || !unicode.IsUpper(r1) {
  1050. if f.PkgPath != "" && !f.Anonymous { // unexported, not embedded
  1051. continue
  1052. }
  1053. stag := x.structTag(f.Tag)
  1054. if stag == "-" {
  1055. continue
  1056. }
  1057. var si *structFieldInfo
  1058. // if anonymous and no struct tag (or it's blank),
  1059. // and a struct (or pointer to struct), inline it.
  1060. if f.Anonymous && fkind != reflect.Interface {
  1061. doInline := stag == ""
  1062. if !doInline {
  1063. si = parseStructFieldInfo("", stag)
  1064. doInline = si.encName == ""
  1065. // doInline = si.isZero()
  1066. }
  1067. if doInline {
  1068. ft := f.Type
  1069. for ft.Kind() == reflect.Ptr {
  1070. ft = ft.Elem()
  1071. }
  1072. if ft.Kind() == reflect.Struct {
  1073. // if etypes contains this, don't call rget again (as fields are already seen here)
  1074. ftid := rt2id(ft)
  1075. // We cannot recurse forever, but we need to track other field depths.
  1076. // So - we break if we see a type twice (not the first time).
  1077. // This should be sufficient to handle an embedded type that refers to its
  1078. // owning type, which then refers to its embedded type.
  1079. processIt := true
  1080. numk := 0
  1081. for _, k := range pv.etypes {
  1082. if k == ftid {
  1083. numk++
  1084. if numk == rgetMaxRecursion {
  1085. processIt = false
  1086. break
  1087. }
  1088. }
  1089. }
  1090. if processIt {
  1091. pv.etypes = append(pv.etypes, ftid)
  1092. indexstack2 := make([]uint16, len(indexstack)+1)
  1093. copy(indexstack2, indexstack)
  1094. indexstack2[len(indexstack)] = j
  1095. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  1096. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  1097. }
  1098. continue
  1099. }
  1100. }
  1101. }
  1102. // after the anonymous dance: if an unexported field, skip
  1103. if f.PkgPath != "" { // unexported
  1104. continue
  1105. }
  1106. if f.Name == "" {
  1107. panic(noFieldNameToStructFieldInfoErr)
  1108. }
  1109. pv.fNames = append(pv.fNames, f.Name)
  1110. if si == nil {
  1111. si = parseStructFieldInfo(f.Name, stag)
  1112. } else if si.encName == "" {
  1113. si.encName = f.Name
  1114. }
  1115. si.fieldName = f.Name
  1116. pv.encNames = append(pv.encNames, si.encName)
  1117. // si.ikind = int(f.Type.Kind())
  1118. if len(indexstack) > maxLevelsEmbedding-1 {
  1119. panic(fmt.Errorf("codec: only supports up to %v depth of embedding - type has %v depth", maxLevelsEmbedding-1, len(indexstack)))
  1120. }
  1121. si.nis = uint8(len(indexstack)) + 1
  1122. copy(si.is[:], indexstack)
  1123. si.is[len(indexstack)] = j
  1124. if omitEmpty {
  1125. si.omitEmpty = true
  1126. }
  1127. pv.sfis = append(pv.sfis, si)
  1128. }
  1129. }
  1130. // resolves the struct field info got from a call to rget.
  1131. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  1132. func rgetResolveSFI(x []*structFieldInfo, pv []sfiIdx) (y, z []*structFieldInfo, anyOmitEmpty bool) {
  1133. var n int
  1134. for i, v := range x {
  1135. xn := v.encName // TODO: fieldName or encName? use encName for now.
  1136. var found bool
  1137. for j, k := range pv {
  1138. if k.name == xn {
  1139. // one of them must be reset to nil, and the index updated appropriately to the other one
  1140. if v.nis == x[k.index].nis {
  1141. } else if v.nis < x[k.index].nis {
  1142. pv[j].index = i
  1143. if x[k.index] != nil {
  1144. x[k.index] = nil
  1145. n++
  1146. }
  1147. } else {
  1148. if x[i] != nil {
  1149. x[i] = nil
  1150. n++
  1151. }
  1152. }
  1153. found = true
  1154. break
  1155. }
  1156. }
  1157. if !found {
  1158. pv = append(pv, sfiIdx{xn, i})
  1159. }
  1160. }
  1161. // remove all the nils
  1162. y = make([]*structFieldInfo, len(x)-n)
  1163. n = 0
  1164. for _, v := range x {
  1165. if v == nil {
  1166. continue
  1167. }
  1168. if !anyOmitEmpty && v.omitEmpty {
  1169. anyOmitEmpty = true
  1170. }
  1171. y[n] = v
  1172. n++
  1173. }
  1174. z = make([]*structFieldInfo, len(y))
  1175. copy(z, y)
  1176. sort.Sort(sfiSortedByEncName(z))
  1177. return
  1178. }
  1179. func xprintf(format string, a ...interface{}) {
  1180. if xDebug {
  1181. fmt.Fprintf(os.Stderr, format, a...)
  1182. }
  1183. }
  1184. func panicToErr(err *error) {
  1185. if recoverPanicToErr {
  1186. if x := recover(); x != nil {
  1187. // if false && xDebug {
  1188. // fmt.Printf("panic'ing with: %v\n", x)
  1189. // debug.PrintStack()
  1190. // }
  1191. panicValToErr(x, err)
  1192. }
  1193. }
  1194. }
  1195. func panicToErrs2(err1, err2 *error) {
  1196. if recoverPanicToErr {
  1197. if x := recover(); x != nil {
  1198. panicValToErr(x, err1)
  1199. panicValToErr(x, err2)
  1200. }
  1201. }
  1202. }
  1203. // func doPanic(tag string, format string, params ...interface{}) {
  1204. // params2 := make([]interface{}, len(params)+1)
  1205. // params2[0] = tag
  1206. // copy(params2[1:], params)
  1207. // panic(fmt.Errorf("%s: "+format, params2...))
  1208. // }
  1209. func isImmutableKind(k reflect.Kind) (v bool) {
  1210. return immutableKindsSet[k]
  1211. // return false ||
  1212. // k == reflect.Int ||
  1213. // k == reflect.Int8 ||
  1214. // k == reflect.Int16 ||
  1215. // k == reflect.Int32 ||
  1216. // k == reflect.Int64 ||
  1217. // k == reflect.Uint ||
  1218. // k == reflect.Uint8 ||
  1219. // k == reflect.Uint16 ||
  1220. // k == reflect.Uint32 ||
  1221. // k == reflect.Uint64 ||
  1222. // k == reflect.Uintptr ||
  1223. // k == reflect.Float32 ||
  1224. // k == reflect.Float64 ||
  1225. // k == reflect.Bool ||
  1226. // k == reflect.String
  1227. }
  1228. // ----
  1229. type codecFnInfo struct {
  1230. ti *typeInfo
  1231. xfFn Ext
  1232. xfTag uint64
  1233. seq seqType
  1234. addr bool
  1235. }
  1236. // codecFn encapsulates the captured variables and the encode function.
  1237. // This way, we only do some calculations one times, and pass to the
  1238. // code block that should be called (encapsulated in a function)
  1239. // instead of executing the checks every time.
  1240. type codecFn struct {
  1241. i codecFnInfo
  1242. fe func(*Encoder, *codecFnInfo, reflect.Value)
  1243. fd func(*Decoder, *codecFnInfo, reflect.Value)
  1244. }
  1245. type codecRtidFn struct {
  1246. rtid uintptr
  1247. fn codecFn
  1248. }
  1249. type codecFner struct {
  1250. hh Handle
  1251. h *BasicHandle
  1252. cs [arrayCacheLen]*[arrayCacheLen]codecRtidFn
  1253. s []*[arrayCacheLen]codecRtidFn
  1254. sn uint32
  1255. be bool
  1256. js bool
  1257. cf [arrayCacheLen]codecRtidFn
  1258. }
  1259. func (c *codecFner) reset(hh Handle) {
  1260. c.hh = hh
  1261. c.h = hh.getBasicHandle()
  1262. _, c.js = hh.(*JsonHandle)
  1263. c.be = hh.isBinary()
  1264. }
  1265. func (c *codecFner) get(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *codecFn) {
  1266. rtid := rt2id(rt)
  1267. var j uint32
  1268. var sn uint32 = c.sn
  1269. if sn == 0 {
  1270. c.s = c.cs[:1]
  1271. c.s[0] = &c.cf
  1272. c.cf[0].rtid = rtid
  1273. fn = &(c.cf[0].fn)
  1274. c.sn = 1
  1275. } else {
  1276. LOOP1:
  1277. for _, x := range c.s {
  1278. for i := range x {
  1279. if j == sn {
  1280. break LOOP1
  1281. }
  1282. if x[i].rtid == rtid {
  1283. fn = &(x[i].fn)
  1284. return
  1285. }
  1286. j++
  1287. }
  1288. }
  1289. sx, sy := sn/arrayCacheLen, sn%arrayCacheLen
  1290. if sy == 0 {
  1291. c.s = append(c.s, &[arrayCacheLen]codecRtidFn{})
  1292. }
  1293. c.s[sx][sy].rtid = rtid
  1294. fn = &(c.s[sx][sy].fn)
  1295. c.sn++
  1296. }
  1297. ti := c.h.getTypeInfo(rtid, rt)
  1298. fi := &(fn.i)
  1299. fi.ti = ti
  1300. if checkCodecSelfer && ti.cs {
  1301. fn.fe = (*Encoder).selferMarshal
  1302. fn.fd = (*Decoder).selferUnmarshal
  1303. } else if rtid == rawTypId {
  1304. fn.fe = (*Encoder).raw
  1305. fn.fd = (*Decoder).raw
  1306. } else if rtid == rawExtTypId {
  1307. fn.fe = (*Encoder).rawExt
  1308. fn.fd = (*Decoder).rawExt
  1309. fn.i.addr = true
  1310. } else if c.hh.IsBuiltinType(rtid) {
  1311. fn.fe = (*Encoder).builtin
  1312. fn.fd = (*Decoder).builtin
  1313. fn.i.addr = true
  1314. } else if xfFn := c.h.getExt(rtid); xfFn != nil {
  1315. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  1316. fn.fe = (*Encoder).ext
  1317. fn.fd = (*Decoder).ext
  1318. fn.i.addr = true
  1319. } else if supportMarshalInterfaces && c.be && ti.bm {
  1320. fn.fe = (*Encoder).binaryMarshal
  1321. fn.fd = (*Decoder).binaryUnmarshal
  1322. } else if supportMarshalInterfaces && !c.be && c.js && ti.jm {
  1323. //If JSON, we should check JSONMarshal before textMarshal
  1324. fn.fe = (*Encoder).jsonMarshal
  1325. fn.fd = (*Decoder).jsonUnmarshal
  1326. } else if supportMarshalInterfaces && !c.be && ti.tm {
  1327. fn.fe = (*Encoder).textMarshal
  1328. fn.fd = (*Decoder).textUnmarshal
  1329. } else {
  1330. rk := rt.Kind()
  1331. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  1332. if rt.PkgPath() == "" { // un-named slice or map
  1333. if idx := fastpathAV.index(rtid); idx != -1 {
  1334. fn.fe = fastpathAV[idx].encfn
  1335. fn.fd = fastpathAV[idx].decfn
  1336. fn.i.addr = true
  1337. }
  1338. } else {
  1339. // use mapping for underlying type if there
  1340. var rtu reflect.Type
  1341. if rk == reflect.Map {
  1342. rtu = reflect.MapOf(rt.Key(), rt.Elem())
  1343. } else {
  1344. rtu = reflect.SliceOf(rt.Elem())
  1345. }
  1346. rtuid := rt2id(rtu)
  1347. if idx := fastpathAV.index(rtuid); idx != -1 {
  1348. xfnf := fastpathAV[idx].encfn
  1349. xrt := fastpathAV[idx].rt
  1350. fn.fe = func(e *Encoder, xf *codecFnInfo, xrv reflect.Value) {
  1351. xfnf(e, xf, xrv.Convert(xrt))
  1352. }
  1353. fn.i.addr = true
  1354. xfnf2 := fastpathAV[idx].decfn
  1355. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1356. xfnf2(d, xf, xrv.Convert(reflect.PtrTo(xrt)))
  1357. }
  1358. }
  1359. }
  1360. }
  1361. if fn.fe == nil && fn.fd == nil {
  1362. switch rk {
  1363. case reflect.Bool:
  1364. fn.fe = (*Encoder).kBool
  1365. fn.fd = (*Decoder).kBool
  1366. case reflect.String:
  1367. fn.fe = (*Encoder).kString
  1368. fn.fd = (*Decoder).kString
  1369. case reflect.Int:
  1370. fn.fd = (*Decoder).kInt
  1371. fn.fe = (*Encoder).kInt
  1372. case reflect.Int8:
  1373. fn.fe = (*Encoder).kInt
  1374. fn.fd = (*Decoder).kInt8
  1375. case reflect.Int16:
  1376. fn.fe = (*Encoder).kInt
  1377. fn.fd = (*Decoder).kInt16
  1378. case reflect.Int32:
  1379. fn.fe = (*Encoder).kInt
  1380. fn.fd = (*Decoder).kInt32
  1381. case reflect.Int64:
  1382. fn.fe = (*Encoder).kInt
  1383. fn.fd = (*Decoder).kInt64
  1384. case reflect.Uint:
  1385. fn.fd = (*Decoder).kUint
  1386. fn.fe = (*Encoder).kUint
  1387. case reflect.Uint8:
  1388. fn.fe = (*Encoder).kUint
  1389. fn.fd = (*Decoder).kUint8
  1390. case reflect.Uint16:
  1391. fn.fe = (*Encoder).kUint
  1392. fn.fd = (*Decoder).kUint16
  1393. case reflect.Uint32:
  1394. fn.fe = (*Encoder).kUint
  1395. fn.fd = (*Decoder).kUint32
  1396. case reflect.Uint64:
  1397. fn.fe = (*Encoder).kUint
  1398. fn.fd = (*Decoder).kUint64
  1399. // case reflect.Ptr:
  1400. // fn.fd = (*Decoder).kPtr
  1401. case reflect.Uintptr:
  1402. fn.fe = (*Encoder).kUint
  1403. fn.fd = (*Decoder).kUintptr
  1404. case reflect.Float32:
  1405. fn.fe = (*Encoder).kFloat32
  1406. fn.fd = (*Decoder).kFloat32
  1407. case reflect.Float64:
  1408. fn.fe = (*Encoder).kFloat64
  1409. fn.fd = (*Decoder).kFloat64
  1410. case reflect.Invalid:
  1411. fn.fe = (*Encoder).kInvalid
  1412. case reflect.Chan:
  1413. fi.seq = seqTypeChan
  1414. fn.fe = (*Encoder).kSlice
  1415. fn.fd = (*Decoder).kSlice
  1416. case reflect.Slice:
  1417. fi.seq = seqTypeSlice
  1418. fn.fe = (*Encoder).kSlice
  1419. fn.fd = (*Decoder).kSlice
  1420. case reflect.Array:
  1421. fi.seq = seqTypeArray
  1422. fn.fe = (*Encoder).kSlice
  1423. fi.addr = false
  1424. rt2 := reflect.SliceOf(rt.Elem())
  1425. fn.fd = func(d *Decoder, xf *codecFnInfo, xrv reflect.Value) {
  1426. // println(">>>>>> decoding an array ... ")
  1427. d.cf.get(rt2, true, false).fd(d, xf, xrv.Slice(0, xrv.Len()))
  1428. // println(">>>>>> decoding an array ... DONE")
  1429. }
  1430. // fn.fd = (*Decoder).kArray
  1431. case reflect.Struct:
  1432. if ti.anyOmitEmpty {
  1433. fn.fe = (*Encoder).kStruct
  1434. } else {
  1435. fn.fe = (*Encoder).kStructNoOmitempty
  1436. }
  1437. fn.fd = (*Decoder).kStruct
  1438. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  1439. // case reflect.Ptr:
  1440. // fn.fe = (*Encoder).kPtr
  1441. // case reflect.Interface:
  1442. // fn.fe = (*Encoder).kInterface
  1443. case reflect.Map:
  1444. fn.fe = (*Encoder).kMap
  1445. fn.fd = (*Decoder).kMap
  1446. case reflect.Interface:
  1447. // encode: reflect.Interface are handled already by preEncodeValue
  1448. fn.fd = (*Decoder).kInterface
  1449. default:
  1450. fn.fe = (*Encoder).kErr
  1451. fn.fd = (*Decoder).kErr
  1452. }
  1453. }
  1454. }
  1455. return
  1456. }
  1457. // ----
  1458. // these functions must be inlinable, and not call anybody
  1459. type checkOverflow struct{}
  1460. func (_ checkOverflow) Float32(f float64) (overflow bool) {
  1461. if f < 0 {
  1462. f = -f
  1463. }
  1464. return math.MaxFloat32 < f && f <= math.MaxFloat64
  1465. }
  1466. func (_ checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  1467. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1468. return
  1469. }
  1470. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1471. overflow = true
  1472. }
  1473. return
  1474. }
  1475. func (_ checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  1476. if bitsize == 0 || bitsize >= 64 || v == 0 {
  1477. return
  1478. }
  1479. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  1480. overflow = true
  1481. }
  1482. return
  1483. }
  1484. func (_ checkOverflow) SignedInt(v uint64) (i int64, overflow bool) {
  1485. //e.g. -127 to 128 for int8
  1486. pos := (v >> 63) == 0
  1487. ui2 := v & 0x7fffffffffffffff
  1488. if pos {
  1489. if ui2 > math.MaxInt64 {
  1490. overflow = true
  1491. return
  1492. }
  1493. } else {
  1494. if ui2 > math.MaxInt64-1 {
  1495. overflow = true
  1496. return
  1497. }
  1498. }
  1499. i = int64(v)
  1500. return
  1501. }
  1502. // ------------------ SORT -----------------
  1503. func isNaN(f float64) bool { return f != f }
  1504. // -----------------------
  1505. type intSlice []int64
  1506. type uintSlice []uint64
  1507. type uintptrSlice []uintptr
  1508. type floatSlice []float64
  1509. type boolSlice []bool
  1510. type stringSlice []string
  1511. type bytesSlice [][]byte
  1512. func (p intSlice) Len() int { return len(p) }
  1513. func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
  1514. func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1515. func (p uintSlice) Len() int { return len(p) }
  1516. func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
  1517. func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1518. func (p uintptrSlice) Len() int { return len(p) }
  1519. func (p uintptrSlice) Less(i, j int) bool { return p[i] < p[j] }
  1520. func (p uintptrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1521. func (p floatSlice) Len() int { return len(p) }
  1522. func (p floatSlice) Less(i, j int) bool {
  1523. return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
  1524. }
  1525. func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1526. func (p stringSlice) Len() int { return len(p) }
  1527. func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
  1528. func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1529. func (p bytesSlice) Len() int { return len(p) }
  1530. func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
  1531. func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1532. func (p boolSlice) Len() int { return len(p) }
  1533. func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
  1534. func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1535. // ---------------------
  1536. type intRv struct {
  1537. v int64
  1538. r reflect.Value
  1539. }
  1540. type intRvSlice []intRv
  1541. type uintRv struct {
  1542. v uint64
  1543. r reflect.Value
  1544. }
  1545. type uintRvSlice []uintRv
  1546. type floatRv struct {
  1547. v float64
  1548. r reflect.Value
  1549. }
  1550. type floatRvSlice []floatRv
  1551. type boolRv struct {
  1552. v bool
  1553. r reflect.Value
  1554. }
  1555. type boolRvSlice []boolRv
  1556. type stringRv struct {
  1557. v string
  1558. r reflect.Value
  1559. }
  1560. type stringRvSlice []stringRv
  1561. type bytesRv struct {
  1562. v []byte
  1563. r reflect.Value
  1564. }
  1565. type bytesRvSlice []bytesRv
  1566. func (p intRvSlice) Len() int { return len(p) }
  1567. func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1568. func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1569. func (p uintRvSlice) Len() int { return len(p) }
  1570. func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1571. func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1572. func (p floatRvSlice) Len() int { return len(p) }
  1573. func (p floatRvSlice) Less(i, j int) bool {
  1574. return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
  1575. }
  1576. func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1577. func (p stringRvSlice) Len() int { return len(p) }
  1578. func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1579. func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1580. func (p bytesRvSlice) Len() int { return len(p) }
  1581. func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1582. func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1583. func (p boolRvSlice) Len() int { return len(p) }
  1584. func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
  1585. func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1586. // -----------------
  1587. type bytesI struct {
  1588. v []byte
  1589. i interface{}
  1590. }
  1591. type bytesISlice []bytesI
  1592. func (p bytesISlice) Len() int { return len(p) }
  1593. func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1594. func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1595. // -----------------
  1596. type set []uintptr
  1597. func (s *set) add(v uintptr) (exists bool) {
  1598. // e.ci is always nil, or len >= 1
  1599. x := *s
  1600. if x == nil {
  1601. x = make([]uintptr, 1, 8)
  1602. x[0] = v
  1603. *s = x
  1604. return
  1605. }
  1606. // typically, length will be 1. make this perform.
  1607. if len(x) == 1 {
  1608. if j := x[0]; j == 0 {
  1609. x[0] = v
  1610. } else if j == v {
  1611. exists = true
  1612. } else {
  1613. x = append(x, v)
  1614. *s = x
  1615. }
  1616. return
  1617. }
  1618. // check if it exists
  1619. for _, j := range x {
  1620. if j == v {
  1621. exists = true
  1622. return
  1623. }
  1624. }
  1625. // try to replace a "deleted" slot
  1626. for i, j := range x {
  1627. if j == 0 {
  1628. x[i] = v
  1629. return
  1630. }
  1631. }
  1632. // if unable to replace deleted slot, just append it.
  1633. x = append(x, v)
  1634. *s = x
  1635. return
  1636. }
  1637. func (s *set) remove(v uintptr) (exists bool) {
  1638. x := *s
  1639. if len(x) == 0 {
  1640. return
  1641. }
  1642. if len(x) == 1 {
  1643. if x[0] == v {
  1644. x[0] = 0
  1645. }
  1646. return
  1647. }
  1648. for i, j := range x {
  1649. if j == v {
  1650. exists = true
  1651. x[i] = 0 // set it to 0, as way to delete it.
  1652. // copy(x[i:], x[i+1:])
  1653. // x = x[:len(x)-1]
  1654. return
  1655. }
  1656. }
  1657. return
  1658. }
  1659. // ------
  1660. // bitset types are better than [256]bool, because they permit the whole
  1661. // bitset array being on a single cache line and use less memory.
  1662. // given x > 0 and n > 0 and x is exactly 2^n, then pos/x === pos>>n AND pos%x === pos&(x-1).
  1663. // consequently, pos/32 === pos>>5, pos/16 === pos>>4, pos/8 === pos>>3, pos%8 == pos&7
  1664. type bitset256 [32]byte
  1665. func (x *bitset256) set(pos byte) {
  1666. x[pos>>3] |= (1 << (pos & 7))
  1667. }
  1668. func (x *bitset256) unset(pos byte) {
  1669. x[pos>>3] &^= (1 << (pos & 7))
  1670. }
  1671. func (x *bitset256) isset(pos byte) bool {
  1672. return x[pos>>3]&(1<<(pos&7)) != 0
  1673. }
  1674. type bitset128 [16]byte
  1675. func (x *bitset128) set(pos byte) {
  1676. x[pos>>3] |= (1 << (pos & 7))
  1677. }
  1678. func (x *bitset128) unset(pos byte) {
  1679. x[pos>>3] &^= (1 << (pos & 7))
  1680. }
  1681. func (x *bitset128) isset(pos byte) bool {
  1682. return x[pos>>3]&(1<<(pos&7)) != 0
  1683. }
  1684. // ------------
  1685. type pooler struct {
  1686. // for stringRV
  1687. strRv8, strRv16, strRv32, strRv64, strRv128 sync.Pool
  1688. // for the decNaked
  1689. dn sync.Pool
  1690. tiload sync.Pool
  1691. }
  1692. func (p *pooler) init() {
  1693. p.strRv8.New = func() interface{} { return new([8]stringRv) }
  1694. p.strRv16.New = func() interface{} { return new([16]stringRv) }
  1695. p.strRv32.New = func() interface{} { return new([32]stringRv) }
  1696. p.strRv64.New = func() interface{} { return new([64]stringRv) }
  1697. p.strRv128.New = func() interface{} { return new([128]stringRv) }
  1698. p.dn.New = func() interface{} { x := new(decNaked); x.init(); return x }
  1699. p.tiload.New = func() interface{} { return new(typeInfoLoadArray) }
  1700. }
  1701. func (p *pooler) stringRv8() (sp *sync.Pool, v interface{}) {
  1702. return &p.strRv8, p.strRv8.Get()
  1703. }
  1704. func (p *pooler) stringRv16() (sp *sync.Pool, v interface{}) {
  1705. return &p.strRv16, p.strRv16.Get()
  1706. }
  1707. func (p *pooler) stringRv32() (sp *sync.Pool, v interface{}) {
  1708. return &p.strRv32, p.strRv32.Get()
  1709. }
  1710. func (p *pooler) stringRv64() (sp *sync.Pool, v interface{}) {
  1711. return &p.strRv64, p.strRv64.Get()
  1712. }
  1713. func (p *pooler) stringRv128() (sp *sync.Pool, v interface{}) {
  1714. return &p.strRv128, p.strRv128.Get()
  1715. }
  1716. func (p *pooler) decNaked() (sp *sync.Pool, v interface{}) {
  1717. return &p.dn, p.dn.Get()
  1718. }
  1719. func (p *pooler) tiLoad() (sp *sync.Pool, v interface{}) {
  1720. return &p.tiload, p.tiload.Get()
  1721. }