encode.go 36 KB

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