helper.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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. "reflect"
  103. "sort"
  104. "strings"
  105. "sync"
  106. "time"
  107. )
  108. const (
  109. scratchByteArrayLen = 32
  110. initCollectionCap = 32 // 32 is defensive. 16 is preferred.
  111. // Support encoding.(Binary|Text)(Unm|M)arshaler.
  112. // This constant flag will enable or disable it.
  113. supportMarshalInterfaces = true
  114. // Each Encoder or Decoder uses a cache of functions based on conditionals,
  115. // so that the conditionals are not run every time.
  116. //
  117. // Either a map or a slice is used to keep track of the functions.
  118. // The map is more natural, but has a higher cost than a slice/array.
  119. // This flag (useMapForCodecCache) controls which is used.
  120. //
  121. // From benchmarks, slices with linear search perform better with < 32 entries.
  122. // We have typically seen a high threshold of about 24 entries.
  123. useMapForCodecCache = false
  124. // for debugging, set this to false, to catch panic traces.
  125. // Note that this will always cause rpc tests to fail, since they need io.EOF sent via panic.
  126. recoverPanicToErr = true
  127. // if resetSliceElemToZeroValue, then on decoding a slice, reset the element to a zero value first.
  128. // Only concern is that, if the slice already contained some garbage, we will decode into that garbage.
  129. // The chances of this are slim, so leave this "optimization".
  130. // TODO: should this be true, to ensure that we always decode into a "zero" "empty" value?
  131. resetSliceElemToZeroValue bool = false
  132. )
  133. var (
  134. oneByteArr = [1]byte{0}
  135. zeroByteSlice = oneByteArr[:0:0]
  136. )
  137. type charEncoding uint8
  138. const (
  139. c_RAW charEncoding = iota
  140. c_UTF8
  141. c_UTF16LE
  142. c_UTF16BE
  143. c_UTF32LE
  144. c_UTF32BE
  145. )
  146. // valueType is the stream type
  147. type valueType uint8
  148. const (
  149. valueTypeUnset valueType = iota
  150. valueTypeNil
  151. valueTypeInt
  152. valueTypeUint
  153. valueTypeFloat
  154. valueTypeBool
  155. valueTypeString
  156. valueTypeSymbol
  157. valueTypeBytes
  158. valueTypeMap
  159. valueTypeArray
  160. valueTypeTimestamp
  161. valueTypeExt
  162. // valueTypeInvalid = 0xff
  163. )
  164. type seqType uint8
  165. const (
  166. _ seqType = iota
  167. seqTypeArray
  168. seqTypeSlice
  169. seqTypeChan
  170. )
  171. // note that containerMapStart and containerArraySend are not sent.
  172. // This is because the ReadXXXStart and EncodeXXXStart already does these.
  173. type containerState uint8
  174. const (
  175. _ containerState = iota
  176. containerMapStart // slot left open, since Driver method already covers it
  177. containerMapKey
  178. containerMapValue
  179. containerMapEnd
  180. containerArrayStart // slot left open, since Driver methods already cover it
  181. containerArrayElem
  182. containerArrayEnd
  183. )
  184. // sfiIdx used for tracking where a (field/enc)Name is seen in a []*structFieldInfo
  185. type sfiIdx struct {
  186. name string
  187. index int
  188. }
  189. // do not recurse if a containing type refers to an embedded type
  190. // which refers back to its containing type (via a pointer).
  191. // The second time this back-reference happens, break out,
  192. // so as not to cause an infinite loop.
  193. const rgetMaxRecursion = 2
  194. // Anecdotally, we believe most types have <= 12 fields.
  195. // Java's PMD rules set TooManyFields threshold to 15.
  196. const rgetPoolTArrayLen = 12
  197. type rgetT struct {
  198. fNames []string
  199. encNames []string
  200. etypes []uintptr
  201. sfis []*structFieldInfo
  202. }
  203. type rgetPoolT struct {
  204. fNames [rgetPoolTArrayLen]string
  205. encNames [rgetPoolTArrayLen]string
  206. etypes [rgetPoolTArrayLen]uintptr
  207. sfis [rgetPoolTArrayLen]*structFieldInfo
  208. sfiidx [rgetPoolTArrayLen]sfiIdx
  209. }
  210. var rgetPool = sync.Pool{
  211. New: func() interface{} { return new(rgetPoolT) },
  212. }
  213. type containerStateRecv interface {
  214. sendContainerState(containerState)
  215. }
  216. // mirror json.Marshaler and json.Unmarshaler here,
  217. // so we don't import the encoding/json package
  218. type jsonMarshaler interface {
  219. MarshalJSON() ([]byte, error)
  220. }
  221. type jsonUnmarshaler interface {
  222. UnmarshalJSON([]byte) error
  223. }
  224. var (
  225. bigen = binary.BigEndian
  226. structInfoFieldName = "_struct"
  227. mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  228. mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
  229. intfSliceTyp = reflect.TypeOf([]interface{}(nil))
  230. intfTyp = intfSliceTyp.Elem()
  231. stringTyp = reflect.TypeOf("")
  232. timeTyp = reflect.TypeOf(time.Time{})
  233. rawExtTyp = reflect.TypeOf(RawExt{})
  234. rawTyp = reflect.TypeOf(Raw{})
  235. uint8SliceTyp = reflect.TypeOf([]uint8(nil))
  236. mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
  237. binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  238. binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
  239. textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  240. textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
  241. jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  242. jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
  243. selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
  244. uint8SliceTypId = reflect.ValueOf(uint8SliceTyp).Pointer()
  245. rawExtTypId = reflect.ValueOf(rawExtTyp).Pointer()
  246. rawTypId = reflect.ValueOf(rawTyp).Pointer()
  247. intfTypId = reflect.ValueOf(intfTyp).Pointer()
  248. timeTypId = reflect.ValueOf(timeTyp).Pointer()
  249. stringTypId = reflect.ValueOf(stringTyp).Pointer()
  250. mapStrIntfTypId = reflect.ValueOf(mapStrIntfTyp).Pointer()
  251. mapIntfIntfTypId = reflect.ValueOf(mapIntfIntfTyp).Pointer()
  252. intfSliceTypId = reflect.ValueOf(intfSliceTyp).Pointer()
  253. // mapBySliceTypId = reflect.ValueOf(mapBySliceTyp).Pointer()
  254. intBitsize uint8 = uint8(reflect.TypeOf(int(0)).Bits())
  255. uintBitsize uint8 = uint8(reflect.TypeOf(uint(0)).Bits())
  256. bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
  257. bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
  258. chkOvf checkOverflow
  259. noFieldNameToStructFieldInfoErr = errors.New("no field name passed to parseStructFieldInfo")
  260. )
  261. var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
  262. // Selfer defines methods by which a value can encode or decode itself.
  263. //
  264. // Any type which implements Selfer will be able to encode or decode itself.
  265. // Consequently, during (en|de)code, this takes precedence over
  266. // (text|binary)(M|Unm)arshal or extension support.
  267. type Selfer interface {
  268. CodecEncodeSelf(*Encoder)
  269. CodecDecodeSelf(*Decoder)
  270. }
  271. // MapBySlice represents a slice which should be encoded as a map in the stream.
  272. // The slice contains a sequence of key-value pairs.
  273. // This affords storing a map in a specific sequence in the stream.
  274. //
  275. // The support of MapBySlice affords the following:
  276. // - A slice type which implements MapBySlice will be encoded as a map
  277. // - A slice can be decoded from a map in the stream
  278. type MapBySlice interface {
  279. MapBySlice()
  280. }
  281. // WARNING: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
  282. //
  283. // BasicHandle encapsulates the common options and extension functions.
  284. type BasicHandle struct {
  285. // TypeInfos is used to get the type info for any type.
  286. //
  287. // If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
  288. TypeInfos *TypeInfos
  289. extHandle
  290. EncodeOptions
  291. DecodeOptions
  292. }
  293. func (x *BasicHandle) getBasicHandle() *BasicHandle {
  294. return x
  295. }
  296. func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  297. if x.TypeInfos != nil {
  298. return x.TypeInfos.get(rtid, rt)
  299. }
  300. return defTypeInfos.get(rtid, rt)
  301. }
  302. // Handle is the interface for a specific encoding format.
  303. //
  304. // Typically, a Handle is pre-configured before first time use,
  305. // and not modified while in use. Such a pre-configured Handle
  306. // is safe for concurrent access.
  307. type Handle interface {
  308. getBasicHandle() *BasicHandle
  309. newEncDriver(w *Encoder) encDriver
  310. newDecDriver(r *Decoder) decDriver
  311. isBinary() bool
  312. }
  313. // Raw represents raw formatted bytes.
  314. // We "blindly" store it during encode and store the raw bytes during decode.
  315. // Note: it is dangerous during encode, so we may gate the behaviour behind an Encode flag which must be explicitly set.
  316. type Raw []byte
  317. // RawExt represents raw unprocessed extension data.
  318. // Some codecs will decode extension data as a *RawExt if there is no registered extension for the tag.
  319. //
  320. // Only one of Data or Value is nil. If Data is nil, then the content of the RawExt is in the Value.
  321. type RawExt struct {
  322. Tag uint64
  323. // Data is the []byte which represents the raw ext. If Data is nil, ext is exposed in Value.
  324. // Data is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types
  325. Data []byte
  326. // Value represents the extension, if Data is nil.
  327. // Value is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  328. Value interface{}
  329. }
  330. // BytesExt handles custom (de)serialization of types to/from []byte.
  331. // It is used by codecs (e.g. binc, msgpack, simple) which do custom serialization of the types.
  332. type BytesExt interface {
  333. // WriteExt converts a value to a []byte.
  334. //
  335. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  336. WriteExt(v interface{}) []byte
  337. // ReadExt updates a value from a []byte.
  338. ReadExt(dst interface{}, src []byte)
  339. }
  340. // InterfaceExt handles custom (de)serialization of types to/from another interface{} value.
  341. // The Encoder or Decoder will then handle the further (de)serialization of that known type.
  342. //
  343. // It is used by codecs (e.g. cbor, json) which use the format to do custom serialization of the types.
  344. type InterfaceExt interface {
  345. // ConvertExt converts a value into a simpler interface for easy encoding e.g. convert time.Time to int64.
  346. //
  347. // Note: v *may* be a pointer to the extension type, if the extension type was a struct or array.
  348. ConvertExt(v interface{}) interface{}
  349. // UpdateExt updates a value from a simpler interface for easy decoding e.g. convert int64 to time.Time.
  350. UpdateExt(dst interface{}, src interface{})
  351. }
  352. // Ext handles custom (de)serialization of custom types / extensions.
  353. type Ext interface {
  354. BytesExt
  355. InterfaceExt
  356. }
  357. // addExtWrapper is a wrapper implementation to support former AddExt exported method.
  358. type addExtWrapper struct {
  359. encFn func(reflect.Value) ([]byte, error)
  360. decFn func(reflect.Value, []byte) error
  361. }
  362. func (x addExtWrapper) WriteExt(v interface{}) []byte {
  363. bs, err := x.encFn(reflect.ValueOf(v))
  364. if err != nil {
  365. panic(err)
  366. }
  367. return bs
  368. }
  369. func (x addExtWrapper) ReadExt(v interface{}, bs []byte) {
  370. if err := x.decFn(reflect.ValueOf(v), bs); err != nil {
  371. panic(err)
  372. }
  373. }
  374. func (x addExtWrapper) ConvertExt(v interface{}) interface{} {
  375. return x.WriteExt(v)
  376. }
  377. func (x addExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  378. x.ReadExt(dest, v.([]byte))
  379. }
  380. type setExtWrapper struct {
  381. b BytesExt
  382. i InterfaceExt
  383. }
  384. func (x *setExtWrapper) WriteExt(v interface{}) []byte {
  385. if x.b == nil {
  386. panic("BytesExt.WriteExt is not supported")
  387. }
  388. return x.b.WriteExt(v)
  389. }
  390. func (x *setExtWrapper) ReadExt(v interface{}, bs []byte) {
  391. if x.b == nil {
  392. panic("BytesExt.WriteExt is not supported")
  393. }
  394. x.b.ReadExt(v, bs)
  395. }
  396. func (x *setExtWrapper) ConvertExt(v interface{}) interface{} {
  397. if x.i == nil {
  398. panic("InterfaceExt.ConvertExt is not supported")
  399. }
  400. return x.i.ConvertExt(v)
  401. }
  402. func (x *setExtWrapper) UpdateExt(dest interface{}, v interface{}) {
  403. if x.i == nil {
  404. panic("InterfaceExxt.UpdateExt is not supported")
  405. }
  406. x.i.UpdateExt(dest, v)
  407. }
  408. // type errorString string
  409. // func (x errorString) Error() string { return string(x) }
  410. type binaryEncodingType struct{}
  411. func (_ binaryEncodingType) isBinary() bool { return true }
  412. type textEncodingType struct{}
  413. func (_ textEncodingType) isBinary() bool { return false }
  414. // noBuiltInTypes is embedded into many types which do not support builtins
  415. // e.g. msgpack, simple, cbor.
  416. type noBuiltInTypes struct{}
  417. func (_ noBuiltInTypes) IsBuiltinType(rt uintptr) bool { return false }
  418. func (_ noBuiltInTypes) EncodeBuiltin(rt uintptr, v interface{}) {}
  419. func (_ noBuiltInTypes) DecodeBuiltin(rt uintptr, v interface{}) {}
  420. type noStreamingCodec struct{}
  421. func (_ noStreamingCodec) CheckBreak() bool { return false }
  422. // bigenHelper.
  423. // Users must already slice the x completely, because we will not reslice.
  424. type bigenHelper struct {
  425. x []byte // must be correctly sliced to appropriate len. slicing is a cost.
  426. w encWriter
  427. }
  428. func (z bigenHelper) writeUint16(v uint16) {
  429. bigen.PutUint16(z.x, v)
  430. z.w.writeb(z.x)
  431. }
  432. func (z bigenHelper) writeUint32(v uint32) {
  433. bigen.PutUint32(z.x, v)
  434. z.w.writeb(z.x)
  435. }
  436. func (z bigenHelper) writeUint64(v uint64) {
  437. bigen.PutUint64(z.x, v)
  438. z.w.writeb(z.x)
  439. }
  440. type extTypeTagFn struct {
  441. rtid uintptr
  442. rt reflect.Type
  443. tag uint64
  444. ext Ext
  445. }
  446. type extHandle []extTypeTagFn
  447. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  448. //
  449. // AddExt registes an encode and decode function for a reflect.Type.
  450. // AddExt internally calls SetExt.
  451. // To deregister an Ext, call AddExt with nil encfn and/or nil decfn.
  452. func (o *extHandle) AddExt(
  453. rt reflect.Type, tag byte,
  454. encfn func(reflect.Value) ([]byte, error), decfn func(reflect.Value, []byte) error,
  455. ) (err error) {
  456. if encfn == nil || decfn == nil {
  457. return o.SetExt(rt, uint64(tag), nil)
  458. }
  459. return o.SetExt(rt, uint64(tag), addExtWrapper{encfn, decfn})
  460. }
  461. // DEPRECATED: Use SetBytesExt or SetInterfaceExt on the Handle instead.
  462. //
  463. // Note that the type must be a named type, and specifically not
  464. // a pointer or Interface. An error is returned if that is not honored.
  465. //
  466. // To Deregister an ext, call SetExt with nil Ext
  467. func (o *extHandle) SetExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
  468. // o is a pointer, because we may need to initialize it
  469. if rt.PkgPath() == "" || rt.Kind() == reflect.Interface {
  470. err = fmt.Errorf("codec.Handle.AddExt: Takes named type, not a pointer or interface: %T",
  471. reflect.Zero(rt).Interface())
  472. return
  473. }
  474. rtid := reflect.ValueOf(rt).Pointer()
  475. for _, v := range *o {
  476. if v.rtid == rtid {
  477. v.tag, v.ext = tag, ext
  478. return
  479. }
  480. }
  481. if *o == nil {
  482. *o = make([]extTypeTagFn, 0, 4)
  483. }
  484. *o = append(*o, extTypeTagFn{rtid, rt, tag, ext})
  485. return
  486. }
  487. func (o extHandle) getExt(rtid uintptr) *extTypeTagFn {
  488. var v *extTypeTagFn
  489. for i := range o {
  490. v = &o[i]
  491. if v.rtid == rtid {
  492. return v
  493. }
  494. }
  495. return nil
  496. }
  497. func (o extHandle) getExtForTag(tag uint64) *extTypeTagFn {
  498. var v *extTypeTagFn
  499. for i := range o {
  500. v = &o[i]
  501. if v.tag == tag {
  502. return v
  503. }
  504. }
  505. return nil
  506. }
  507. type structFieldInfo struct {
  508. encName string // encode name
  509. fieldName string // field name
  510. // only one of 'i' or 'is' can be set. If 'i' is -1, then 'is' has been set.
  511. is []int // (recursive/embedded) field index in struct
  512. i int16 // field index in struct
  513. omitEmpty bool
  514. toArray bool // if field is _struct, is the toArray set?
  515. }
  516. // func (si *structFieldInfo) isZero() bool {
  517. // return si.encName == "" && len(si.is) == 0 && si.i == 0 && !si.omitEmpty && !si.toArray
  518. // }
  519. // rv returns the field of the struct.
  520. // If anonymous, it returns an Invalid
  521. func (si *structFieldInfo) field(v reflect.Value, update bool) (rv2 reflect.Value) {
  522. if si.i != -1 {
  523. v = v.Field(int(si.i))
  524. return v
  525. }
  526. // replicate FieldByIndex
  527. for _, x := range si.is {
  528. for v.Kind() == reflect.Ptr {
  529. if v.IsNil() {
  530. if !update {
  531. return
  532. }
  533. v.Set(reflect.New(v.Type().Elem()))
  534. }
  535. v = v.Elem()
  536. }
  537. v = v.Field(x)
  538. }
  539. return v
  540. }
  541. func (si *structFieldInfo) setToZeroValue(v reflect.Value) {
  542. if si.i != -1 {
  543. v = v.Field(int(si.i))
  544. v.Set(reflect.Zero(v.Type()))
  545. // v.Set(reflect.New(v.Type()).Elem())
  546. // v.Set(reflect.New(v.Type()))
  547. } else {
  548. // replicate FieldByIndex
  549. for _, x := range si.is {
  550. for v.Kind() == reflect.Ptr {
  551. if v.IsNil() {
  552. return
  553. }
  554. v = v.Elem()
  555. }
  556. v = v.Field(x)
  557. }
  558. v.Set(reflect.Zero(v.Type()))
  559. }
  560. }
  561. func parseStructFieldInfo(fname string, stag string) *structFieldInfo {
  562. // if fname == "" {
  563. // panic(noFieldNameToStructFieldInfoErr)
  564. // }
  565. si := structFieldInfo{
  566. encName: fname,
  567. }
  568. if stag != "" {
  569. for i, s := range strings.Split(stag, ",") {
  570. if i == 0 {
  571. if s != "" {
  572. si.encName = s
  573. }
  574. } else {
  575. if s == "omitempty" {
  576. si.omitEmpty = true
  577. } else if s == "toarray" {
  578. si.toArray = true
  579. }
  580. }
  581. }
  582. }
  583. // si.encNameBs = []byte(si.encName)
  584. return &si
  585. }
  586. type sfiSortedByEncName []*structFieldInfo
  587. func (p sfiSortedByEncName) Len() int {
  588. return len(p)
  589. }
  590. func (p sfiSortedByEncName) Less(i, j int) bool {
  591. return p[i].encName < p[j].encName
  592. }
  593. func (p sfiSortedByEncName) Swap(i, j int) {
  594. p[i], p[j] = p[j], p[i]
  595. }
  596. // typeInfo keeps information about each type referenced in the encode/decode sequence.
  597. //
  598. // During an encode/decode sequence, we work as below:
  599. // - If base is a built in type, en/decode base value
  600. // - If base is registered as an extension, en/decode base value
  601. // - If type is binary(M/Unm)arshaler, call Binary(M/Unm)arshal method
  602. // - If type is text(M/Unm)arshaler, call Text(M/Unm)arshal method
  603. // - Else decode appropriately based on the reflect.Kind
  604. type typeInfo struct {
  605. sfi []*structFieldInfo // sorted. Used when enc/dec struct to map.
  606. sfip []*structFieldInfo // unsorted. Used when enc/dec struct to array.
  607. rt reflect.Type
  608. rtid uintptr
  609. numMeth uint16 // number of methods
  610. // baseId gives pointer to the base reflect.Type, after deferencing
  611. // the pointers. E.g. base type of ***time.Time is time.Time.
  612. base reflect.Type
  613. baseId uintptr
  614. baseIndir int8 // number of indirections to get to base
  615. mbs bool // base type (T or *T) is a MapBySlice
  616. bm bool // base type (T or *T) is a binaryMarshaler
  617. bunm bool // base type (T or *T) is a binaryUnmarshaler
  618. bmIndir int8 // number of indirections to get to binaryMarshaler type
  619. bunmIndir int8 // number of indirections to get to binaryUnmarshaler type
  620. tm bool // base type (T or *T) is a textMarshaler
  621. tunm bool // base type (T or *T) is a textUnmarshaler
  622. tmIndir int8 // number of indirections to get to textMarshaler type
  623. tunmIndir int8 // number of indirections to get to textUnmarshaler type
  624. jm bool // base type (T or *T) is a jsonMarshaler
  625. junm bool // base type (T or *T) is a jsonUnmarshaler
  626. jmIndir int8 // number of indirections to get to jsonMarshaler type
  627. junmIndir int8 // number of indirections to get to jsonUnmarshaler type
  628. cs bool // base type (T or *T) is a Selfer
  629. csIndir int8 // number of indirections to get to Selfer type
  630. toArray bool // whether this (struct) type should be encoded as an array
  631. }
  632. func (ti *typeInfo) indexForEncName(name string) int {
  633. // NOTE: name may be a stringView, so don't pass it to another function.
  634. //tisfi := ti.sfi
  635. const binarySearchThreshold = 16
  636. if sfilen := len(ti.sfi); sfilen < binarySearchThreshold {
  637. // linear search. faster than binary search in my testing up to 16-field structs.
  638. for i, si := range ti.sfi {
  639. if si.encName == name {
  640. return i
  641. }
  642. }
  643. } else {
  644. // binary search. adapted from sort/search.go.
  645. h, i, j := 0, 0, sfilen
  646. for i < j {
  647. h = i + (j-i)/2
  648. if ti.sfi[h].encName < name {
  649. i = h + 1
  650. } else {
  651. j = h
  652. }
  653. }
  654. if i < sfilen && ti.sfi[i].encName == name {
  655. return i
  656. }
  657. }
  658. return -1
  659. }
  660. // TypeInfos caches typeInfo for each type on first inspection.
  661. //
  662. // It is configured with a set of tag keys, which are used to get
  663. // configuration for the type.
  664. type TypeInfos struct {
  665. infos map[uintptr]*typeInfo
  666. mu sync.RWMutex
  667. tags []string
  668. }
  669. // NewTypeInfos creates a TypeInfos given a set of struct tags keys.
  670. //
  671. // This allows users customize the struct tag keys which contain configuration
  672. // of their types.
  673. func NewTypeInfos(tags []string) *TypeInfos {
  674. return &TypeInfos{tags: tags, infos: make(map[uintptr]*typeInfo, 64)}
  675. }
  676. func (x *TypeInfos) structTag(t reflect.StructTag) (s string) {
  677. // check for tags: codec, json, in that order.
  678. // this allows seamless support for many configured structs.
  679. for _, x := range x.tags {
  680. s = t.Get(x)
  681. if s != "" {
  682. return s
  683. }
  684. }
  685. return
  686. }
  687. func (x *TypeInfos) get(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
  688. var ok bool
  689. x.mu.RLock()
  690. pti, ok = x.infos[rtid]
  691. x.mu.RUnlock()
  692. if ok {
  693. return
  694. }
  695. // do not hold lock while computing this.
  696. // it may lead to duplication, but that's ok.
  697. ti := typeInfo{rt: rt, rtid: rtid}
  698. ti.numMeth = uint16(rt.NumMethod())
  699. var indir int8
  700. if ok, indir = implementsIntf(rt, binaryMarshalerTyp); ok {
  701. ti.bm, ti.bmIndir = true, indir
  702. }
  703. if ok, indir = implementsIntf(rt, binaryUnmarshalerTyp); ok {
  704. ti.bunm, ti.bunmIndir = true, indir
  705. }
  706. if ok, indir = implementsIntf(rt, textMarshalerTyp); ok {
  707. ti.tm, ti.tmIndir = true, indir
  708. }
  709. if ok, indir = implementsIntf(rt, textUnmarshalerTyp); ok {
  710. ti.tunm, ti.tunmIndir = true, indir
  711. }
  712. if ok, indir = implementsIntf(rt, jsonMarshalerTyp); ok {
  713. ti.jm, ti.jmIndir = true, indir
  714. }
  715. if ok, indir = implementsIntf(rt, jsonUnmarshalerTyp); ok {
  716. ti.junm, ti.junmIndir = true, indir
  717. }
  718. if ok, indir = implementsIntf(rt, selferTyp); ok {
  719. ti.cs, ti.csIndir = true, indir
  720. }
  721. if ok, _ = implementsIntf(rt, mapBySliceTyp); ok {
  722. ti.mbs = true
  723. }
  724. pt := rt
  725. var ptIndir int8
  726. // for ; pt.Kind() == reflect.Ptr; pt, ptIndir = pt.Elem(), ptIndir+1 { }
  727. for pt.Kind() == reflect.Ptr {
  728. pt = pt.Elem()
  729. ptIndir++
  730. }
  731. if ptIndir == 0 {
  732. ti.base = rt
  733. ti.baseId = rtid
  734. } else {
  735. ti.base = pt
  736. ti.baseId = reflect.ValueOf(pt).Pointer()
  737. ti.baseIndir = ptIndir
  738. }
  739. if rt.Kind() == reflect.Struct {
  740. var omitEmpty bool
  741. if f, ok := rt.FieldByName(structInfoFieldName); ok {
  742. siInfo := parseStructFieldInfo(structInfoFieldName, x.structTag(f.Tag))
  743. ti.toArray = siInfo.toArray
  744. omitEmpty = siInfo.omitEmpty
  745. }
  746. pi := rgetPool.Get()
  747. pv := pi.(*rgetPoolT)
  748. pv.etypes[0] = ti.baseId
  749. vv := rgetT{pv.fNames[:0], pv.encNames[:0], pv.etypes[:1], pv.sfis[:0]}
  750. x.rget(rt, rtid, omitEmpty, nil, &vv)
  751. ti.sfip, ti.sfi = rgetResolveSFI(vv.sfis, pv.sfiidx[:0])
  752. rgetPool.Put(pi)
  753. }
  754. // sfi = sfip
  755. x.mu.Lock()
  756. if pti, ok = x.infos[rtid]; !ok {
  757. pti = &ti
  758. x.infos[rtid] = pti
  759. }
  760. x.mu.Unlock()
  761. return
  762. }
  763. func (x *TypeInfos) rget(rt reflect.Type, rtid uintptr, omitEmpty bool,
  764. indexstack []int, pv *rgetT,
  765. ) {
  766. // Read up fields and store how to access the value.
  767. //
  768. // It uses go's rules for message selectors,
  769. // which say that the field with the shallowest depth is selected.
  770. //
  771. // Note: we consciously use slices, not a map, to simulate a set.
  772. // Typically, types have < 16 fields,
  773. // and iteration using equals is faster than maps there
  774. LOOP:
  775. for j, jlen := 0, rt.NumField(); j < jlen; j++ {
  776. f := rt.Field(j)
  777. fkind := f.Type.Kind()
  778. // skip if a func type, or is unexported, or structTag value == "-"
  779. switch fkind {
  780. case reflect.Func, reflect.Complex64, reflect.Complex128, reflect.UnsafePointer:
  781. continue LOOP
  782. }
  783. // if r1, _ := utf8.DecodeRuneInString(f.Name);
  784. // r1 == utf8.RuneError || !unicode.IsUpper(r1) {
  785. if f.PkgPath != "" && !f.Anonymous { // unexported, not embedded
  786. continue
  787. }
  788. stag := x.structTag(f.Tag)
  789. if stag == "-" {
  790. continue
  791. }
  792. var si *structFieldInfo
  793. // if anonymous and no struct tag (or it's blank),
  794. // and a struct (or pointer to struct), inline it.
  795. if f.Anonymous && fkind != reflect.Interface {
  796. doInline := stag == ""
  797. if !doInline {
  798. si = parseStructFieldInfo("", stag)
  799. doInline = si.encName == ""
  800. // doInline = si.isZero()
  801. }
  802. if doInline {
  803. ft := f.Type
  804. for ft.Kind() == reflect.Ptr {
  805. ft = ft.Elem()
  806. }
  807. if ft.Kind() == reflect.Struct {
  808. // if etypes contains this, don't call rget again (as fields are already seen here)
  809. ftid := reflect.ValueOf(ft).Pointer()
  810. // We cannot recurse forever, but we need to track other field depths.
  811. // So - we break if we see a type twice (not the first time).
  812. // This should be sufficient to handle an embedded type that refers to its
  813. // owning type, which then refers to its embedded type.
  814. processIt := true
  815. numk := 0
  816. for _, k := range pv.etypes {
  817. if k == ftid {
  818. numk++
  819. if numk == rgetMaxRecursion {
  820. processIt = false
  821. break
  822. }
  823. }
  824. }
  825. if processIt {
  826. pv.etypes = append(pv.etypes, ftid)
  827. indexstack2 := make([]int, len(indexstack)+1)
  828. copy(indexstack2, indexstack)
  829. indexstack2[len(indexstack)] = j
  830. // indexstack2 := append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  831. x.rget(ft, ftid, omitEmpty, indexstack2, pv)
  832. }
  833. continue
  834. }
  835. }
  836. }
  837. // after the anonymous dance: if an unexported field, skip
  838. if f.PkgPath != "" { // unexported
  839. continue
  840. }
  841. if f.Name == "" {
  842. panic(noFieldNameToStructFieldInfoErr)
  843. }
  844. pv.fNames = append(pv.fNames, f.Name)
  845. if si == nil {
  846. si = parseStructFieldInfo(f.Name, stag)
  847. } else if si.encName == "" {
  848. si.encName = f.Name
  849. }
  850. si.fieldName = f.Name
  851. pv.encNames = append(pv.encNames, si.encName)
  852. // si.ikind = int(f.Type.Kind())
  853. if len(indexstack) == 0 {
  854. si.i = int16(j)
  855. } else {
  856. si.i = -1
  857. si.is = make([]int, len(indexstack)+1)
  858. copy(si.is, indexstack)
  859. si.is[len(indexstack)] = j
  860. // si.is = append(append(make([]int, 0, len(indexstack)+4), indexstack...), j)
  861. }
  862. if omitEmpty {
  863. si.omitEmpty = true
  864. }
  865. pv.sfis = append(pv.sfis, si)
  866. }
  867. }
  868. // resolves the struct field info got from a call to rget.
  869. // Returns a trimmed, unsorted and sorted []*structFieldInfo.
  870. func rgetResolveSFI(x []*structFieldInfo, pv []sfiIdx) (y, z []*structFieldInfo) {
  871. var n int
  872. for i, v := range x {
  873. xn := v.encName //TODO: fieldName or encName? use encName for now.
  874. var found bool
  875. for j, k := range pv {
  876. if k.name == xn {
  877. // one of them must be reset to nil, and the index updated appropriately to the other one
  878. if len(v.is) == len(x[k.index].is) {
  879. } else if len(v.is) < len(x[k.index].is) {
  880. pv[j].index = i
  881. if x[k.index] != nil {
  882. x[k.index] = nil
  883. n++
  884. }
  885. } else {
  886. if x[i] != nil {
  887. x[i] = nil
  888. n++
  889. }
  890. }
  891. found = true
  892. break
  893. }
  894. }
  895. if !found {
  896. pv = append(pv, sfiIdx{xn, i})
  897. }
  898. }
  899. // remove all the nils
  900. y = make([]*structFieldInfo, len(x)-n)
  901. n = 0
  902. for _, v := range x {
  903. if v == nil {
  904. continue
  905. }
  906. y[n] = v
  907. n++
  908. }
  909. z = make([]*structFieldInfo, len(y))
  910. copy(z, y)
  911. sort.Sort(sfiSortedByEncName(z))
  912. return
  913. }
  914. func panicToErr(err *error) {
  915. if recoverPanicToErr {
  916. if x := recover(); x != nil {
  917. //debug.PrintStack()
  918. panicValToErr(x, err)
  919. }
  920. }
  921. }
  922. // func doPanic(tag string, format string, params ...interface{}) {
  923. // params2 := make([]interface{}, len(params)+1)
  924. // params2[0] = tag
  925. // copy(params2[1:], params)
  926. // panic(fmt.Errorf("%s: "+format, params2...))
  927. // }
  928. func isImmutableKind(k reflect.Kind) (v bool) {
  929. return false ||
  930. k == reflect.Int ||
  931. k == reflect.Int8 ||
  932. k == reflect.Int16 ||
  933. k == reflect.Int32 ||
  934. k == reflect.Int64 ||
  935. k == reflect.Uint ||
  936. k == reflect.Uint8 ||
  937. k == reflect.Uint16 ||
  938. k == reflect.Uint32 ||
  939. k == reflect.Uint64 ||
  940. k == reflect.Uintptr ||
  941. k == reflect.Float32 ||
  942. k == reflect.Float64 ||
  943. k == reflect.Bool ||
  944. k == reflect.String
  945. }
  946. // these functions must be inlinable, and not call anybody
  947. type checkOverflow struct{}
  948. func (_ checkOverflow) Float32(f float64) (overflow bool) {
  949. if f < 0 {
  950. f = -f
  951. }
  952. return math.MaxFloat32 < f && f <= math.MaxFloat64
  953. }
  954. func (_ checkOverflow) Uint(v uint64, bitsize uint8) (overflow bool) {
  955. if bitsize == 0 || bitsize >= 64 || v == 0 {
  956. return
  957. }
  958. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  959. overflow = true
  960. }
  961. return
  962. }
  963. func (_ checkOverflow) Int(v int64, bitsize uint8) (overflow bool) {
  964. if bitsize == 0 || bitsize >= 64 || v == 0 {
  965. return
  966. }
  967. if trunc := (v << (64 - bitsize)) >> (64 - bitsize); v != trunc {
  968. overflow = true
  969. }
  970. return
  971. }
  972. func (_ checkOverflow) SignedInt(v uint64) (i int64, overflow bool) {
  973. //e.g. -127 to 128 for int8
  974. pos := (v >> 63) == 0
  975. ui2 := v & 0x7fffffffffffffff
  976. if pos {
  977. if ui2 > math.MaxInt64 {
  978. overflow = true
  979. return
  980. }
  981. } else {
  982. if ui2 > math.MaxInt64-1 {
  983. overflow = true
  984. return
  985. }
  986. }
  987. i = int64(v)
  988. return
  989. }
  990. // ------------------ SORT -----------------
  991. func isNaN(f float64) bool { return f != f }
  992. // -----------------------
  993. type intSlice []int64
  994. type uintSlice []uint64
  995. type floatSlice []float64
  996. type boolSlice []bool
  997. type stringSlice []string
  998. type bytesSlice [][]byte
  999. func (p intSlice) Len() int { return len(p) }
  1000. func (p intSlice) Less(i, j int) bool { return p[i] < p[j] }
  1001. func (p intSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1002. func (p uintSlice) Len() int { return len(p) }
  1003. func (p uintSlice) Less(i, j int) bool { return p[i] < p[j] }
  1004. func (p uintSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1005. func (p floatSlice) Len() int { return len(p) }
  1006. func (p floatSlice) Less(i, j int) bool {
  1007. return p[i] < p[j] || isNaN(p[i]) && !isNaN(p[j])
  1008. }
  1009. func (p floatSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1010. func (p stringSlice) Len() int { return len(p) }
  1011. func (p stringSlice) Less(i, j int) bool { return p[i] < p[j] }
  1012. func (p stringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1013. func (p bytesSlice) Len() int { return len(p) }
  1014. func (p bytesSlice) Less(i, j int) bool { return bytes.Compare(p[i], p[j]) == -1 }
  1015. func (p bytesSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1016. func (p boolSlice) Len() int { return len(p) }
  1017. func (p boolSlice) Less(i, j int) bool { return !p[i] && p[j] }
  1018. func (p boolSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1019. // ---------------------
  1020. type intRv struct {
  1021. v int64
  1022. r reflect.Value
  1023. }
  1024. type intRvSlice []intRv
  1025. type uintRv struct {
  1026. v uint64
  1027. r reflect.Value
  1028. }
  1029. type uintRvSlice []uintRv
  1030. type floatRv struct {
  1031. v float64
  1032. r reflect.Value
  1033. }
  1034. type floatRvSlice []floatRv
  1035. type boolRv struct {
  1036. v bool
  1037. r reflect.Value
  1038. }
  1039. type boolRvSlice []boolRv
  1040. type stringRv struct {
  1041. v string
  1042. r reflect.Value
  1043. }
  1044. type stringRvSlice []stringRv
  1045. type bytesRv struct {
  1046. v []byte
  1047. r reflect.Value
  1048. }
  1049. type bytesRvSlice []bytesRv
  1050. func (p intRvSlice) Len() int { return len(p) }
  1051. func (p intRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1052. func (p intRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1053. func (p uintRvSlice) Len() int { return len(p) }
  1054. func (p uintRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1055. func (p uintRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1056. func (p floatRvSlice) Len() int { return len(p) }
  1057. func (p floatRvSlice) Less(i, j int) bool {
  1058. return p[i].v < p[j].v || isNaN(p[i].v) && !isNaN(p[j].v)
  1059. }
  1060. func (p floatRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1061. func (p stringRvSlice) Len() int { return len(p) }
  1062. func (p stringRvSlice) Less(i, j int) bool { return p[i].v < p[j].v }
  1063. func (p stringRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1064. func (p bytesRvSlice) Len() int { return len(p) }
  1065. func (p bytesRvSlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1066. func (p bytesRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1067. func (p boolRvSlice) Len() int { return len(p) }
  1068. func (p boolRvSlice) Less(i, j int) bool { return !p[i].v && p[j].v }
  1069. func (p boolRvSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1070. // -----------------
  1071. type bytesI struct {
  1072. v []byte
  1073. i interface{}
  1074. }
  1075. type bytesISlice []bytesI
  1076. func (p bytesISlice) Len() int { return len(p) }
  1077. func (p bytesISlice) Less(i, j int) bool { return bytes.Compare(p[i].v, p[j].v) == -1 }
  1078. func (p bytesISlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  1079. // -----------------
  1080. type set []uintptr
  1081. func (s *set) add(v uintptr) (exists bool) {
  1082. // e.ci is always nil, or len >= 1
  1083. // defer func() { fmt.Printf("$$$$$$$$$$$ cirRef Add: %v, exists: %v\n", v, exists) }()
  1084. x := *s
  1085. if x == nil {
  1086. x = make([]uintptr, 1, 8)
  1087. x[0] = v
  1088. *s = x
  1089. return
  1090. }
  1091. // typically, length will be 1. make this perform.
  1092. if len(x) == 1 {
  1093. if j := x[0]; j == 0 {
  1094. x[0] = v
  1095. } else if j == v {
  1096. exists = true
  1097. } else {
  1098. x = append(x, v)
  1099. *s = x
  1100. }
  1101. return
  1102. }
  1103. // check if it exists
  1104. for _, j := range x {
  1105. if j == v {
  1106. exists = true
  1107. return
  1108. }
  1109. }
  1110. // try to replace a "deleted" slot
  1111. for i, j := range x {
  1112. if j == 0 {
  1113. x[i] = v
  1114. return
  1115. }
  1116. }
  1117. // if unable to replace deleted slot, just append it.
  1118. x = append(x, v)
  1119. *s = x
  1120. return
  1121. }
  1122. func (s *set) remove(v uintptr) (exists bool) {
  1123. // defer func() { fmt.Printf("$$$$$$$$$$$ cirRef Rm: %v, exists: %v\n", v, exists) }()
  1124. x := *s
  1125. if len(x) == 0 {
  1126. return
  1127. }
  1128. if len(x) == 1 {
  1129. if x[0] == v {
  1130. x[0] = 0
  1131. }
  1132. return
  1133. }
  1134. for i, j := range x {
  1135. if j == v {
  1136. exists = true
  1137. x[i] = 0 // set it to 0, as way to delete it.
  1138. // copy(x[i:], x[i+1:])
  1139. // x = x[:len(x)-1]
  1140. return
  1141. }
  1142. }
  1143. return
  1144. }