helper.go 36 KB

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