encode.go 36 KB

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