helper.go 38 KB

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