encode.go 34 KB

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