encode.go 39 KB

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