encode.go 40 KB

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