encode.go 33 KB

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