encode.go 34 KB

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