encode.go 37 KB

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