encode.go 34 KB

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