encode.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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. import (
  5. "bufio"
  6. "encoding"
  7. "fmt"
  8. "io"
  9. "reflect"
  10. "sort"
  11. "sync"
  12. )
  13. const defEncByteBufSize = 1 << 6 // 4:16, 6:64, 8:256, 10:1024
  14. // AsSymbolFlag defines what should be encoded as symbols.
  15. type AsSymbolFlag uint8
  16. const (
  17. // AsSymbolDefault is default.
  18. // Currently, this means only encode struct field names as symbols.
  19. // The default is subject to change.
  20. AsSymbolDefault AsSymbolFlag = iota
  21. // AsSymbolAll means encode anything which could be a symbol as a symbol.
  22. AsSymbolAll = 0xfe
  23. // AsSymbolNone means do not encode anything as a symbol.
  24. AsSymbolNone = 1 << iota
  25. // AsSymbolMapStringKeys means encode keys in map[string]XXX as symbols.
  26. AsSymbolMapStringKeysFlag
  27. // AsSymbolStructFieldName means encode struct field names as symbols.
  28. AsSymbolStructFieldNameFlag
  29. )
  30. // encWriter abstracts writing to a byte array or to an io.Writer.
  31. type encWriter interface {
  32. writeb([]byte)
  33. writestr(string)
  34. writen1(byte)
  35. writen2(byte, byte)
  36. atEndOfEncode()
  37. }
  38. // encDriver abstracts the actual codec (binc vs msgpack, etc)
  39. type encDriver interface {
  40. // IsBuiltinType(rt uintptr) bool
  41. EncodeBuiltin(rt uintptr, v interface{})
  42. EncodeNil()
  43. EncodeInt(i int64)
  44. EncodeUint(i uint64)
  45. EncodeBool(b bool)
  46. EncodeFloat32(f float32)
  47. EncodeFloat64(f float64)
  48. // encodeExtPreamble(xtag byte, length int)
  49. EncodeRawExt(re *RawExt, e *Encoder)
  50. EncodeExt(v interface{}, xtag uint64, ext Ext, e *Encoder)
  51. WriteArrayStart(length int)
  52. WriteArrayElem()
  53. WriteArrayEnd()
  54. WriteMapStart(length int)
  55. WriteMapElemKey()
  56. WriteMapElemValue()
  57. WriteMapEnd()
  58. EncodeString(c charEncoding, v string)
  59. EncodeSymbol(v string)
  60. EncodeStringBytes(c charEncoding, v []byte)
  61. //TODO
  62. //encBignum(f *big.Int)
  63. //encStringRunes(c charEncoding, v []rune)
  64. reset()
  65. atEndOfEncode()
  66. }
  67. type ioEncStringWriter interface {
  68. WriteString(s string) (n int, err error)
  69. }
  70. type encDriverAsis interface {
  71. EncodeAsis(v []byte)
  72. }
  73. // type encNoSeparator struct{}
  74. // func (_ encNoSeparator) EncodeEnd() {}
  75. type encDriverNoopContainerWriter struct{}
  76. func (_ encDriverNoopContainerWriter) WriteArrayStart(length int) {}
  77. func (_ encDriverNoopContainerWriter) WriteArrayElem() {}
  78. func (_ encDriverNoopContainerWriter) WriteArrayEnd() {}
  79. func (_ encDriverNoopContainerWriter) WriteMapStart(length int) {}
  80. func (_ encDriverNoopContainerWriter) WriteMapElemKey() {}
  81. func (_ encDriverNoopContainerWriter) WriteMapElemValue() {}
  82. func (_ encDriverNoopContainerWriter) WriteMapEnd() {}
  83. func (_ encDriverNoopContainerWriter) atEndOfEncode() {}
  84. // type ioEncWriterWriter interface {
  85. // WriteByte(c byte) error
  86. // WriteString(s string) (n int, err error)
  87. // Write(p []byte) (n int, err error)
  88. // }
  89. type EncodeOptions struct {
  90. // Encode a struct as an array, and not as a map
  91. StructToArray bool
  92. // Canonical representation means that encoding a value will always result in the same
  93. // sequence of bytes.
  94. //
  95. // This only affects maps, as the iteration order for maps is random.
  96. //
  97. // The implementation MAY use the natural sort order for the map keys if possible:
  98. //
  99. // - If there is a natural sort order (ie for number, bool, string or []byte keys),
  100. // then the map keys are first sorted in natural order and then written
  101. // with corresponding map values to the strema.
  102. // - If there is no natural sort order, then the map keys will first be
  103. // encoded into []byte, and then sorted,
  104. // before writing the sorted keys and the corresponding map values to the stream.
  105. //
  106. Canonical bool
  107. // CheckCircularRef controls whether we check for circular references
  108. // and error fast during an encode.
  109. //
  110. // If enabled, an error is received if a pointer to a struct
  111. // references itself either directly or through one of its fields (iteratively).
  112. //
  113. // This is opt-in, as there may be a performance hit to checking circular references.
  114. CheckCircularRef bool
  115. // RecursiveEmptyCheck controls whether we descend into interfaces, structs and pointers
  116. // when checking if a value is empty.
  117. //
  118. // Note that this may make OmitEmpty more expensive, as it incurs a lot more reflect calls.
  119. RecursiveEmptyCheck bool
  120. // Raw controls whether we encode Raw values.
  121. // This is a "dangerous" option and must be explicitly set.
  122. // If set, we blindly encode Raw values as-is, without checking
  123. // if they are a correct representation of a value in that format.
  124. // If unset, we error out.
  125. Raw bool
  126. // AsSymbols defines what should be encoded as symbols.
  127. //
  128. // Encoding as symbols can reduce the encoded size significantly.
  129. //
  130. // However, during decoding, each string to be encoded as a symbol must
  131. // be checked to see if it has been seen before. Consequently, encoding time
  132. // will increase if using symbols, because string comparisons has a clear cost.
  133. //
  134. // Sample values:
  135. // AsSymbolNone
  136. // AsSymbolAll
  137. // AsSymbolMapStringKeys
  138. // AsSymbolMapStringKeysFlag | AsSymbolStructFieldNameFlag
  139. AsSymbols AsSymbolFlag
  140. // WriterBufferSize is the size of the buffer used when writing.
  141. //
  142. // if > 0, we use a smart buffer internally for performance purposes.
  143. WriterBufferSize int
  144. }
  145. // ---------------------------------------------
  146. type simpleIoEncWriter struct {
  147. io.Writer
  148. }
  149. // type bufIoEncWriter struct {
  150. // w io.Writer
  151. // buf []byte
  152. // err error
  153. // }
  154. // func (x *bufIoEncWriter) Write(b []byte) (n int, err error) {
  155. // if x.err != nil {
  156. // return 0, x.err
  157. // }
  158. // if cap(x.buf)-len(x.buf) >= len(b) {
  159. // x.buf = append(x.buf, b)
  160. // return len(b), nil
  161. // }
  162. // n, err = x.w.Write(x.buf)
  163. // if err != nil {
  164. // x.err = err
  165. // return 0, x.err
  166. // }
  167. // n, err = x.w.Write(b)
  168. // x.err = err
  169. // return
  170. // }
  171. // ioEncWriter implements encWriter and can write to an io.Writer implementation
  172. type ioEncWriter struct {
  173. w io.Writer
  174. ww io.Writer
  175. bw io.ByteWriter
  176. sw ioEncStringWriter
  177. fw ioFlusher
  178. b [8]byte
  179. }
  180. func (z *ioEncWriter) WriteByte(b byte) (err error) {
  181. // x.bs[0] = b
  182. // _, err = x.ww.Write(x.bs[:])
  183. z.b[0] = b
  184. _, err = z.w.Write(z.b[:1])
  185. return
  186. }
  187. func (z *ioEncWriter) WriteString(s string) (n int, err error) {
  188. return z.w.Write(bytesView(s))
  189. }
  190. func (z *ioEncWriter) writeb(bs []byte) {
  191. // if len(bs) == 0 {
  192. // return
  193. // }
  194. if _, err := z.ww.Write(bs); err != nil {
  195. panic(err)
  196. }
  197. }
  198. func (z *ioEncWriter) writestr(s string) {
  199. // if len(s) == 0 {
  200. // return
  201. // }
  202. if _, err := z.sw.WriteString(s); err != nil {
  203. panic(err)
  204. }
  205. }
  206. func (z *ioEncWriter) writen1(b byte) {
  207. if err := z.bw.WriteByte(b); err != nil {
  208. panic(err)
  209. }
  210. }
  211. func (z *ioEncWriter) writen2(b1, b2 byte) {
  212. var err error
  213. if err = z.bw.WriteByte(b1); err == nil {
  214. if err = z.bw.WriteByte(b2); err == nil {
  215. return
  216. }
  217. }
  218. panic(err)
  219. }
  220. // func (z *ioEncWriter) writen5(b1, b2, b3, b4, b5 byte) {
  221. // z.b[0], z.b[1], z.b[2], z.b[3], z.b[4] = b1, b2, b3, b4, b5
  222. // if _, err := z.ww.Write(z.b[:5]); err != nil {
  223. // panic(err)
  224. // }
  225. // }
  226. func (z *ioEncWriter) atEndOfEncode() {
  227. if z.fw != nil {
  228. z.fw.Flush()
  229. }
  230. }
  231. // ----------------------------------------
  232. // bytesEncWriter implements encWriter and can write to an byte slice.
  233. // It is used by Marshal function.
  234. type bytesEncWriter struct {
  235. b []byte
  236. c int // cursor
  237. out *[]byte // write out on atEndOfEncode
  238. }
  239. func (z *bytesEncWriter) writeb(s []byte) {
  240. oc, a := z.growNoAlloc(len(s))
  241. if a {
  242. z.growAlloc(len(s), oc)
  243. }
  244. copy(z.b[oc:], s)
  245. }
  246. func (z *bytesEncWriter) writestr(s string) {
  247. oc, a := z.growNoAlloc(len(s))
  248. if a {
  249. z.growAlloc(len(s), oc)
  250. }
  251. copy(z.b[oc:], s)
  252. }
  253. func (z *bytesEncWriter) writen1(b1 byte) {
  254. oc, a := z.growNoAlloc(1)
  255. if a {
  256. z.growAlloc(1, oc)
  257. }
  258. z.b[oc] = b1
  259. }
  260. func (z *bytesEncWriter) writen2(b1, b2 byte) {
  261. oc, a := z.growNoAlloc(2)
  262. if a {
  263. z.growAlloc(2, oc)
  264. }
  265. z.b[oc+1] = b2
  266. z.b[oc] = b1
  267. }
  268. func (z *bytesEncWriter) atEndOfEncode() {
  269. *(z.out) = z.b[:z.c]
  270. }
  271. // have a growNoalloc(n int), which can be inlined.
  272. // if allocation is needed, then call growAlloc(n int)
  273. func (z *bytesEncWriter) growNoAlloc(n int) (oldcursor int, allocNeeded bool) {
  274. oldcursor = z.c
  275. z.c = z.c + n
  276. if z.c > len(z.b) {
  277. if z.c > cap(z.b) {
  278. allocNeeded = true
  279. } else {
  280. z.b = z.b[:cap(z.b)]
  281. }
  282. }
  283. return
  284. }
  285. func (z *bytesEncWriter) growAlloc(n int, oldcursor int) {
  286. // appendslice logic (if cap < 1024, *2, else *1.25): more expensive. many copy calls.
  287. // bytes.Buffer model (2*cap + n): much better
  288. // bs := make([]byte, 2*cap(z.b)+n)
  289. bs := make([]byte, growCap(cap(z.b), 1, n))
  290. copy(bs, z.b[:oldcursor])
  291. z.b = bs
  292. }
  293. // ---------------------------------------------
  294. func (e *Encoder) builtin(f *codecFnInfo, rv reflect.Value) {
  295. e.e.EncodeBuiltin(f.ti.rtid, rv2i(rv))
  296. }
  297. func (e *Encoder) rawExt(f *codecFnInfo, rv reflect.Value) {
  298. // rev := rv2i(rv).(RawExt)
  299. // e.e.EncodeRawExt(&rev, e)
  300. // var re *RawExt
  301. // if rv.CanAddr() {
  302. // re = rv2i(rv.Addr()).(*RawExt)
  303. // } else {
  304. // rev := rv2i(rv).(RawExt)
  305. // re = &rev
  306. // }
  307. // e.e.EncodeRawExt(re, e)
  308. e.e.EncodeRawExt(rv2i(rv).(*RawExt), e)
  309. }
  310. func (e *Encoder) ext(f *codecFnInfo, rv reflect.Value) {
  311. // if this is a struct|array and it was addressable, then pass the address directly (not the value)
  312. // if k := rv.Kind(); (k == reflect.Struct || k == reflect.Array) && rv.CanAddr() {
  313. // rv = rv.Addr()
  314. // }
  315. e.e.EncodeExt(rv2i(rv), f.xfTag, f.xfFn, e)
  316. }
  317. // func rviptr(rv reflect.Value) (v interface{}) {
  318. // // If a non-pointer was passed to Encode(), then that value is not addressable.
  319. // // Take addr if addressable, else copy value to an addressable value.
  320. // if rv.CanAddr() {
  321. // v = rv2i(rv.Addr())
  322. // } else {
  323. // rv2 := reflect.New(rv.Type())
  324. // rv2.Elem().Set(rv)
  325. // v = rv2i(rv2)
  326. // }
  327. // return v
  328. // }
  329. func (e *Encoder) selferMarshal(f *codecFnInfo, rv reflect.Value) {
  330. rv2i(rv).(Selfer).CodecEncodeSelf(e)
  331. }
  332. func (e *Encoder) binaryMarshal(f *codecFnInfo, rv reflect.Value) {
  333. bs, fnerr := rv2i(rv).(encoding.BinaryMarshaler).MarshalBinary()
  334. e.marshal(bs, fnerr, false, c_RAW)
  335. }
  336. func (e *Encoder) textMarshal(f *codecFnInfo, rv reflect.Value) {
  337. bs, fnerr := rv2i(rv).(encoding.TextMarshaler).MarshalText()
  338. e.marshal(bs, fnerr, false, c_UTF8)
  339. }
  340. func (e *Encoder) jsonMarshal(f *codecFnInfo, rv reflect.Value) {
  341. bs, fnerr := rv2i(rv).(jsonMarshaler).MarshalJSON()
  342. e.marshal(bs, fnerr, true, c_UTF8)
  343. }
  344. func (e *Encoder) raw(f *codecFnInfo, rv reflect.Value) {
  345. e.rawBytes(rv2i(rv).(Raw))
  346. }
  347. func (e *Encoder) kInvalid(f *codecFnInfo, rv reflect.Value) {
  348. e.e.EncodeNil()
  349. }
  350. func (e *Encoder) kErr(f *codecFnInfo, rv reflect.Value) {
  351. e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv)
  352. }
  353. func (e *Encoder) kSlice(f *codecFnInfo, rv reflect.Value) {
  354. ti := f.ti
  355. ee := e.e
  356. // array may be non-addressable, so we have to manage with care
  357. // (don't call rv.Bytes, rv.Slice, etc).
  358. // E.g. type struct S{B [2]byte};
  359. // Encode(S{}) will bomb on "panic: slice of unaddressable array".
  360. if f.seq != seqTypeArray {
  361. if rv.IsNil() {
  362. ee.EncodeNil()
  363. return
  364. }
  365. // If in this method, then there was no extension function defined.
  366. // So it's okay to treat as []byte.
  367. if ti.rtid == uint8SliceTypId {
  368. ee.EncodeStringBytes(c_RAW, rv.Bytes())
  369. return
  370. }
  371. }
  372. elemsep := e.hh.hasElemSeparators()
  373. rtelem := ti.rt.Elem()
  374. l := rv.Len()
  375. if ti.rtid == uint8SliceTypId || rtelem.Kind() == reflect.Uint8 {
  376. switch f.seq {
  377. case seqTypeArray:
  378. if rv.CanAddr() {
  379. ee.EncodeStringBytes(c_RAW, rv.Slice(0, l).Bytes())
  380. } else {
  381. var bs []byte
  382. if l <= cap(e.b) {
  383. bs = e.b[:l]
  384. } else {
  385. bs = make([]byte, l)
  386. }
  387. reflect.Copy(reflect.ValueOf(bs), rv)
  388. ee.EncodeStringBytes(c_RAW, bs)
  389. }
  390. return
  391. case seqTypeSlice:
  392. ee.EncodeStringBytes(c_RAW, rv.Bytes())
  393. return
  394. }
  395. }
  396. if ti.rtid == uint8SliceTypId && f.seq == seqTypeChan {
  397. bs := e.b[:0]
  398. // do not use range, so that the number of elements encoded
  399. // does not change, and encoding does not hang waiting on someone to close chan.
  400. // for b := range rv2i(rv).(<-chan byte) { bs = append(bs, b) }
  401. ch := rv2i(rv).(<-chan byte)
  402. for i := 0; i < l; i++ {
  403. bs = append(bs, <-ch)
  404. }
  405. ee.EncodeStringBytes(c_RAW, bs)
  406. return
  407. }
  408. if ti.mbs {
  409. if l%2 == 1 {
  410. e.errorf("mapBySlice requires even slice length, but got %v", l)
  411. return
  412. }
  413. ee.WriteMapStart(l / 2)
  414. } else {
  415. ee.WriteArrayStart(l)
  416. }
  417. if l > 0 {
  418. var fn *codecFn
  419. for rtelem.Kind() == reflect.Ptr {
  420. rtelem = rtelem.Elem()
  421. }
  422. // if kind is reflect.Interface, do not pre-determine the
  423. // encoding type, because preEncodeValue may break it down to
  424. // a concrete type and kInterface will bomb.
  425. if rtelem.Kind() != reflect.Interface {
  426. fn = e.cf.get(rtelem, true, true)
  427. }
  428. // TODO: Consider perf implication of encoding odd index values as symbols if type is string
  429. for j := 0; j < l; j++ {
  430. if elemsep {
  431. if ti.mbs {
  432. if j%2 == 0 {
  433. ee.WriteMapElemKey()
  434. } else {
  435. ee.WriteMapElemValue()
  436. }
  437. } else {
  438. ee.WriteArrayElem()
  439. }
  440. }
  441. if f.seq == seqTypeChan {
  442. if rv2, ok2 := rv.Recv(); ok2 {
  443. e.encodeValue(rv2, fn, true)
  444. } else {
  445. ee.EncodeNil() // WE HAVE TO DO SOMETHING, so nil if nothing received.
  446. }
  447. } else {
  448. e.encodeValue(rv.Index(j), fn, true)
  449. }
  450. }
  451. }
  452. if ti.mbs {
  453. ee.WriteMapEnd()
  454. } else {
  455. ee.WriteArrayEnd()
  456. }
  457. }
  458. func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) {
  459. fti := f.ti
  460. elemsep := e.hh.hasElemSeparators()
  461. tisfi := fti.sfip
  462. toMap := !(fti.toArray || e.h.StructToArray)
  463. if toMap {
  464. tisfi = fti.sfi
  465. }
  466. ee := e.e
  467. sfn := structFieldNode{v: rv, update: false}
  468. if toMap {
  469. ee.WriteMapStart(len(tisfi))
  470. // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
  471. asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
  472. if !elemsep {
  473. for _, si := range tisfi {
  474. if asSymbols {
  475. ee.EncodeSymbol(si.encName)
  476. } else {
  477. ee.EncodeString(c_UTF8, si.encName)
  478. }
  479. e.encodeValue(sfn.field(si), nil, true)
  480. }
  481. } else {
  482. for _, si := range tisfi {
  483. ee.WriteMapElemKey()
  484. if asSymbols {
  485. ee.EncodeSymbol(si.encName)
  486. } else {
  487. ee.EncodeString(c_UTF8, si.encName)
  488. }
  489. ee.WriteMapElemValue()
  490. e.encodeValue(sfn.field(si), nil, true)
  491. }
  492. }
  493. ee.WriteMapEnd()
  494. } else {
  495. ee.WriteArrayStart(len(tisfi))
  496. if !elemsep {
  497. for _, si := range tisfi {
  498. e.encodeValue(sfn.field(si), nil, true)
  499. }
  500. } else {
  501. for _, si := range tisfi {
  502. ee.WriteArrayElem()
  503. e.encodeValue(sfn.field(si), nil, true)
  504. }
  505. }
  506. ee.WriteArrayEnd()
  507. }
  508. }
  509. func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  510. fti := f.ti
  511. elemsep := e.hh.hasElemSeparators()
  512. tisfi := fti.sfip
  513. toMap := !(fti.toArray || e.h.StructToArray)
  514. // if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct)
  515. if toMap {
  516. tisfi = fti.sfi
  517. }
  518. newlen := len(fti.sfi)
  519. ee := e.e
  520. // Use sync.Pool to reduce allocating slices unnecessarily.
  521. // The cost of sync.Pool is less than the cost of new allocation.
  522. //
  523. // Each element of the array pools one of encStructPool(8|16|32|64).
  524. // It allows the re-use of slices up to 64 in length.
  525. // A performance cost of encoding structs was collecting
  526. // which values were empty and should be omitted.
  527. // We needed slices of reflect.Value and string to collect them.
  528. // This shared pool reduces the amount of unnecessary creation we do.
  529. // The cost is that of locking sometimes, but sync.Pool is efficient
  530. // enough to reduce thread contention.
  531. var spool *sync.Pool
  532. var poolv interface{}
  533. var fkvs []stringRv
  534. if newlen <= 8 {
  535. spool, poolv = pool.stringRv8()
  536. fkvs = poolv.(*[8]stringRv)[:newlen]
  537. } else if newlen <= 16 {
  538. spool, poolv = pool.stringRv16()
  539. fkvs = poolv.(*[16]stringRv)[:newlen]
  540. } else if newlen <= 32 {
  541. spool, poolv = pool.stringRv32()
  542. fkvs = poolv.(*[32]stringRv)[:newlen]
  543. } else if newlen <= 64 {
  544. spool, poolv = pool.stringRv64()
  545. fkvs = poolv.(*[64]stringRv)[:newlen]
  546. } else if newlen <= 128 {
  547. spool, poolv = pool.stringRv128()
  548. fkvs = poolv.(*[128]stringRv)[:newlen]
  549. } else {
  550. fkvs = make([]stringRv, newlen)
  551. }
  552. newlen = 0
  553. var kv stringRv
  554. recur := e.h.RecursiveEmptyCheck
  555. sfn := structFieldNode{v: rv, update: false}
  556. for _, si := range tisfi {
  557. // kv.r = si.field(rv, false)
  558. kv.r = sfn.field(si)
  559. if toMap {
  560. if si.omitEmpty && isEmptyValue(kv.r, recur, recur) {
  561. continue
  562. }
  563. kv.v = si.encName
  564. } else {
  565. // use the zero value.
  566. // if a reference or struct, set to nil (so you do not output too much)
  567. if si.omitEmpty && isEmptyValue(kv.r, recur, recur) {
  568. switch kv.r.Kind() {
  569. case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice:
  570. kv.r = reflect.Value{} //encode as nil
  571. }
  572. }
  573. }
  574. fkvs[newlen] = kv
  575. newlen++
  576. }
  577. if toMap {
  578. ee.WriteMapStart(newlen)
  579. // asSymbols := e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
  580. asSymbols := e.h.AsSymbols == AsSymbolDefault || e.h.AsSymbols&AsSymbolStructFieldNameFlag != 0
  581. if !elemsep {
  582. for j := 0; j < newlen; j++ {
  583. kv = fkvs[j]
  584. if asSymbols {
  585. ee.EncodeSymbol(kv.v)
  586. } else {
  587. ee.EncodeString(c_UTF8, kv.v)
  588. }
  589. e.encodeValue(kv.r, nil, true)
  590. }
  591. } else {
  592. for j := 0; j < newlen; j++ {
  593. kv = fkvs[j]
  594. ee.WriteMapElemKey()
  595. if asSymbols {
  596. ee.EncodeSymbol(kv.v)
  597. } else {
  598. ee.EncodeString(c_UTF8, kv.v)
  599. }
  600. ee.WriteMapElemValue()
  601. e.encodeValue(kv.r, nil, true)
  602. }
  603. }
  604. ee.WriteMapEnd()
  605. } else {
  606. ee.WriteArrayStart(newlen)
  607. if !elemsep {
  608. for j := 0; j < newlen; j++ {
  609. e.encodeValue(fkvs[j].r, nil, true)
  610. }
  611. } else {
  612. for j := 0; j < newlen; j++ {
  613. ee.WriteArrayElem()
  614. e.encodeValue(fkvs[j].r, nil, true)
  615. }
  616. }
  617. ee.WriteArrayEnd()
  618. }
  619. // do not use defer. Instead, use explicit pool return at end of function.
  620. // defer has a cost we are trying to avoid.
  621. // If there is a panic and these slices are not returned, it is ok.
  622. if spool != nil {
  623. spool.Put(poolv)
  624. }
  625. }
  626. func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) {
  627. ee := e.e
  628. if rv.IsNil() {
  629. ee.EncodeNil()
  630. return
  631. }
  632. l := rv.Len()
  633. ee.WriteMapStart(l)
  634. elemsep := e.hh.hasElemSeparators()
  635. if l == 0 {
  636. ee.WriteMapEnd()
  637. return
  638. }
  639. var asSymbols bool
  640. // determine the underlying key and val encFn's for the map.
  641. // This eliminates some work which is done for each loop iteration i.e.
  642. // rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn.
  643. //
  644. // However, if kind is reflect.Interface, do not pre-determine the
  645. // encoding type, because preEncodeValue may break it down to
  646. // a concrete type and kInterface will bomb.
  647. var keyFn, valFn *codecFn
  648. ti := f.ti
  649. rtkey0 := ti.rt.Key()
  650. rtkey := rtkey0
  651. rtval0 := ti.rt.Elem()
  652. rtval := rtval0
  653. rtkeyid := rt2id(rtkey0)
  654. for rtval.Kind() == reflect.Ptr {
  655. rtval = rtval.Elem()
  656. }
  657. if rtval.Kind() != reflect.Interface {
  658. valFn = e.cf.get(rtval, true, true)
  659. }
  660. mks := rv.MapKeys()
  661. if e.h.Canonical {
  662. e.kMapCanonical(rtkey, rv, mks, valFn, asSymbols)
  663. ee.WriteMapEnd()
  664. return
  665. }
  666. var keyTypeIsString = rtkeyid == stringTypId
  667. if keyTypeIsString {
  668. asSymbols = e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0
  669. } else {
  670. for rtkey.Kind() == reflect.Ptr {
  671. rtkey = rtkey.Elem()
  672. }
  673. if rtkey.Kind() != reflect.Interface {
  674. rtkeyid = rt2id(rtkey)
  675. keyFn = e.cf.get(rtkey, true, true)
  676. }
  677. }
  678. // for j, lmks := 0, len(mks); j < lmks; j++ {
  679. for j := range mks {
  680. if elemsep {
  681. ee.WriteMapElemKey()
  682. }
  683. if keyTypeIsString {
  684. if asSymbols {
  685. ee.EncodeSymbol(mks[j].String())
  686. } else {
  687. ee.EncodeString(c_UTF8, mks[j].String())
  688. }
  689. } else {
  690. e.encodeValue(mks[j], keyFn, true)
  691. }
  692. if elemsep {
  693. ee.WriteMapElemValue()
  694. }
  695. e.encodeValue(rv.MapIndex(mks[j]), valFn, true)
  696. }
  697. ee.WriteMapEnd()
  698. }
  699. func (e *Encoder) kMapCanonical(rtkey reflect.Type, rv reflect.Value, mks []reflect.Value, valFn *codecFn, asSymbols bool) {
  700. ee := e.e
  701. elemsep := e.hh.hasElemSeparators()
  702. // we previously did out-of-band if an extension was registered.
  703. // This is not necessary, as the natural kind is sufficient for ordering.
  704. // WHAT IS THIS? rtkeyid can never be a []uint8, per spec
  705. // if rtkeyid == uint8SliceTypId {
  706. // mksv := make([]bytesRv, len(mks))
  707. // for i, k := range mks {
  708. // v := &mksv[i]
  709. // v.r = k
  710. // v.v = k.Bytes()
  711. // }
  712. // sort.Sort(bytesRvSlice(mksv))
  713. // for i := range mksv {
  714. // if elemsep {
  715. // ee.WriteMapElemKey()
  716. // }
  717. // ee.EncodeStringBytes(c_RAW, mksv[i].v)
  718. // if elemsep {
  719. // ee.WriteMapElemValue()
  720. // }
  721. // e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  722. // }
  723. // return
  724. // }
  725. switch rtkey.Kind() {
  726. case reflect.Bool:
  727. mksv := make([]boolRv, len(mks))
  728. for i, k := range mks {
  729. v := &mksv[i]
  730. v.r = k
  731. v.v = k.Bool()
  732. }
  733. sort.Sort(boolRvSlice(mksv))
  734. for i := range mksv {
  735. if elemsep {
  736. ee.WriteMapElemKey()
  737. }
  738. ee.EncodeBool(mksv[i].v)
  739. if elemsep {
  740. ee.WriteMapElemValue()
  741. }
  742. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  743. }
  744. case reflect.String:
  745. mksv := make([]stringRv, len(mks))
  746. for i, k := range mks {
  747. v := &mksv[i]
  748. v.r = k
  749. v.v = k.String()
  750. }
  751. sort.Sort(stringRvSlice(mksv))
  752. for i := range mksv {
  753. if elemsep {
  754. ee.WriteMapElemKey()
  755. }
  756. if asSymbols {
  757. ee.EncodeSymbol(mksv[i].v)
  758. } else {
  759. ee.EncodeString(c_UTF8, mksv[i].v)
  760. }
  761. if elemsep {
  762. ee.WriteMapElemValue()
  763. }
  764. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  765. }
  766. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
  767. mksv := make([]uintRv, len(mks))
  768. for i, k := range mks {
  769. v := &mksv[i]
  770. v.r = k
  771. v.v = k.Uint()
  772. }
  773. sort.Sort(uintRvSlice(mksv))
  774. for i := range mksv {
  775. if elemsep {
  776. ee.WriteMapElemKey()
  777. }
  778. ee.EncodeUint(mksv[i].v)
  779. if elemsep {
  780. ee.WriteMapElemValue()
  781. }
  782. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  783. }
  784. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  785. mksv := make([]intRv, len(mks))
  786. for i, k := range mks {
  787. v := &mksv[i]
  788. v.r = k
  789. v.v = k.Int()
  790. }
  791. sort.Sort(intRvSlice(mksv))
  792. for i := range mksv {
  793. if elemsep {
  794. ee.WriteMapElemKey()
  795. }
  796. ee.EncodeInt(mksv[i].v)
  797. if elemsep {
  798. ee.WriteMapElemValue()
  799. }
  800. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  801. }
  802. case reflect.Float32:
  803. mksv := make([]floatRv, len(mks))
  804. for i, k := range mks {
  805. v := &mksv[i]
  806. v.r = k
  807. v.v = k.Float()
  808. }
  809. sort.Sort(floatRvSlice(mksv))
  810. for i := range mksv {
  811. if elemsep {
  812. ee.WriteMapElemKey()
  813. }
  814. ee.EncodeFloat32(float32(mksv[i].v))
  815. if elemsep {
  816. ee.WriteMapElemValue()
  817. }
  818. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  819. }
  820. case reflect.Float64:
  821. mksv := make([]floatRv, len(mks))
  822. for i, k := range mks {
  823. v := &mksv[i]
  824. v.r = k
  825. v.v = k.Float()
  826. }
  827. sort.Sort(floatRvSlice(mksv))
  828. for i := range mksv {
  829. if elemsep {
  830. ee.WriteMapElemKey()
  831. }
  832. ee.EncodeFloat64(mksv[i].v)
  833. if elemsep {
  834. ee.WriteMapElemValue()
  835. }
  836. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  837. }
  838. default:
  839. // out-of-band
  840. // first encode each key to a []byte first, then sort them, then record
  841. var mksv []byte = make([]byte, 0, len(mks)*16) // temporary byte slice for the encoding
  842. e2 := NewEncoderBytes(&mksv, e.hh)
  843. mksbv := make([]bytesRv, len(mks))
  844. for i, k := range mks {
  845. v := &mksbv[i]
  846. l := len(mksv)
  847. e2.MustEncode(k)
  848. v.r = k
  849. v.v = mksv[l:]
  850. }
  851. sort.Sort(bytesRvSlice(mksbv))
  852. for j := range mksbv {
  853. if elemsep {
  854. ee.WriteMapElemKey()
  855. }
  856. e.asis(mksbv[j].v)
  857. if elemsep {
  858. ee.WriteMapElemValue()
  859. }
  860. e.encodeValue(rv.MapIndex(mksbv[j].r), valFn, true)
  861. }
  862. }
  863. }
  864. // // --------------------------------------------------
  865. // An Encoder writes an object to an output stream in the codec format.
  866. type Encoder struct {
  867. // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder
  868. e encDriver
  869. // NOTE: Encoder shouldn't call it's write methods,
  870. // as the handler MAY need to do some coordination.
  871. w encWriter
  872. hh Handle
  873. h *BasicHandle
  874. // ---- cpu cache line boundary?
  875. wi ioEncWriter
  876. wb bytesEncWriter
  877. bw bufio.Writer
  878. // cr containerStateRecv
  879. as encDriverAsis
  880. // ---- cpu cache line boundary?
  881. ci set
  882. err error
  883. b [scratchByteArrayLen]byte
  884. cf codecFner
  885. }
  886. // NewEncoder returns an Encoder for encoding into an io.Writer.
  887. //
  888. // For efficiency, Users are encouraged to pass in a memory buffered writer
  889. // (eg bufio.Writer, bytes.Buffer).
  890. func NewEncoder(w io.Writer, h Handle) *Encoder {
  891. e := newEncoder(h)
  892. e.Reset(w)
  893. return e
  894. }
  895. // NewEncoderBytes returns an encoder for encoding directly and efficiently
  896. // into a byte slice, using zero-copying to temporary slices.
  897. //
  898. // It will potentially replace the output byte slice pointed to.
  899. // After encoding, the out parameter contains the encoded contents.
  900. func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
  901. e := newEncoder(h)
  902. e.ResetBytes(out)
  903. return e
  904. }
  905. func newEncoder(h Handle) *Encoder {
  906. e := &Encoder{hh: h, h: h.getBasicHandle()}
  907. e.e = h.newEncDriver(e)
  908. e.as, _ = e.e.(encDriverAsis)
  909. // e.cr, _ = e.e.(containerStateRecv)
  910. return e
  911. }
  912. // Reset the Encoder with a new output stream.
  913. //
  914. // This accommodates using the state of the Encoder,
  915. // where it has "cached" information about sub-engines.
  916. func (e *Encoder) Reset(w io.Writer) {
  917. var ok bool
  918. e.wi.w = w
  919. if e.h.WriterBufferSize > 0 {
  920. bw := bufio.NewWriterSize(w, e.h.WriterBufferSize)
  921. e.bw = *bw
  922. e.wi.bw = &e.bw
  923. e.wi.sw = &e.bw
  924. e.wi.fw = &e.bw
  925. e.wi.ww = &e.bw
  926. } else {
  927. if e.wi.bw, ok = w.(io.ByteWriter); !ok {
  928. e.wi.bw = &e.wi
  929. }
  930. if e.wi.sw, ok = w.(ioEncStringWriter); !ok {
  931. e.wi.sw = &e.wi
  932. }
  933. e.wi.fw, _ = w.(ioFlusher)
  934. e.wi.ww = w
  935. }
  936. e.w = &e.wi
  937. e.e.reset()
  938. e.cf.reset(e.hh)
  939. e.err = nil
  940. }
  941. func (e *Encoder) ResetBytes(out *[]byte) {
  942. in := *out
  943. if in == nil {
  944. in = make([]byte, defEncByteBufSize)
  945. }
  946. e.wb.b, e.wb.out, e.wb.c = in, out, 0
  947. e.w = &e.wb
  948. e.e.reset()
  949. e.cf.reset(e.hh)
  950. e.err = nil
  951. }
  952. // Encode writes an object into a stream.
  953. //
  954. // Encoding can be configured via the struct tag for the fields.
  955. // The "codec" key in struct field's tag value is the key name,
  956. // followed by an optional comma and options.
  957. // Note that the "json" key is used in the absence of the "codec" key.
  958. //
  959. // To set an option on all fields (e.g. omitempty on all fields), you
  960. // can create a field called _struct, and set flags on it.
  961. //
  962. // Struct values "usually" encode as maps. Each exported struct field is encoded unless:
  963. // - the field's tag is "-", OR
  964. // - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
  965. //
  966. // When encoding as a map, the first string in the tag (before the comma)
  967. // is the map key string to use when encoding.
  968. //
  969. // However, struct values may encode as arrays. This happens when:
  970. // - StructToArray Encode option is set, OR
  971. // - the tag on the _struct field sets the "toarray" option
  972. // Note that omitempty is ignored when encoding struct values as arrays,
  973. // as an entry must be encoded for each field, to maintain its position.
  974. //
  975. // Values with types that implement MapBySlice are encoded as stream maps.
  976. //
  977. // The empty values (for omitempty option) are false, 0, any nil pointer
  978. // or interface value, and any array, slice, map, or string of length zero.
  979. //
  980. // Anonymous fields are encoded inline except:
  981. // - the struct tag specifies a replacement name (first value)
  982. // - the field is of an interface type
  983. //
  984. // Examples:
  985. //
  986. // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
  987. // type MyStruct struct {
  988. // _struct bool `codec:",omitempty"` //set omitempty for every field
  989. // Field1 string `codec:"-"` //skip this field
  990. // Field2 int `codec:"myName"` //Use key "myName" in encode stream
  991. // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
  992. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
  993. // io.Reader //use key "Reader".
  994. // MyStruct `codec:"my1" //use key "my1".
  995. // MyStruct //inline it
  996. // ...
  997. // }
  998. //
  999. // type MyStruct struct {
  1000. // _struct bool `codec:",toarray"` //encode struct as an array
  1001. // }
  1002. //
  1003. // The mode of encoding is based on the type of the value. When a value is seen:
  1004. // - If a Selfer, call its CodecEncodeSelf method
  1005. // - If an extension is registered for it, call that extension function
  1006. // - If it implements encoding.(Binary|Text|JSON)Marshaler, call its Marshal(Binary|Text|JSON) method
  1007. // - Else encode it based on its reflect.Kind
  1008. //
  1009. // Note that struct field names and keys in map[string]XXX will be treated as symbols.
  1010. // Some formats support symbols (e.g. binc) and will properly encode the string
  1011. // only once in the stream, and use a tag to refer to it thereafter.
  1012. func (e *Encoder) Encode(v interface{}) (err error) {
  1013. defer panicToErrs2(&e.err, &err)
  1014. e.MustEncode(v)
  1015. return
  1016. }
  1017. // MustEncode is like Encode, but panics if unable to Encode.
  1018. // This provides insight to the code location that triggered the error.
  1019. func (e *Encoder) MustEncode(v interface{}) {
  1020. if e.err != nil {
  1021. panic(e.err)
  1022. }
  1023. e.encode(v)
  1024. e.e.atEndOfEncode()
  1025. e.w.atEndOfEncode()
  1026. }
  1027. func (e *Encoder) encode(iv interface{}) {
  1028. if iv == nil || definitelyNil(iv) {
  1029. e.e.EncodeNil()
  1030. return
  1031. }
  1032. if v, ok := iv.(Selfer); ok {
  1033. v.CodecEncodeSelf(e)
  1034. return
  1035. }
  1036. switch v := iv.(type) {
  1037. // case nil:
  1038. // e.e.EncodeNil()
  1039. // case Selfer:
  1040. // v.CodecEncodeSelf(e)
  1041. case Raw:
  1042. e.rawBytes(v)
  1043. case reflect.Value:
  1044. e.encodeValue(v, nil, true)
  1045. case string:
  1046. e.e.EncodeString(c_UTF8, v)
  1047. case bool:
  1048. e.e.EncodeBool(v)
  1049. case int:
  1050. e.e.EncodeInt(int64(v))
  1051. case int8:
  1052. e.e.EncodeInt(int64(v))
  1053. case int16:
  1054. e.e.EncodeInt(int64(v))
  1055. case int32:
  1056. e.e.EncodeInt(int64(v))
  1057. case int64:
  1058. e.e.EncodeInt(v)
  1059. case uint:
  1060. e.e.EncodeUint(uint64(v))
  1061. case uint8:
  1062. e.e.EncodeUint(uint64(v))
  1063. case uint16:
  1064. e.e.EncodeUint(uint64(v))
  1065. case uint32:
  1066. e.e.EncodeUint(uint64(v))
  1067. case uint64:
  1068. e.e.EncodeUint(v)
  1069. case uintptr:
  1070. e.e.EncodeUint(uint64(v))
  1071. case float32:
  1072. e.e.EncodeFloat32(v)
  1073. case float64:
  1074. e.e.EncodeFloat64(v)
  1075. case []uint8:
  1076. e.e.EncodeStringBytes(c_RAW, v)
  1077. case *string:
  1078. e.e.EncodeString(c_UTF8, *v)
  1079. case *bool:
  1080. e.e.EncodeBool(*v)
  1081. case *int:
  1082. e.e.EncodeInt(int64(*v))
  1083. case *int8:
  1084. e.e.EncodeInt(int64(*v))
  1085. case *int16:
  1086. e.e.EncodeInt(int64(*v))
  1087. case *int32:
  1088. e.e.EncodeInt(int64(*v))
  1089. case *int64:
  1090. e.e.EncodeInt(*v)
  1091. case *uint:
  1092. e.e.EncodeUint(uint64(*v))
  1093. case *uint8:
  1094. e.e.EncodeUint(uint64(*v))
  1095. case *uint16:
  1096. e.e.EncodeUint(uint64(*v))
  1097. case *uint32:
  1098. e.e.EncodeUint(uint64(*v))
  1099. case *uint64:
  1100. e.e.EncodeUint(*v)
  1101. case *uintptr:
  1102. e.e.EncodeUint(uint64(*v))
  1103. case *float32:
  1104. e.e.EncodeFloat32(*v)
  1105. case *float64:
  1106. e.e.EncodeFloat64(*v)
  1107. case *[]uint8:
  1108. e.e.EncodeStringBytes(c_RAW, *v)
  1109. default:
  1110. if !fastpathEncodeTypeSwitch(iv, e) {
  1111. // checkfastpath=true (not false), as underlying slice/map type may be fast-path
  1112. e.encodeValue(reflect.ValueOf(iv), nil, true)
  1113. }
  1114. }
  1115. }
  1116. func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn, checkFastpath bool) {
  1117. // if a valid fn is passed, it MUST BE for the dereferenced type of rv
  1118. var sptr uintptr
  1119. var rvp reflect.Value
  1120. var rvpValid bool
  1121. TOP:
  1122. switch rv.Kind() {
  1123. case reflect.Ptr:
  1124. if rv.IsNil() {
  1125. e.e.EncodeNil()
  1126. return
  1127. }
  1128. rvpValid = true
  1129. rvp = rv
  1130. rv = rv.Elem()
  1131. if e.h.CheckCircularRef && rv.Kind() == reflect.Struct {
  1132. // TODO: Movable pointers will be an issue here. Future problem.
  1133. sptr = rv.UnsafeAddr()
  1134. break TOP
  1135. }
  1136. goto TOP
  1137. case reflect.Interface:
  1138. if rv.IsNil() {
  1139. e.e.EncodeNil()
  1140. return
  1141. }
  1142. rv = rv.Elem()
  1143. goto TOP
  1144. case reflect.Slice, reflect.Map:
  1145. if rv.IsNil() {
  1146. e.e.EncodeNil()
  1147. return
  1148. }
  1149. case reflect.Invalid, reflect.Func:
  1150. e.e.EncodeNil()
  1151. return
  1152. }
  1153. if sptr != 0 && (&e.ci).add(sptr) {
  1154. e.errorf("circular reference found: # %d", sptr)
  1155. }
  1156. if fn == nil {
  1157. rt := rv.Type()
  1158. // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer
  1159. fn = e.cf.get(rt, checkFastpath, true)
  1160. }
  1161. if fn.i.addrE {
  1162. if rvpValid {
  1163. fn.fe(e, &fn.i, rvp)
  1164. } else if rv.CanAddr() {
  1165. fn.fe(e, &fn.i, rv.Addr())
  1166. } else {
  1167. rv2 := reflect.New(rv.Type())
  1168. rv2.Elem().Set(rv)
  1169. fn.fe(e, &fn.i, rv2)
  1170. }
  1171. } else {
  1172. fn.fe(e, &fn.i, rv)
  1173. }
  1174. if sptr != 0 {
  1175. (&e.ci).remove(sptr)
  1176. }
  1177. }
  1178. func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) {
  1179. if fnerr != nil {
  1180. panic(fnerr)
  1181. }
  1182. if bs == nil {
  1183. e.e.EncodeNil()
  1184. } else if asis {
  1185. e.asis(bs)
  1186. } else {
  1187. e.e.EncodeStringBytes(c, bs)
  1188. }
  1189. }
  1190. func (e *Encoder) asis(v []byte) {
  1191. if e.as == nil {
  1192. e.w.writeb(v)
  1193. } else {
  1194. e.as.EncodeAsis(v)
  1195. }
  1196. }
  1197. func (e *Encoder) rawBytes(vv Raw) {
  1198. v := []byte(vv)
  1199. if !e.h.Raw {
  1200. e.errorf("Raw values cannot be encoded: %v", v)
  1201. }
  1202. if e.as == nil {
  1203. e.w.writeb(v)
  1204. } else {
  1205. e.as.EncodeAsis(v)
  1206. }
  1207. }
  1208. func (e *Encoder) errorf(format string, params ...interface{}) {
  1209. err := fmt.Errorf(format, params...)
  1210. panic(err)
  1211. }