encode.go 34 KB

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