encode.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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. encStructFieldKey(ee, fti.keyType, si.encName)
  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. encStructFieldKey(ee, fti.keyType, si.encName)
  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 encStructFieldKey(ee encDriver, keyType valueType, s string) {
  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. ee.EncodeString(cUTF8, s)
  473. } else if keyType == valueTypeInt {
  474. ee.EncodeInt(m.Int(strconv.ParseInt(s, 10, 64)))
  475. } else if keyType == valueTypeUint {
  476. ee.EncodeUint(m.Uint(strconv.ParseUint(s, 10, 64)))
  477. } else if keyType == valueTypeFloat {
  478. ee.EncodeFloat64(m.Float(strconv.ParseFloat(s, 64)))
  479. } else {
  480. ee.EncodeString(cUTF8, s)
  481. }
  482. }
  483. func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  484. fti := f.ti
  485. elemsep := e.esep
  486. tisfi := fti.sfiSrc
  487. toMap := !(fti.toArray || e.h.StructToArray)
  488. // if toMap, use the sorted array. If toArray, use unsorted array (to match sequence in struct)
  489. if toMap {
  490. tisfi = fti.sfiSort
  491. }
  492. newlen := len(fti.sfiSort)
  493. ee := e.e
  494. // Use sync.Pool to reduce allocating slices unnecessarily.
  495. // The cost of sync.Pool is less than the cost of new allocation.
  496. //
  497. // Each element of the array pools one of encStructPool(8|16|32|64).
  498. // It allows the re-use of slices up to 64 in length.
  499. // A performance cost of encoding structs was collecting
  500. // which values were empty and should be omitted.
  501. // We needed slices of reflect.Value and string to collect them.
  502. // This shared pool reduces the amount of unnecessary creation we do.
  503. // The cost is that of locking sometimes, but sync.Pool is efficient
  504. // enough to reduce thread contention.
  505. var spool *sync.Pool
  506. var poolv interface{}
  507. var fkvs []stringRv
  508. // fmt.Printf(">>>>>>>>>>>>>> encode.kStruct: newlen: %d\n", newlen)
  509. if newlen <= 8 {
  510. spool, poolv = pool.stringRv8()
  511. fkvs = poolv.(*[8]stringRv)[:newlen]
  512. } else if newlen <= 16 {
  513. spool, poolv = pool.stringRv16()
  514. fkvs = poolv.(*[16]stringRv)[:newlen]
  515. } else if newlen <= 32 {
  516. spool, poolv = pool.stringRv32()
  517. fkvs = poolv.(*[32]stringRv)[:newlen]
  518. } else if newlen <= 64 {
  519. spool, poolv = pool.stringRv64()
  520. fkvs = poolv.(*[64]stringRv)[:newlen]
  521. } else if newlen <= 128 {
  522. spool, poolv = pool.stringRv128()
  523. fkvs = poolv.(*[128]stringRv)[:newlen]
  524. } else {
  525. fkvs = make([]stringRv, newlen)
  526. }
  527. newlen = 0
  528. var kv stringRv
  529. recur := e.h.RecursiveEmptyCheck
  530. sfn := structFieldNode{v: rv, update: false}
  531. for _, si := range tisfi {
  532. // kv.r = si.field(rv, false)
  533. kv.r = sfn.field(si)
  534. if toMap {
  535. if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) {
  536. continue
  537. }
  538. kv.v = si.encName
  539. } else {
  540. // use the zero value.
  541. // if a reference or struct, set to nil (so you do not output too much)
  542. if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) {
  543. switch kv.r.Kind() {
  544. case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice:
  545. kv.r = reflect.Value{} //encode as nil
  546. }
  547. }
  548. }
  549. fkvs[newlen] = kv
  550. newlen++
  551. }
  552. if toMap {
  553. ee.WriteMapStart(newlen)
  554. if elemsep {
  555. for j := 0; j < newlen; j++ {
  556. kv = fkvs[j]
  557. ee.WriteMapElemKey()
  558. // ee.EncodeString(cUTF8, kv.v)
  559. encStructFieldKey(ee, fti.keyType, kv.v)
  560. ee.WriteMapElemValue()
  561. e.encodeValue(kv.r, nil, true)
  562. }
  563. } else {
  564. for j := 0; j < newlen; j++ {
  565. kv = fkvs[j]
  566. // ee.EncodeString(cUTF8, kv.v)
  567. encStructFieldKey(ee, fti.keyType, kv.v)
  568. e.encodeValue(kv.r, nil, true)
  569. }
  570. }
  571. ee.WriteMapEnd()
  572. } else {
  573. ee.WriteArrayStart(newlen)
  574. if elemsep {
  575. for j := 0; j < newlen; j++ {
  576. ee.WriteArrayElem()
  577. e.encodeValue(fkvs[j].r, nil, true)
  578. }
  579. } else {
  580. for j := 0; j < newlen; j++ {
  581. e.encodeValue(fkvs[j].r, nil, true)
  582. }
  583. }
  584. ee.WriteArrayEnd()
  585. }
  586. // do not use defer. Instead, use explicit pool return at end of function.
  587. // defer has a cost we are trying to avoid.
  588. // If there is a panic and these slices are not returned, it is ok.
  589. if spool != nil {
  590. spool.Put(poolv)
  591. }
  592. }
  593. func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) {
  594. ee := e.e
  595. if rv.IsNil() {
  596. ee.EncodeNil()
  597. return
  598. }
  599. l := rv.Len()
  600. ee.WriteMapStart(l)
  601. elemsep := e.esep
  602. if l == 0 {
  603. ee.WriteMapEnd()
  604. return
  605. }
  606. // var asSymbols bool
  607. // determine the underlying key and val encFn's for the map.
  608. // This eliminates some work which is done for each loop iteration i.e.
  609. // rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn.
  610. //
  611. // However, if kind is reflect.Interface, do not pre-determine the
  612. // encoding type, because preEncodeValue may break it down to
  613. // a concrete type and kInterface will bomb.
  614. var keyFn, valFn *codecFn
  615. ti := f.ti
  616. rtkey0 := ti.key
  617. rtkey := rtkey0
  618. rtval0 := ti.elem
  619. rtval := rtval0
  620. // rtkeyid := rt2id(rtkey0)
  621. for rtval.Kind() == reflect.Ptr {
  622. rtval = rtval.Elem()
  623. }
  624. if rtval.Kind() != reflect.Interface {
  625. valFn = e.cfer().get(rtval, true, true)
  626. }
  627. mks := rv.MapKeys()
  628. if e.h.Canonical {
  629. e.kMapCanonical(rtkey, rv, mks, valFn)
  630. ee.WriteMapEnd()
  631. return
  632. }
  633. var keyTypeIsString = stringTypId == rt2id(rtkey0) // rtkeyid
  634. if !keyTypeIsString {
  635. for rtkey.Kind() == reflect.Ptr {
  636. rtkey = rtkey.Elem()
  637. }
  638. if rtkey.Kind() != reflect.Interface {
  639. // rtkeyid = rt2id(rtkey)
  640. keyFn = e.cfer().get(rtkey, true, true)
  641. }
  642. }
  643. // for j, lmks := 0, len(mks); j < lmks; j++ {
  644. for j := range mks {
  645. if elemsep {
  646. ee.WriteMapElemKey()
  647. }
  648. if keyTypeIsString {
  649. ee.EncodeString(cUTF8, mks[j].String())
  650. } else {
  651. e.encodeValue(mks[j], keyFn, true)
  652. }
  653. if elemsep {
  654. ee.WriteMapElemValue()
  655. }
  656. e.encodeValue(rv.MapIndex(mks[j]), valFn, true)
  657. }
  658. ee.WriteMapEnd()
  659. }
  660. func (e *Encoder) kMapCanonical(rtkey reflect.Type, rv reflect.Value, mks []reflect.Value, valFn *codecFn) {
  661. ee := e.e
  662. elemsep := e.esep
  663. // we previously did out-of-band if an extension was registered.
  664. // This is not necessary, as the natural kind is sufficient for ordering.
  665. switch rtkey.Kind() {
  666. case reflect.Bool:
  667. mksv := make([]boolRv, len(mks))
  668. for i, k := range mks {
  669. v := &mksv[i]
  670. v.r = k
  671. v.v = k.Bool()
  672. }
  673. sort.Sort(boolRvSlice(mksv))
  674. for i := range mksv {
  675. if elemsep {
  676. ee.WriteMapElemKey()
  677. }
  678. ee.EncodeBool(mksv[i].v)
  679. if elemsep {
  680. ee.WriteMapElemValue()
  681. }
  682. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  683. }
  684. case reflect.String:
  685. mksv := make([]stringRv, len(mks))
  686. for i, k := range mks {
  687. v := &mksv[i]
  688. v.r = k
  689. v.v = k.String()
  690. }
  691. sort.Sort(stringRvSlice(mksv))
  692. for i := range mksv {
  693. if elemsep {
  694. ee.WriteMapElemKey()
  695. }
  696. ee.EncodeString(cUTF8, mksv[i].v)
  697. if elemsep {
  698. ee.WriteMapElemValue()
  699. }
  700. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  701. }
  702. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
  703. mksv := make([]uintRv, len(mks))
  704. for i, k := range mks {
  705. v := &mksv[i]
  706. v.r = k
  707. v.v = k.Uint()
  708. }
  709. sort.Sort(uintRvSlice(mksv))
  710. for i := range mksv {
  711. if elemsep {
  712. ee.WriteMapElemKey()
  713. }
  714. ee.EncodeUint(mksv[i].v)
  715. if elemsep {
  716. ee.WriteMapElemValue()
  717. }
  718. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  719. }
  720. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  721. mksv := make([]intRv, len(mks))
  722. for i, k := range mks {
  723. v := &mksv[i]
  724. v.r = k
  725. v.v = k.Int()
  726. }
  727. sort.Sort(intRvSlice(mksv))
  728. for i := range mksv {
  729. if elemsep {
  730. ee.WriteMapElemKey()
  731. }
  732. ee.EncodeInt(mksv[i].v)
  733. if elemsep {
  734. ee.WriteMapElemValue()
  735. }
  736. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  737. }
  738. case reflect.Float32:
  739. mksv := make([]floatRv, len(mks))
  740. for i, k := range mks {
  741. v := &mksv[i]
  742. v.r = k
  743. v.v = k.Float()
  744. }
  745. sort.Sort(floatRvSlice(mksv))
  746. for i := range mksv {
  747. if elemsep {
  748. ee.WriteMapElemKey()
  749. }
  750. ee.EncodeFloat32(float32(mksv[i].v))
  751. if elemsep {
  752. ee.WriteMapElemValue()
  753. }
  754. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  755. }
  756. case reflect.Float64:
  757. mksv := make([]floatRv, len(mks))
  758. for i, k := range mks {
  759. v := &mksv[i]
  760. v.r = k
  761. v.v = k.Float()
  762. }
  763. sort.Sort(floatRvSlice(mksv))
  764. for i := range mksv {
  765. if elemsep {
  766. ee.WriteMapElemKey()
  767. }
  768. ee.EncodeFloat64(mksv[i].v)
  769. if elemsep {
  770. ee.WriteMapElemValue()
  771. }
  772. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  773. }
  774. case reflect.Struct:
  775. if rv.Type() == timeTyp {
  776. mksv := make([]timeRv, len(mks))
  777. for i, k := range mks {
  778. v := &mksv[i]
  779. v.r = k
  780. v.v = rv2i(k).(time.Time)
  781. }
  782. sort.Sort(timeRvSlice(mksv))
  783. for i := range mksv {
  784. if elemsep {
  785. ee.WriteMapElemKey()
  786. }
  787. ee.EncodeTime(mksv[i].v)
  788. if elemsep {
  789. ee.WriteMapElemValue()
  790. }
  791. e.encodeValue(rv.MapIndex(mksv[i].r), valFn, true)
  792. }
  793. break
  794. }
  795. fallthrough
  796. default:
  797. // out-of-band
  798. // first encode each key to a []byte first, then sort them, then record
  799. var mksv []byte = make([]byte, 0, len(mks)*16) // temporary byte slice for the encoding
  800. e2 := NewEncoderBytes(&mksv, e.hh)
  801. mksbv := make([]bytesRv, len(mks))
  802. for i, k := range mks {
  803. v := &mksbv[i]
  804. l := len(mksv)
  805. e2.MustEncode(k)
  806. v.r = k
  807. v.v = mksv[l:]
  808. }
  809. sort.Sort(bytesRvSlice(mksbv))
  810. for j := range mksbv {
  811. if elemsep {
  812. ee.WriteMapElemKey()
  813. }
  814. e.asis(mksbv[j].v)
  815. if elemsep {
  816. ee.WriteMapElemValue()
  817. }
  818. e.encodeValue(rv.MapIndex(mksbv[j].r), valFn, true)
  819. }
  820. }
  821. }
  822. // // --------------------------------------------------
  823. type encWriterSwitch struct {
  824. wi *ioEncWriter
  825. // wb bytesEncWriter
  826. wb bytesEncAppender
  827. wx bool // if bytes, wx=true
  828. esep bool // whether it has elem separators
  829. isas bool // whether e.as != nil
  830. }
  831. // // TODO: Uncomment after mid-stack inlining enabled in go 1.11
  832. // func (z *encWriterSwitch) writeb(s []byte) {
  833. // if z.wx {
  834. // z.wb.writeb(s)
  835. // } else {
  836. // z.wi.writeb(s)
  837. // }
  838. // }
  839. // func (z *encWriterSwitch) writestr(s string) {
  840. // if z.wx {
  841. // z.wb.writestr(s)
  842. // } else {
  843. // z.wi.writestr(s)
  844. // }
  845. // }
  846. // func (z *encWriterSwitch) writen1(b1 byte) {
  847. // if z.wx {
  848. // z.wb.writen1(b1)
  849. // } else {
  850. // z.wi.writen1(b1)
  851. // }
  852. // }
  853. // func (z *encWriterSwitch) writen2(b1, b2 byte) {
  854. // if z.wx {
  855. // z.wb.writen2(b1, b2)
  856. // } else {
  857. // z.wi.writen2(b1, b2)
  858. // }
  859. // }
  860. // An Encoder writes an object to an output stream in the codec format.
  861. type Encoder struct {
  862. panicHdl
  863. // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder
  864. e encDriver
  865. // NOTE: Encoder shouldn't call it's write methods,
  866. // as the handler MAY need to do some coordination.
  867. w encWriter
  868. h *BasicHandle
  869. bw *bufio.Writer
  870. as encDriverAsis
  871. // ---- cpu cache line boundary?
  872. // ---- cpu cache line boundary?
  873. encWriterSwitch
  874. err error
  875. // ---- cpu cache line boundary?
  876. codecFnPooler
  877. ci set
  878. js bool // here, so that no need to piggy back on *codecFner for this
  879. be bool // here, so that no need to piggy back on *codecFner for this
  880. _ [6]byte // padding
  881. // ---- writable fields during execution --- *try* to keep in sep cache line
  882. // ---- cpu cache line boundary?
  883. // b [scratchByteArrayLen]byte
  884. // _ [cacheLineSize - scratchByteArrayLen]byte // padding
  885. b [cacheLineSize - 0]byte // used for encoding a chan or (non-addressable) array of bytes
  886. }
  887. // NewEncoder returns an Encoder for encoding into an io.Writer.
  888. //
  889. // For efficiency, Users are encouraged to pass in a memory buffered writer
  890. // (eg bufio.Writer, bytes.Buffer).
  891. func NewEncoder(w io.Writer, h Handle) *Encoder {
  892. e := newEncoder(h)
  893. e.Reset(w)
  894. return e
  895. }
  896. // NewEncoderBytes returns an encoder for encoding directly and efficiently
  897. // into a byte slice, using zero-copying to temporary slices.
  898. //
  899. // It will potentially replace the output byte slice pointed to.
  900. // After encoding, the out parameter contains the encoded contents.
  901. func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
  902. e := newEncoder(h)
  903. e.ResetBytes(out)
  904. return e
  905. }
  906. func newEncoder(h Handle) *Encoder {
  907. e := &Encoder{h: h.getBasicHandle(), err: errEncoderNotInitialized}
  908. e.hh = h
  909. e.esep = h.hasElemSeparators()
  910. return e
  911. }
  912. func (e *Encoder) resetCommon() {
  913. if e.e == nil || e.hh.recreateEncDriver(e.e) {
  914. e.e = e.hh.newEncDriver(e)
  915. e.as, e.isas = e.e.(encDriverAsis)
  916. // e.cr, _ = e.e.(containerStateRecv)
  917. }
  918. e.be = e.hh.isBinary()
  919. _, e.js = e.hh.(*JsonHandle)
  920. e.e.reset()
  921. e.err = nil
  922. }
  923. // Reset resets the Encoder with a new output stream.
  924. //
  925. // This accommodates using the state of the Encoder,
  926. // where it has "cached" information about sub-engines.
  927. func (e *Encoder) Reset(w io.Writer) {
  928. if w == nil {
  929. return
  930. }
  931. if e.wi == nil {
  932. e.wi = new(ioEncWriter)
  933. }
  934. var ok bool
  935. e.wx = false
  936. e.wi.w = w
  937. if e.h.WriterBufferSize > 0 {
  938. e.bw = bufio.NewWriterSize(w, e.h.WriterBufferSize)
  939. e.wi.bw = e.bw
  940. e.wi.sw = e.bw
  941. e.wi.fw = e.bw
  942. e.wi.ww = e.bw
  943. } else {
  944. if e.wi.bw, ok = w.(io.ByteWriter); !ok {
  945. e.wi.bw = e.wi
  946. }
  947. if e.wi.sw, ok = w.(ioEncStringWriter); !ok {
  948. e.wi.sw = e.wi
  949. }
  950. e.wi.fw, _ = w.(ioFlusher)
  951. e.wi.ww = w
  952. }
  953. e.w = e.wi
  954. e.resetCommon()
  955. }
  956. // ResetBytes resets the Encoder with a new destination output []byte.
  957. func (e *Encoder) ResetBytes(out *[]byte) {
  958. if out == nil {
  959. return
  960. }
  961. var in []byte
  962. if out != nil {
  963. in = *out
  964. }
  965. if in == nil {
  966. in = make([]byte, defEncByteBufSize)
  967. }
  968. e.wx = true
  969. e.wb.reset(in, out)
  970. e.w = &e.wb
  971. e.resetCommon()
  972. }
  973. // Encode writes an object into a stream.
  974. //
  975. // Encoding can be configured via the struct tag for the fields.
  976. // The key (in the struct tags) that we look at is configurable.
  977. //
  978. // By default, we look up the "codec" key in the struct field's tags,
  979. // and fall bak to the "json" key if "codec" is absent.
  980. // That key in struct field's tag value is the key name,
  981. // followed by an optional comma and options.
  982. //
  983. // To set an option on all fields (e.g. omitempty on all fields), you
  984. // can create a field called _struct, and set flags on it. The options
  985. // which can be set on _struct are:
  986. // - omitempty: so all fields are omitted if empty
  987. // - toarray: so struct is encoded as an array
  988. // - int: so struct key names are encoded as signed integers (instead of strings)
  989. // - uint: so struct key names are encoded as unsigned integers (instead of strings)
  990. // - float: so struct key names are encoded as floats (instead of strings)
  991. // More details on these below.
  992. //
  993. // Struct values "usually" encode as maps. Each exported struct field is encoded unless:
  994. // - the field's tag is "-", OR
  995. // - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
  996. //
  997. // When encoding as a map, the first string in the tag (before the comma)
  998. // is the map key string to use when encoding.
  999. // ...
  1000. // This key is typically encoded as a string.
  1001. // However, there are instances where the encoded stream has mapping keys encoded as numbers.
  1002. // For example, some cbor streams have keys as integer codes in the stream, but they should map
  1003. // to fields in a structured object. Consequently, a struct is the natural representation in code.
  1004. // For these, configure the struct to encode/decode the keys as numbers (instead of string).
  1005. // This is done with the int,uint or float option on the _struct field (see above).
  1006. //
  1007. // However, struct values may encode as arrays. This happens when:
  1008. // - StructToArray Encode option is set, OR
  1009. // - the tag on the _struct field sets the "toarray" option
  1010. // Note that omitempty is ignored when encoding struct values as arrays,
  1011. // as an entry must be encoded for each field, to maintain its position.
  1012. //
  1013. // Values with types that implement MapBySlice are encoded as stream maps.
  1014. //
  1015. // The empty values (for omitempty option) are false, 0, any nil pointer
  1016. // or interface value, and any array, slice, map, or string of length zero.
  1017. //
  1018. // Anonymous fields are encoded inline except:
  1019. // - the struct tag specifies a replacement name (first value)
  1020. // - the field is of an interface type
  1021. //
  1022. // Examples:
  1023. //
  1024. // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
  1025. // type MyStruct struct {
  1026. // _struct bool `codec:",omitempty"` //set omitempty for every field
  1027. // Field1 string `codec:"-"` //skip this field
  1028. // Field2 int `codec:"myName"` //Use key "myName" in encode stream
  1029. // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
  1030. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
  1031. // io.Reader //use key "Reader".
  1032. // MyStruct `codec:"my1" //use key "my1".
  1033. // MyStruct //inline it
  1034. // ...
  1035. // }
  1036. //
  1037. // type MyStruct struct {
  1038. // _struct bool `codec:",toarray"` //encode struct as an array
  1039. // }
  1040. //
  1041. // type MyStruct struct {
  1042. // _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys
  1043. // Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1)
  1044. // Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2)
  1045. // }
  1046. //
  1047. // The mode of encoding is based on the type of the value. When a value is seen:
  1048. // - If a Selfer, call its CodecEncodeSelf method
  1049. // - If an extension is registered for it, call that extension function
  1050. // - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method
  1051. // - Else encode it based on its reflect.Kind
  1052. //
  1053. // Note that struct field names and keys in map[string]XXX will be treated as symbols.
  1054. // Some formats support symbols (e.g. binc) and will properly encode the string
  1055. // only once in the stream, and use a tag to refer to it thereafter.
  1056. func (e *Encoder) Encode(v interface{}) (err error) {
  1057. defer e.deferred(&err)
  1058. e.MustEncode(v)
  1059. return
  1060. }
  1061. // MustEncode is like Encode, but panics if unable to Encode.
  1062. // This provides insight to the code location that triggered the error.
  1063. func (e *Encoder) MustEncode(v interface{}) {
  1064. if e.err != nil {
  1065. panic(e.err)
  1066. }
  1067. e.encode(v)
  1068. e.e.atEndOfEncode()
  1069. e.w.atEndOfEncode()
  1070. e.alwaysAtEnd()
  1071. }
  1072. func (e *Encoder) deferred(err1 *error) {
  1073. e.alwaysAtEnd()
  1074. if recoverPanicToErr {
  1075. if x := recover(); x != nil {
  1076. panicValToErr(e, x, err1)
  1077. panicValToErr(e, x, &e.err)
  1078. }
  1079. }
  1080. }
  1081. // func (e *Encoder) alwaysAtEnd() {
  1082. // e.codecFnPooler.alwaysAtEnd()
  1083. // }
  1084. func (e *Encoder) encode(iv interface{}) {
  1085. if iv == nil || definitelyNil(iv) {
  1086. e.e.EncodeNil()
  1087. return
  1088. }
  1089. if v, ok := iv.(Selfer); ok {
  1090. v.CodecEncodeSelf(e)
  1091. return
  1092. }
  1093. // a switch with only concrete types can be optimized.
  1094. // consequently, we deal with nil and interfaces outside.
  1095. switch v := iv.(type) {
  1096. case Raw:
  1097. e.rawBytes(v)
  1098. case reflect.Value:
  1099. e.encodeValue(v, nil, true)
  1100. case string:
  1101. e.e.EncodeString(cUTF8, v)
  1102. case bool:
  1103. e.e.EncodeBool(v)
  1104. case int:
  1105. e.e.EncodeInt(int64(v))
  1106. case int8:
  1107. e.e.EncodeInt(int64(v))
  1108. case int16:
  1109. e.e.EncodeInt(int64(v))
  1110. case int32:
  1111. e.e.EncodeInt(int64(v))
  1112. case int64:
  1113. e.e.EncodeInt(v)
  1114. case uint:
  1115. e.e.EncodeUint(uint64(v))
  1116. case uint8:
  1117. e.e.EncodeUint(uint64(v))
  1118. case uint16:
  1119. e.e.EncodeUint(uint64(v))
  1120. case uint32:
  1121. e.e.EncodeUint(uint64(v))
  1122. case uint64:
  1123. e.e.EncodeUint(v)
  1124. case uintptr:
  1125. e.e.EncodeUint(uint64(v))
  1126. case float32:
  1127. e.e.EncodeFloat32(v)
  1128. case float64:
  1129. e.e.EncodeFloat64(v)
  1130. case time.Time:
  1131. e.e.EncodeTime(v)
  1132. case []uint8:
  1133. e.e.EncodeStringBytes(cRAW, v)
  1134. case *Raw:
  1135. e.rawBytes(*v)
  1136. case *string:
  1137. e.e.EncodeString(cUTF8, *v)
  1138. case *bool:
  1139. e.e.EncodeBool(*v)
  1140. case *int:
  1141. e.e.EncodeInt(int64(*v))
  1142. case *int8:
  1143. e.e.EncodeInt(int64(*v))
  1144. case *int16:
  1145. e.e.EncodeInt(int64(*v))
  1146. case *int32:
  1147. e.e.EncodeInt(int64(*v))
  1148. case *int64:
  1149. e.e.EncodeInt(*v)
  1150. case *uint:
  1151. e.e.EncodeUint(uint64(*v))
  1152. case *uint8:
  1153. e.e.EncodeUint(uint64(*v))
  1154. case *uint16:
  1155. e.e.EncodeUint(uint64(*v))
  1156. case *uint32:
  1157. e.e.EncodeUint(uint64(*v))
  1158. case *uint64:
  1159. e.e.EncodeUint(*v)
  1160. case *uintptr:
  1161. e.e.EncodeUint(uint64(*v))
  1162. case *float32:
  1163. e.e.EncodeFloat32(*v)
  1164. case *float64:
  1165. e.e.EncodeFloat64(*v)
  1166. case *time.Time:
  1167. e.e.EncodeTime(*v)
  1168. case *[]uint8:
  1169. e.e.EncodeStringBytes(cRAW, *v)
  1170. default:
  1171. if !fastpathEncodeTypeSwitch(iv, e) {
  1172. // checkfastpath=true (not false), as underlying slice/map type may be fast-path
  1173. e.encodeValue(reflect.ValueOf(iv), nil, true)
  1174. }
  1175. }
  1176. }
  1177. func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn, checkFastpath bool) {
  1178. // if a valid fn is passed, it MUST BE for the dereferenced type of rv
  1179. var sptr uintptr
  1180. var rvp reflect.Value
  1181. var rvpValid bool
  1182. TOP:
  1183. switch rv.Kind() {
  1184. case reflect.Ptr:
  1185. if rv.IsNil() {
  1186. e.e.EncodeNil()
  1187. return
  1188. }
  1189. rvpValid = true
  1190. rvp = rv
  1191. rv = rv.Elem()
  1192. if e.h.CheckCircularRef && rv.Kind() == reflect.Struct {
  1193. // TODO: Movable pointers will be an issue here. Future problem.
  1194. sptr = rv.UnsafeAddr()
  1195. break TOP
  1196. }
  1197. goto TOP
  1198. case reflect.Interface:
  1199. if rv.IsNil() {
  1200. e.e.EncodeNil()
  1201. return
  1202. }
  1203. rv = rv.Elem()
  1204. goto TOP
  1205. case reflect.Slice, reflect.Map:
  1206. if rv.IsNil() {
  1207. e.e.EncodeNil()
  1208. return
  1209. }
  1210. case reflect.Invalid, reflect.Func:
  1211. e.e.EncodeNil()
  1212. return
  1213. }
  1214. if sptr != 0 && (&e.ci).add(sptr) {
  1215. e.errorf("circular reference found: # %d", sptr)
  1216. }
  1217. if fn == nil {
  1218. rt := rv.Type()
  1219. // always pass checkCodecSelfer=true, in case T or ****T is passed, where *T is a Selfer
  1220. fn = e.cfer().get(rt, checkFastpath, true)
  1221. }
  1222. if fn.i.addrE {
  1223. if rvpValid {
  1224. fn.fe(e, &fn.i, rvp)
  1225. } else if rv.CanAddr() {
  1226. fn.fe(e, &fn.i, rv.Addr())
  1227. } else {
  1228. rv2 := reflect.New(rv.Type())
  1229. rv2.Elem().Set(rv)
  1230. fn.fe(e, &fn.i, rv2)
  1231. }
  1232. } else {
  1233. fn.fe(e, &fn.i, rv)
  1234. }
  1235. if sptr != 0 {
  1236. (&e.ci).remove(sptr)
  1237. }
  1238. }
  1239. func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) {
  1240. if fnerr != nil {
  1241. panic(fnerr)
  1242. }
  1243. if bs == nil {
  1244. e.e.EncodeNil()
  1245. } else if asis {
  1246. e.asis(bs)
  1247. } else {
  1248. e.e.EncodeStringBytes(c, bs)
  1249. }
  1250. }
  1251. func (e *Encoder) asis(v []byte) {
  1252. if e.isas {
  1253. e.as.EncodeAsis(v)
  1254. } else {
  1255. e.w.writeb(v)
  1256. }
  1257. }
  1258. func (e *Encoder) rawBytes(vv Raw) {
  1259. v := []byte(vv)
  1260. if !e.h.Raw {
  1261. e.errorf("Raw values cannot be encoded: %v", v)
  1262. }
  1263. e.asis(v)
  1264. }
  1265. func (e *Encoder) wrapErrstr(v interface{}, err *error) {
  1266. *err = fmt.Errorf("%s encode error: %v", e.hh.Name(), v)
  1267. }