encode.go 36 KB

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