helper.go 37 KB

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