encode.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  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, rv.Interface())
  269. }
  270. func (f *encFnInfo) raw(rv reflect.Value) {
  271. f.e.raw(rv.Interface().(Raw))
  272. }
  273. func (f *encFnInfo) rawExt(rv reflect.Value) {
  274. // rev := rv.Interface().(RawExt)
  275. // f.e.e.EncodeRawExt(&rev, f.e)
  276. var re *RawExt
  277. if rv.CanAddr() {
  278. re = rv.Addr().Interface().(*RawExt)
  279. } else {
  280. rev := rv.Interface().(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(rv.Interface(), 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 = rv.Interface()
  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 = rv.Addr().Interface()
  300. } else {
  301. rv2 := reflect.New(rv.Type())
  302. rv2.Elem().Set(rv)
  303. v = rv2.Interface()
  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 = rv.Interface()
  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", rv.Interface())
  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 rv.Interface().(<-chan byte) {
  415. // bs = append(bs, b)
  416. // }
  417. ch := rv.Interface().(<-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 := reflect.ValueOf(rtelem).Pointer()
  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 := reflect.ValueOf(rtkey).Pointer()
  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 = reflect.ValueOf(rtkey).Pointer()
  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 := reflect.ValueOf(rtval).Pointer()
  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. //
  934. // Values with types that implement MapBySlice are encoded as stream maps.
  935. //
  936. // The empty values (for omitempty option) are false, 0, any nil pointer
  937. // or interface value, and any array, slice, map, or string of length zero.
  938. //
  939. // Anonymous fields are encoded inline except:
  940. // - the struct tag specifies a replacement name (first value)
  941. // - the field is of an interface type
  942. //
  943. // Examples:
  944. //
  945. // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
  946. // type MyStruct struct {
  947. // _struct bool `codec:",omitempty"` //set omitempty for every field
  948. // Field1 string `codec:"-"` //skip this field
  949. // Field2 int `codec:"myName"` //Use key "myName" in encode stream
  950. // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
  951. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
  952. // io.Reader //use key "Reader".
  953. // MyStruct `codec:"my1" //use key "my1".
  954. // MyStruct //inline it
  955. // ...
  956. // }
  957. //
  958. // type MyStruct struct {
  959. // _struct bool `codec:",omitempty,toarray"` //set omitempty for every field
  960. // //and encode struct as an array
  961. // }
  962. //
  963. // The mode of encoding is based on the type of the value. When a value is seen:
  964. // - If a Selfer, call its CodecEncodeSelf method
  965. // - If an extension is registered for it, call that extension function
  966. // - If it implements encoding.(Binary|Text|JSON)Marshaler, call its Marshal(Binary|Text|JSON) method
  967. // - Else encode it based on its reflect.Kind
  968. //
  969. // Note that struct field names and keys in map[string]XXX will be treated as symbols.
  970. // Some formats support symbols (e.g. binc) and will properly encode the string
  971. // only once in the stream, and use a tag to refer to it thereafter.
  972. func (e *Encoder) Encode(v interface{}) (err error) {
  973. defer panicToErr(&err)
  974. e.encode(v)
  975. e.w.atEndOfEncode()
  976. return
  977. }
  978. // MustEncode is like Encode, but panics if unable to Encode.
  979. // This provides insight to the code location that triggered the error.
  980. func (e *Encoder) MustEncode(v interface{}) {
  981. e.encode(v)
  982. e.w.atEndOfEncode()
  983. }
  984. func (e *Encoder) encode(iv interface{}) {
  985. // if ics, ok := iv.(Selfer); ok {
  986. // ics.CodecEncodeSelf(e)
  987. // return
  988. // }
  989. switch v := iv.(type) {
  990. case nil:
  991. e.e.EncodeNil()
  992. case Selfer:
  993. v.CodecEncodeSelf(e)
  994. case Raw:
  995. e.raw(v)
  996. case reflect.Value:
  997. e.encodeValue(v, nil)
  998. case string:
  999. e.e.EncodeString(c_UTF8, v)
  1000. case bool:
  1001. e.e.EncodeBool(v)
  1002. case int:
  1003. e.e.EncodeInt(int64(v))
  1004. case int8:
  1005. e.e.EncodeInt(int64(v))
  1006. case int16:
  1007. e.e.EncodeInt(int64(v))
  1008. case int32:
  1009. e.e.EncodeInt(int64(v))
  1010. case int64:
  1011. e.e.EncodeInt(v)
  1012. case uint:
  1013. e.e.EncodeUint(uint64(v))
  1014. case uint8:
  1015. e.e.EncodeUint(uint64(v))
  1016. case uint16:
  1017. e.e.EncodeUint(uint64(v))
  1018. case uint32:
  1019. e.e.EncodeUint(uint64(v))
  1020. case uint64:
  1021. e.e.EncodeUint(v)
  1022. case float32:
  1023. e.e.EncodeFloat32(v)
  1024. case float64:
  1025. e.e.EncodeFloat64(v)
  1026. case []uint8:
  1027. e.e.EncodeStringBytes(c_RAW, v)
  1028. case *string:
  1029. e.e.EncodeString(c_UTF8, *v)
  1030. case *bool:
  1031. e.e.EncodeBool(*v)
  1032. case *int:
  1033. e.e.EncodeInt(int64(*v))
  1034. case *int8:
  1035. e.e.EncodeInt(int64(*v))
  1036. case *int16:
  1037. e.e.EncodeInt(int64(*v))
  1038. case *int32:
  1039. e.e.EncodeInt(int64(*v))
  1040. case *int64:
  1041. e.e.EncodeInt(*v)
  1042. case *uint:
  1043. e.e.EncodeUint(uint64(*v))
  1044. case *uint8:
  1045. e.e.EncodeUint(uint64(*v))
  1046. case *uint16:
  1047. e.e.EncodeUint(uint64(*v))
  1048. case *uint32:
  1049. e.e.EncodeUint(uint64(*v))
  1050. case *uint64:
  1051. e.e.EncodeUint(*v)
  1052. case *float32:
  1053. e.e.EncodeFloat32(*v)
  1054. case *float64:
  1055. e.e.EncodeFloat64(*v)
  1056. case *[]uint8:
  1057. e.e.EncodeStringBytes(c_RAW, *v)
  1058. default:
  1059. const checkCodecSelfer1 = true // in case T is passed, where *T is a Selfer, still checkCodecSelfer
  1060. if !fastpathEncodeTypeSwitch(iv, e) {
  1061. e.encodeI(iv, false, checkCodecSelfer1)
  1062. }
  1063. }
  1064. }
  1065. func (e *Encoder) preEncodeValue(rv reflect.Value) (rv2 reflect.Value, sptr uintptr, proceed bool) {
  1066. // use a goto statement instead of a recursive function for ptr/interface.
  1067. TOP:
  1068. switch rv.Kind() {
  1069. case reflect.Ptr:
  1070. if rv.IsNil() {
  1071. e.e.EncodeNil()
  1072. return
  1073. }
  1074. rv = rv.Elem()
  1075. if e.h.CheckCircularRef && rv.Kind() == reflect.Struct {
  1076. // TODO: Movable pointers will be an issue here. Future problem.
  1077. sptr = rv.UnsafeAddr()
  1078. break TOP
  1079. }
  1080. goto TOP
  1081. case reflect.Interface:
  1082. if rv.IsNil() {
  1083. e.e.EncodeNil()
  1084. return
  1085. }
  1086. rv = rv.Elem()
  1087. goto TOP
  1088. case reflect.Slice, reflect.Map:
  1089. if rv.IsNil() {
  1090. e.e.EncodeNil()
  1091. return
  1092. }
  1093. case reflect.Invalid, reflect.Func:
  1094. e.e.EncodeNil()
  1095. return
  1096. }
  1097. proceed = true
  1098. rv2 = rv
  1099. return
  1100. }
  1101. func (e *Encoder) doEncodeValue(rv reflect.Value, fn *encFn, sptr uintptr,
  1102. checkFastpath, checkCodecSelfer bool) {
  1103. if sptr != 0 {
  1104. if (&e.ci).add(sptr) {
  1105. e.errorf("circular reference found: # %d", sptr)
  1106. }
  1107. }
  1108. if fn == nil {
  1109. rt := rv.Type()
  1110. rtid := reflect.ValueOf(rt).Pointer()
  1111. // fn = e.getEncFn(rtid, rt, true, true)
  1112. fn = e.getEncFn(rtid, rt, checkFastpath, checkCodecSelfer)
  1113. }
  1114. fn.f(&fn.i, rv)
  1115. if sptr != 0 {
  1116. (&e.ci).remove(sptr)
  1117. }
  1118. }
  1119. func (e *Encoder) encodeI(iv interface{}, checkFastpath, checkCodecSelfer bool) {
  1120. if rv, sptr, proceed := e.preEncodeValue(reflect.ValueOf(iv)); proceed {
  1121. e.doEncodeValue(rv, nil, sptr, checkFastpath, checkCodecSelfer)
  1122. }
  1123. }
  1124. func (e *Encoder) encodeValue(rv reflect.Value, fn *encFn) {
  1125. // if a valid fn is passed, it MUST BE for the dereferenced type of rv
  1126. if rv, sptr, proceed := e.preEncodeValue(rv); proceed {
  1127. e.doEncodeValue(rv, fn, sptr, true, true)
  1128. }
  1129. }
  1130. func (e *Encoder) getEncFn(rtid uintptr, rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *encFn) {
  1131. // rtid := reflect.ValueOf(rt).Pointer()
  1132. var ok bool
  1133. if useMapForCodecCache {
  1134. fn, ok = e.f[rtid]
  1135. } else {
  1136. for i := range e.s {
  1137. v := &(e.s[i])
  1138. if v.rtid == rtid {
  1139. fn, ok = &(v.fn), true
  1140. break
  1141. }
  1142. }
  1143. }
  1144. if ok {
  1145. return
  1146. }
  1147. if useMapForCodecCache {
  1148. if e.f == nil {
  1149. e.f = make(map[uintptr]*encFn, initCollectionCap)
  1150. }
  1151. fn = new(encFn)
  1152. e.f[rtid] = fn
  1153. } else {
  1154. if e.s == nil {
  1155. e.s = make([]encRtidFn, 0, initCollectionCap)
  1156. }
  1157. e.s = append(e.s, encRtidFn{rtid: rtid})
  1158. fn = &(e.s[len(e.s)-1]).fn
  1159. }
  1160. ti := e.h.getTypeInfo(rtid, rt)
  1161. fi := &(fn.i)
  1162. fi.e = e
  1163. fi.ti = ti
  1164. if checkCodecSelfer && ti.cs {
  1165. fn.f = (*encFnInfo).selferMarshal
  1166. } else if rtid == rawTypId {
  1167. fn.f = (*encFnInfo).raw
  1168. } else if rtid == rawExtTypId {
  1169. fn.f = (*encFnInfo).rawExt
  1170. } else if e.e.IsBuiltinType(rtid) {
  1171. fn.f = (*encFnInfo).builtin
  1172. } else if xfFn := e.h.getExt(rtid); xfFn != nil {
  1173. fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext
  1174. fn.f = (*encFnInfo).ext
  1175. } else if supportMarshalInterfaces && e.be && ti.bm {
  1176. fn.f = (*encFnInfo).binaryMarshal
  1177. } else if supportMarshalInterfaces && !e.be && e.js && ti.jm {
  1178. //If JSON, we should check JSONMarshal before textMarshal
  1179. fn.f = (*encFnInfo).jsonMarshal
  1180. } else if supportMarshalInterfaces && !e.be && ti.tm {
  1181. fn.f = (*encFnInfo).textMarshal
  1182. } else {
  1183. rk := rt.Kind()
  1184. if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) {
  1185. if rt.PkgPath() == "" { // un-named slice or map
  1186. if idx := fastpathAV.index(rtid); idx != -1 {
  1187. fn.f = fastpathAV[idx].encfn
  1188. }
  1189. } else {
  1190. ok = false
  1191. // use mapping for underlying type if there
  1192. var rtu reflect.Type
  1193. if rk == reflect.Map {
  1194. rtu = reflect.MapOf(rt.Key(), rt.Elem())
  1195. } else {
  1196. rtu = reflect.SliceOf(rt.Elem())
  1197. }
  1198. rtuid := reflect.ValueOf(rtu).Pointer()
  1199. if idx := fastpathAV.index(rtuid); idx != -1 {
  1200. xfnf := fastpathAV[idx].encfn
  1201. xrt := fastpathAV[idx].rt
  1202. fn.f = func(xf *encFnInfo, xrv reflect.Value) {
  1203. xfnf(xf, xrv.Convert(xrt))
  1204. }
  1205. }
  1206. }
  1207. }
  1208. if fn.f == nil {
  1209. switch rk {
  1210. case reflect.Bool:
  1211. fn.f = (*encFnInfo).kBool
  1212. case reflect.String:
  1213. fn.f = (*encFnInfo).kString
  1214. case reflect.Float64:
  1215. fn.f = (*encFnInfo).kFloat64
  1216. case reflect.Float32:
  1217. fn.f = (*encFnInfo).kFloat32
  1218. case reflect.Int, reflect.Int8, reflect.Int64, reflect.Int32, reflect.Int16:
  1219. fn.f = (*encFnInfo).kInt
  1220. case reflect.Uint8, reflect.Uint64, reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uintptr:
  1221. fn.f = (*encFnInfo).kUint
  1222. case reflect.Invalid:
  1223. fn.f = (*encFnInfo).kInvalid
  1224. case reflect.Chan:
  1225. fi.seq = seqTypeChan
  1226. fn.f = (*encFnInfo).kSlice
  1227. case reflect.Slice:
  1228. fi.seq = seqTypeSlice
  1229. fn.f = (*encFnInfo).kSlice
  1230. case reflect.Array:
  1231. fi.seq = seqTypeArray
  1232. fn.f = (*encFnInfo).kSlice
  1233. case reflect.Struct:
  1234. fn.f = (*encFnInfo).kStruct
  1235. // reflect.Ptr and reflect.Interface are handled already by preEncodeValue
  1236. // case reflect.Ptr:
  1237. // fn.f = (*encFnInfo).kPtr
  1238. // case reflect.Interface:
  1239. // fn.f = (*encFnInfo).kInterface
  1240. case reflect.Map:
  1241. fn.f = (*encFnInfo).kMap
  1242. default:
  1243. fn.f = (*encFnInfo).kErr
  1244. }
  1245. }
  1246. }
  1247. return
  1248. }
  1249. func (e *Encoder) marshal(bs []byte, fnerr error, asis bool, c charEncoding) {
  1250. if fnerr != nil {
  1251. panic(fnerr)
  1252. }
  1253. if bs == nil {
  1254. e.e.EncodeNil()
  1255. } else if asis {
  1256. e.asis(bs)
  1257. } else {
  1258. e.e.EncodeStringBytes(c, bs)
  1259. }
  1260. }
  1261. func (e *Encoder) asis(v []byte) {
  1262. if e.as == nil {
  1263. e.w.writeb(v)
  1264. } else {
  1265. e.as.EncodeAsis(v)
  1266. }
  1267. }
  1268. func (e *Encoder) raw(vv Raw) {
  1269. v := []byte(vv)
  1270. if !e.h.Raw {
  1271. e.errorf("Raw values cannot be encoded: %v", v)
  1272. }
  1273. if e.as == nil {
  1274. e.w.writeb(v)
  1275. } else {
  1276. e.as.EncodeAsis(v)
  1277. }
  1278. }
  1279. func (e *Encoder) errorf(format string, params ...interface{}) {
  1280. err := fmt.Errorf(format, params...)
  1281. panic(err)
  1282. }
  1283. // ----------------------------------------
  1284. const encStructPoolLen = 5
  1285. // encStructPool is an array of sync.Pool.
  1286. // Each element of the array pools one of encStructPool(8|16|32|64).
  1287. // It allows the re-use of slices up to 64 in length.
  1288. // A performance cost of encoding structs was collecting
  1289. // which values were empty and should be omitted.
  1290. // We needed slices of reflect.Value and string to collect them.
  1291. // This shared pool reduces the amount of unnecessary creation we do.
  1292. // The cost is that of locking sometimes, but sync.Pool is efficient
  1293. // enough to reduce thread contention.
  1294. var encStructPool [encStructPoolLen]sync.Pool
  1295. func init() {
  1296. encStructPool[0].New = func() interface{} { return new([8]stringRv) }
  1297. encStructPool[1].New = func() interface{} { return new([16]stringRv) }
  1298. encStructPool[2].New = func() interface{} { return new([32]stringRv) }
  1299. encStructPool[3].New = func() interface{} { return new([64]stringRv) }
  1300. encStructPool[4].New = func() interface{} { return new([128]stringRv) }
  1301. }
  1302. func encStructPoolGet(newlen int) (p *sync.Pool, v interface{}, s []stringRv) {
  1303. // if encStructPoolLen != 5 { // constant chec, so removed at build time.
  1304. // panic(errors.New("encStructPoolLen must be equal to 4")) // defensive, in case it is changed
  1305. // }
  1306. // idxpool := newlen / 8
  1307. if newlen <= 8 {
  1308. p = &encStructPool[0]
  1309. v = p.Get()
  1310. s = v.(*[8]stringRv)[:newlen]
  1311. } else if newlen <= 16 {
  1312. p = &encStructPool[1]
  1313. v = p.Get()
  1314. s = v.(*[16]stringRv)[:newlen]
  1315. } else if newlen <= 32 {
  1316. p = &encStructPool[2]
  1317. v = p.Get()
  1318. s = v.(*[32]stringRv)[:newlen]
  1319. } else if newlen <= 64 {
  1320. p = &encStructPool[3]
  1321. v = p.Get()
  1322. s = v.(*[64]stringRv)[:newlen]
  1323. } else if newlen <= 128 {
  1324. p = &encStructPool[4]
  1325. v = p.Get()
  1326. s = v.(*[128]stringRv)[:newlen]
  1327. } else {
  1328. s = make([]stringRv, newlen)
  1329. }
  1330. return
  1331. }
  1332. // ----------------------------------------
  1333. // func encErr(format string, params ...interface{}) {
  1334. // doPanic(msgTagEnc, format, params...)
  1335. // }