encode.go 34 KB

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