encode.go 39 KB

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