encode.go 35 KB

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