encode.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  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. if e.h.Canonical {
  601. e.kMapCanonical(f.ti, rv, rvv, valFn)
  602. e.mapEnd()
  603. return
  604. }
  605. rtkey := f.ti.key
  606. var keyTypeIsString = stringTypId == rt2id(rtkey) // rtkeyid
  607. if !keyTypeIsString {
  608. for rtkey.Kind() == reflect.Ptr {
  609. rtkey = rtkey.Elem()
  610. }
  611. if rtkey.Kind() != reflect.Interface {
  612. keyFn = e.h.fn(rtkey)
  613. }
  614. }
  615. var rvk = mapAddrLoopvarRV(f.ti.key, ktypeKind)
  616. var it mapIter
  617. mapRange(&it, rv, rvk, rvv, true)
  618. for it.Next() {
  619. e.mapElemKey()
  620. if keyTypeIsString {
  621. e.e.EncodeString(it.Key().String())
  622. } else {
  623. e.encodeValue(it.Key(), keyFn)
  624. }
  625. e.mapElemValue()
  626. e.encodeValue(it.Value(), valFn)
  627. }
  628. it.Done()
  629. e.mapEnd()
  630. }
  631. func (e *Encoder) kMapCanonical(ti *typeInfo, rv, rvv reflect.Value, valFn *codecFn) {
  632. // we previously did out-of-band if an extension was registered.
  633. // This is not necessary, as the natural kind is sufficient for ordering.
  634. rtkey := ti.key
  635. mks := rv.MapKeys()
  636. rtkeyKind := rtkey.Kind()
  637. kfast := mapKeyFastKindFor(rtkeyKind)
  638. visindirect := mapStoresElemIndirect(uintptr(ti.elemsize))
  639. visref := refBitset.isset(ti.elemkind)
  640. switch rtkeyKind {
  641. case reflect.Bool:
  642. mksv := make([]boolRv, len(mks))
  643. for i, k := range mks {
  644. v := &mksv[i]
  645. v.r = k
  646. v.v = k.Bool()
  647. }
  648. sort.Sort(boolRvSlice(mksv))
  649. for i := range mksv {
  650. e.mapElemKey()
  651. e.e.EncodeBool(mksv[i].v)
  652. e.mapElemValue()
  653. e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
  654. }
  655. case reflect.String:
  656. mksv := make([]stringRv, len(mks))
  657. for i, k := range mks {
  658. v := &mksv[i]
  659. v.r = k
  660. v.v = k.String()
  661. }
  662. sort.Sort(stringRvSlice(mksv))
  663. for i := range mksv {
  664. e.mapElemKey()
  665. e.e.EncodeString(mksv[i].v)
  666. e.mapElemValue()
  667. e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
  668. }
  669. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
  670. mksv := make([]uint64Rv, len(mks))
  671. for i, k := range mks {
  672. v := &mksv[i]
  673. v.r = k
  674. v.v = k.Uint()
  675. }
  676. sort.Sort(uint64RvSlice(mksv))
  677. for i := range mksv {
  678. e.mapElemKey()
  679. e.e.EncodeUint(mksv[i].v)
  680. e.mapElemValue()
  681. e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
  682. }
  683. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  684. mksv := make([]int64Rv, len(mks))
  685. for i, k := range mks {
  686. v := &mksv[i]
  687. v.r = k
  688. v.v = k.Int()
  689. }
  690. sort.Sort(int64RvSlice(mksv))
  691. for i := range mksv {
  692. e.mapElemKey()
  693. e.e.EncodeInt(mksv[i].v)
  694. e.mapElemValue()
  695. e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
  696. }
  697. case reflect.Float32:
  698. mksv := make([]float64Rv, len(mks))
  699. for i, k := range mks {
  700. v := &mksv[i]
  701. v.r = k
  702. v.v = k.Float()
  703. }
  704. sort.Sort(float64RvSlice(mksv))
  705. for i := range mksv {
  706. e.mapElemKey()
  707. e.e.EncodeFloat32(float32(mksv[i].v))
  708. e.mapElemValue()
  709. e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
  710. }
  711. case reflect.Float64:
  712. mksv := make([]float64Rv, len(mks))
  713. for i, k := range mks {
  714. v := &mksv[i]
  715. v.r = k
  716. v.v = k.Float()
  717. }
  718. sort.Sort(float64RvSlice(mksv))
  719. for i := range mksv {
  720. e.mapElemKey()
  721. e.e.EncodeFloat64(mksv[i].v)
  722. e.mapElemValue()
  723. e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
  724. }
  725. case reflect.Struct:
  726. if rtkey == timeTyp {
  727. mksv := make([]timeRv, len(mks))
  728. for i, k := range mks {
  729. v := &mksv[i]
  730. v.r = k
  731. v.v = rv2i(k).(time.Time)
  732. }
  733. sort.Sort(timeRvSlice(mksv))
  734. for i := range mksv {
  735. e.mapElemKey()
  736. e.e.EncodeTime(mksv[i].v)
  737. e.mapElemValue()
  738. e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
  739. }
  740. break
  741. }
  742. fallthrough
  743. default:
  744. // out-of-band
  745. // first encode each key to a []byte first, then sort them, then record
  746. bs0 := e.blist.get(len(mks) * 16)
  747. mksv := bs0
  748. mksbv := make([]bytesRv, len(mks))
  749. func() {
  750. // replicate sideEncode logic
  751. defer func(wb bytesEncAppender, bytes bool, c containerState, state interface{}) {
  752. e.wb = wb
  753. e.bytes = bytes
  754. e.c = c
  755. e.e.restoreState(state)
  756. }(e.wb, e.bytes, e.c, e.e.captureState())
  757. // e2 := NewEncoderBytes(&mksv, e.hh)
  758. e.wb = bytesEncAppender{mksv[:0], &mksv}
  759. e.bytes = true
  760. e.c = 0
  761. e.e.resetState()
  762. for i, k := range mks {
  763. v := &mksbv[i]
  764. l := len(mksv)
  765. e.encodeValue(k, nil)
  766. e.atEndOfEncode()
  767. e.w().end()
  768. v.r = k
  769. v.v = mksv[l:]
  770. }
  771. }()
  772. sort.Sort(bytesRvSlice(mksbv))
  773. for j := range mksbv {
  774. e.mapElemKey()
  775. e.encWr.writeb(mksbv[j].v)
  776. e.mapElemValue()
  777. e.encodeValue(mapGet(rv, mksbv[j].r, rvv, kfast, visindirect, visref), valFn)
  778. }
  779. e.blist.put(mksv)
  780. if !byteSliceSameData(bs0, mksv) {
  781. e.blist.put(bs0)
  782. }
  783. }
  784. }
  785. // Encoder writes an object to an output stream in a supported format.
  786. //
  787. // Encoder is NOT safe for concurrent use i.e. a Encoder cannot be used
  788. // concurrently in multiple goroutines.
  789. //
  790. // However, as Encoder could be allocation heavy to initialize, a Reset method is provided
  791. // so its state can be reused to decode new input streams repeatedly.
  792. // This is the idiomatic way to use.
  793. type Encoder struct {
  794. panicHdl
  795. e encDriver
  796. h *BasicHandle
  797. // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder
  798. encWr
  799. // ---- cpu cache line boundary
  800. hh Handle
  801. blist bytesFreelist
  802. err error
  803. // ---- cpu cache line boundary
  804. // ---- writable fields during execution --- *try* to keep in sep cache line
  805. // ci holds interfaces during an encoding (if CheckCircularRef=true)
  806. //
  807. // We considered using a []uintptr (slice of pointer addresses) retrievable via rv.UnsafeAddr.
  808. // However, it is possible for the same pointer to point to 2 different types e.g.
  809. // type T struct { tHelper }
  810. // Here, for var v T; &v and &v.tHelper are the same pointer.
  811. // Consequently, we need a tuple of type and pointer, which interface{} natively provides.
  812. ci []interface{} // []uintptr
  813. perType encPerType
  814. slist sfiRvFreelist
  815. }
  816. // NewEncoder returns an Encoder for encoding into an io.Writer.
  817. //
  818. // For efficiency, Users are encouraged to configure WriterBufferSize on the handle
  819. // OR pass in a memory buffered writer (eg bufio.Writer, bytes.Buffer).
  820. func NewEncoder(w io.Writer, h Handle) *Encoder {
  821. e := h.newEncDriver().encoder()
  822. if w != nil {
  823. e.Reset(w)
  824. }
  825. return e
  826. }
  827. // NewEncoderBytes returns an encoder for encoding directly and efficiently
  828. // into a byte slice, using zero-copying to temporary slices.
  829. //
  830. // It will potentially replace the output byte slice pointed to.
  831. // After encoding, the out parameter contains the encoded contents.
  832. func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
  833. e := h.newEncDriver().encoder()
  834. if out != nil {
  835. e.ResetBytes(out)
  836. }
  837. return e
  838. }
  839. func (e *Encoder) init(h Handle) {
  840. initHandle(h)
  841. e.err = errEncoderNotInitialized
  842. e.bytes = true
  843. e.hh = h
  844. e.h = h.getBasicHandle()
  845. e.be = e.hh.isBinary()
  846. }
  847. func (e *Encoder) w() *encWr {
  848. return &e.encWr
  849. }
  850. func (e *Encoder) resetCommon() {
  851. e.e.reset()
  852. if e.ci != nil {
  853. e.ci = e.ci[:0]
  854. }
  855. e.c = 0
  856. e.calls = 0
  857. e.seq = 0
  858. e.err = nil
  859. }
  860. // Reset resets the Encoder with a new output stream.
  861. //
  862. // This accommodates using the state of the Encoder,
  863. // where it has "cached" information about sub-engines.
  864. func (e *Encoder) Reset(w io.Writer) {
  865. e.bytes = false
  866. if e.wf == nil {
  867. e.wf = new(bufioEncWriter)
  868. }
  869. e.wf.reset(w, e.h.WriterBufferSize, &e.blist)
  870. e.resetCommon()
  871. }
  872. // ResetBytes resets the Encoder with a new destination output []byte.
  873. func (e *Encoder) ResetBytes(out *[]byte) {
  874. e.bytes = true
  875. e.wb.reset(encInBytes(out), out)
  876. e.resetCommon()
  877. }
  878. // Encode writes an object into a stream.
  879. //
  880. // Encoding can be configured via the struct tag for the fields.
  881. // The key (in the struct tags) that we look at is configurable.
  882. //
  883. // By default, we look up the "codec" key in the struct field's tags,
  884. // and fall bak to the "json" key if "codec" is absent.
  885. // That key in struct field's tag value is the key name,
  886. // followed by an optional comma and options.
  887. //
  888. // To set an option on all fields (e.g. omitempty on all fields), you
  889. // can create a field called _struct, and set flags on it. The options
  890. // which can be set on _struct are:
  891. // - omitempty: so all fields are omitted if empty
  892. // - toarray: so struct is encoded as an array
  893. // - int: so struct key names are encoded as signed integers (instead of strings)
  894. // - uint: so struct key names are encoded as unsigned integers (instead of strings)
  895. // - float: so struct key names are encoded as floats (instead of strings)
  896. // More details on these below.
  897. //
  898. // Struct values "usually" encode as maps. Each exported struct field is encoded unless:
  899. // - the field's tag is "-", OR
  900. // - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
  901. //
  902. // When encoding as a map, the first string in the tag (before the comma)
  903. // is the map key string to use when encoding.
  904. // ...
  905. // This key is typically encoded as a string.
  906. // However, there are instances where the encoded stream has mapping keys encoded as numbers.
  907. // For example, some cbor streams have keys as integer codes in the stream, but they should map
  908. // to fields in a structured object. Consequently, a struct is the natural representation in code.
  909. // For these, configure the struct to encode/decode the keys as numbers (instead of string).
  910. // This is done with the int,uint or float option on the _struct field (see above).
  911. //
  912. // However, struct values may encode as arrays. This happens when:
  913. // - StructToArray Encode option is set, OR
  914. // - the tag on the _struct field sets the "toarray" option
  915. // Note that omitempty is ignored when encoding struct values as arrays,
  916. // as an entry must be encoded for each field, to maintain its position.
  917. //
  918. // Values with types that implement MapBySlice are encoded as stream maps.
  919. //
  920. // The empty values (for omitempty option) are false, 0, any nil pointer
  921. // or interface value, and any array, slice, map, or string of length zero.
  922. //
  923. // Anonymous fields are encoded inline except:
  924. // - the struct tag specifies a replacement name (first value)
  925. // - the field is of an interface type
  926. //
  927. // Examples:
  928. //
  929. // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
  930. // type MyStruct struct {
  931. // _struct bool `codec:",omitempty"` //set omitempty for every field
  932. // Field1 string `codec:"-"` //skip this field
  933. // Field2 int `codec:"myName"` //Use key "myName" in encode stream
  934. // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
  935. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
  936. // io.Reader //use key "Reader".
  937. // MyStruct `codec:"my1" //use key "my1".
  938. // MyStruct //inline it
  939. // ...
  940. // }
  941. //
  942. // type MyStruct struct {
  943. // _struct bool `codec:",toarray"` //encode struct as an array
  944. // }
  945. //
  946. // type MyStruct struct {
  947. // _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys
  948. // Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1)
  949. // Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2)
  950. // }
  951. //
  952. // The mode of encoding is based on the type of the value. When a value is seen:
  953. // - If a Selfer, call its CodecEncodeSelf method
  954. // - If an extension is registered for it, call that extension function
  955. // - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method
  956. // - Else encode it based on its reflect.Kind
  957. //
  958. // Note that struct field names and keys in map[string]XXX will be treated as symbols.
  959. // Some formats support symbols (e.g. binc) and will properly encode the string
  960. // only once in the stream, and use a tag to refer to it thereafter.
  961. func (e *Encoder) Encode(v interface{}) (err error) {
  962. // tried to use closure, as runtime optimizes defer with no params.
  963. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  964. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  965. if !debugging {
  966. defer func() {
  967. // if error occurred during encoding, return that error;
  968. // else if error occurred on end'ing (i.e. during flush), return that error.
  969. if x := recover(); x != nil {
  970. panicValToErr(e, x, &e.err)
  971. err = e.err
  972. }
  973. }()
  974. }
  975. e.MustEncode(v)
  976. return
  977. }
  978. // MustEncode is like Encode, but panics if unable to Encode.
  979. //
  980. // Note: This provides insight to the code location that triggered the error.
  981. func (e *Encoder) MustEncode(v interface{}) {
  982. halt.onerror(e.err)
  983. if e.hh == nil {
  984. halt.onerror(errNoFormatHandle)
  985. }
  986. e.calls++
  987. e.encode(v)
  988. e.calls--
  989. if e.calls == 0 {
  990. e.atEndOfEncode()
  991. e.w().end()
  992. }
  993. }
  994. // Release releases shared (pooled) resources.
  995. //
  996. // It is important to call Release() when done with an Encoder, so those resources
  997. // are released instantly for use by subsequently created Encoders.
  998. //
  999. // Deprecated: Release is a no-op as pooled resources are not used with an Encoder.
  1000. // This method is kept for compatibility reasons only.
  1001. func (e *Encoder) Release() {
  1002. }
  1003. func (e *Encoder) encode(iv interface{}) {
  1004. // MARKER: a switch with only concrete types can be optimized.
  1005. // consequently, we deal with nil and interfaces outside the switch.
  1006. if iv == nil {
  1007. e.e.EncodeNil()
  1008. return
  1009. }
  1010. rv, ok := isNil(iv)
  1011. if ok {
  1012. e.e.EncodeNil()
  1013. return
  1014. }
  1015. switch v := iv.(type) {
  1016. // case nil:
  1017. // case Selfer:
  1018. case Raw:
  1019. e.rawBytes(v)
  1020. case reflect.Value:
  1021. e.encodeValue(v, nil)
  1022. case string:
  1023. e.e.EncodeString(v)
  1024. case bool:
  1025. e.e.EncodeBool(v)
  1026. case int:
  1027. e.e.EncodeInt(int64(v))
  1028. case int8:
  1029. e.e.EncodeInt(int64(v))
  1030. case int16:
  1031. e.e.EncodeInt(int64(v))
  1032. case int32:
  1033. e.e.EncodeInt(int64(v))
  1034. case int64:
  1035. e.e.EncodeInt(v)
  1036. case uint:
  1037. e.e.EncodeUint(uint64(v))
  1038. case uint8:
  1039. e.e.EncodeUint(uint64(v))
  1040. case uint16:
  1041. e.e.EncodeUint(uint64(v))
  1042. case uint32:
  1043. e.e.EncodeUint(uint64(v))
  1044. case uint64:
  1045. e.e.EncodeUint(v)
  1046. case uintptr:
  1047. e.e.EncodeUint(uint64(v))
  1048. case float32:
  1049. e.e.EncodeFloat32(v)
  1050. case float64:
  1051. e.e.EncodeFloat64(v)
  1052. case complex64:
  1053. e.encodeComplex64(v)
  1054. case complex128:
  1055. e.encodeComplex128(v)
  1056. case time.Time:
  1057. e.e.EncodeTime(v)
  1058. case []byte:
  1059. e.e.EncodeStringBytesRaw(v)
  1060. case *Raw:
  1061. e.rawBytes(*v)
  1062. case *string:
  1063. e.e.EncodeString(*v)
  1064. case *bool:
  1065. e.e.EncodeBool(*v)
  1066. case *int:
  1067. e.e.EncodeInt(int64(*v))
  1068. case *int8:
  1069. e.e.EncodeInt(int64(*v))
  1070. case *int16:
  1071. e.e.EncodeInt(int64(*v))
  1072. case *int32:
  1073. e.e.EncodeInt(int64(*v))
  1074. case *int64:
  1075. e.e.EncodeInt(*v)
  1076. case *uint:
  1077. e.e.EncodeUint(uint64(*v))
  1078. case *uint8:
  1079. e.e.EncodeUint(uint64(*v))
  1080. case *uint16:
  1081. e.e.EncodeUint(uint64(*v))
  1082. case *uint32:
  1083. e.e.EncodeUint(uint64(*v))
  1084. case *uint64:
  1085. e.e.EncodeUint(*v)
  1086. case *uintptr:
  1087. e.e.EncodeUint(uint64(*v))
  1088. case *float32:
  1089. e.e.EncodeFloat32(*v)
  1090. case *float64:
  1091. e.e.EncodeFloat64(*v)
  1092. case *complex64:
  1093. e.encodeComplex64(*v)
  1094. case *complex128:
  1095. e.encodeComplex128(*v)
  1096. case *time.Time:
  1097. e.e.EncodeTime(*v)
  1098. case *[]byte:
  1099. if *v == nil {
  1100. e.e.EncodeNil()
  1101. } else {
  1102. e.e.EncodeStringBytesRaw(*v)
  1103. }
  1104. default:
  1105. // we can't check non-predefined types, as they might be a Selfer or extension.
  1106. if skipFastpathTypeSwitchInDirectCall || !fastpathEncodeTypeSwitch(iv, e) {
  1107. e.encodeValue(rv, nil)
  1108. }
  1109. }
  1110. }
  1111. // encodeValue will encode a value.
  1112. //
  1113. // Note that encodeValue will handle nil in the stream early, so that the
  1114. // subsequent calls i.e. kXXX methods, etc do not have to handle it themselves.
  1115. func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn) {
  1116. // if a valid fn is passed, it MUST BE for the dereferenced type of rv
  1117. // MARKER: We check if value is nil here, so that the kXXX method do not have to.
  1118. var sptr interface{}
  1119. var rvp reflect.Value
  1120. var rvpValid bool
  1121. TOP:
  1122. switch rv.Kind() {
  1123. case reflect.Ptr:
  1124. if rvIsNil(rv) {
  1125. e.e.EncodeNil()
  1126. return
  1127. }
  1128. rvpValid = true
  1129. rvp = rv
  1130. rv = rv.Elem()
  1131. goto TOP
  1132. case reflect.Interface:
  1133. if rvIsNil(rv) {
  1134. e.e.EncodeNil()
  1135. return
  1136. }
  1137. rvpValid = false
  1138. rvp = reflect.Value{}
  1139. rv = rv.Elem()
  1140. goto TOP
  1141. case reflect.Struct:
  1142. if rvpValid && e.h.CheckCircularRef {
  1143. sptr = rv2i(rvp)
  1144. for _, vv := range e.ci {
  1145. if eq4i(sptr, vv) { // error if sptr already seen
  1146. e.errorf("circular reference found: %p, %T", sptr, sptr)
  1147. }
  1148. }
  1149. e.ci = append(e.ci, sptr)
  1150. }
  1151. case reflect.Slice, reflect.Map, reflect.Chan:
  1152. if rvIsNil(rv) {
  1153. e.e.EncodeNil()
  1154. return
  1155. }
  1156. case reflect.Invalid, reflect.Func:
  1157. e.e.EncodeNil()
  1158. return
  1159. }
  1160. if fn == nil {
  1161. fn = e.h.fn(rvType(rv))
  1162. }
  1163. if !fn.i.addrE { // typically, addrE = false, so check it first
  1164. // keep rv same
  1165. } else if rvpValid {
  1166. rv = rvp
  1167. } else {
  1168. rv = e.addrRV(rv, fn.i.ti.rt, fn.i.ti.ptr)
  1169. }
  1170. fn.fe(e, &fn.i, rv)
  1171. if sptr != nil { // remove sptr
  1172. e.ci = e.ci[:len(e.ci)-1]
  1173. }
  1174. }
  1175. // addrRV returns a addressable value which may be readonly
  1176. func (e *Encoder) addrRV(rv reflect.Value, typ, ptrType reflect.Type) (rva reflect.Value) {
  1177. if rv.CanAddr() {
  1178. return rvAddr(rv, ptrType)
  1179. }
  1180. if e.h.NoAddressableReadonly {
  1181. rva = reflect.New(typ)
  1182. rvSetDirect(rva.Elem(), rv)
  1183. return
  1184. }
  1185. return rvAddr(e.perType.AddressableRO(rv), ptrType)
  1186. }
  1187. func (e *Encoder) marshalUtf8(bs []byte, fnerr error) {
  1188. e.onerror(fnerr)
  1189. if bs == nil {
  1190. e.e.EncodeNil()
  1191. } else {
  1192. e.e.EncodeString(stringView(bs))
  1193. }
  1194. }
  1195. func (e *Encoder) marshalAsis(bs []byte, fnerr error) {
  1196. e.onerror(fnerr)
  1197. if bs == nil {
  1198. e.e.EncodeNil()
  1199. } else {
  1200. e.encWr.writeb(bs) // e.asis(bs)
  1201. }
  1202. }
  1203. func (e *Encoder) marshalRaw(bs []byte, fnerr error) {
  1204. e.onerror(fnerr)
  1205. if bs == nil {
  1206. e.e.EncodeNil()
  1207. } else {
  1208. e.e.EncodeStringBytesRaw(bs)
  1209. }
  1210. }
  1211. func (e *Encoder) rawBytes(vv Raw) {
  1212. v := []byte(vv)
  1213. if !e.h.Raw {
  1214. e.errorf("Raw values cannot be encoded: %v", v)
  1215. }
  1216. e.encWr.writeb(v)
  1217. }
  1218. func (e *Encoder) wrapErr(v error, err *error) {
  1219. *err = wrapCodecErr(v, e.hh.Name(), 0, true)
  1220. }
  1221. // ---- container tracker methods
  1222. // Note: We update the .c after calling the callback.
  1223. // This way, the callback can know what the last status was.
  1224. func (e *Encoder) mapStart(length int) {
  1225. e.e.WriteMapStart(length)
  1226. e.c = containerMapStart
  1227. }
  1228. func (e *Encoder) mapElemKey() {
  1229. if e.js {
  1230. e.jsondriver().WriteMapElemKey()
  1231. }
  1232. e.c = containerMapKey
  1233. }
  1234. func (e *Encoder) mapElemValue() {
  1235. if e.js {
  1236. e.jsondriver().WriteMapElemValue()
  1237. }
  1238. e.c = containerMapValue
  1239. }
  1240. func (e *Encoder) mapEnd() {
  1241. e.e.WriteMapEnd()
  1242. e.c = 0
  1243. }
  1244. func (e *Encoder) arrayStart(length int) {
  1245. e.e.WriteArrayStart(length)
  1246. e.c = containerArrayStart
  1247. }
  1248. func (e *Encoder) arrayElem() {
  1249. if e.js {
  1250. e.jsondriver().WriteArrayElem()
  1251. }
  1252. e.c = containerArrayElem
  1253. }
  1254. func (e *Encoder) arrayEnd() {
  1255. e.e.WriteArrayEnd()
  1256. e.c = 0
  1257. }
  1258. // ----------
  1259. func (e *Encoder) haltOnMbsOddLen(length int) {
  1260. if length&1 != 0 { // similar to &1==1 or %2 == 1
  1261. e.errorf("mapBySlice requires even slice length, but got %v", length)
  1262. }
  1263. }
  1264. func (e *Encoder) atEndOfEncode() {
  1265. // e.e.atEndOfEncode()
  1266. if e.js {
  1267. e.jsondriver().atEndOfEncode()
  1268. }
  1269. }
  1270. func (e *Encoder) sideEncode(v interface{}, basetype reflect.Type, bs *[]byte) {
  1271. // rv := baseRV(v)
  1272. // e2 := NewEncoderBytes(bs, e.hh)
  1273. // e2.encodeValue(rv, e2.h.fnNoExt(basetype))
  1274. // e2.atEndOfEncode()
  1275. // e2.w().end()
  1276. defer func(wb bytesEncAppender, bytes bool, c containerState, state interface{}) {
  1277. e.wb = wb
  1278. e.bytes = bytes
  1279. e.c = c
  1280. e.e.restoreState(state)
  1281. }(e.wb, e.bytes, e.c, e.e.captureState())
  1282. e.wb = bytesEncAppender{encInBytes(bs)[:0], bs}
  1283. e.bytes = true
  1284. e.c = 0
  1285. e.e.resetState()
  1286. // must call using fnNoExt
  1287. rv := baseRV(v)
  1288. e.encodeValue(rv, e.h.fnNoExt(basetype))
  1289. e.atEndOfEncode()
  1290. e.w().end()
  1291. }
  1292. func encInBytes(out *[]byte) (in []byte) {
  1293. in = *out
  1294. if in == nil {
  1295. in = make([]byte, defEncByteBufSize)
  1296. }
  1297. return
  1298. }
  1299. func encStructFieldKey(encName string, ee encDriver, w *encWr,
  1300. keyType valueType, encNameAsciiAlphaNum bool, js bool) {
  1301. // use if-else-if, not switch (which compiles to binary-search)
  1302. // since keyType is typically valueTypeString, branch prediction is pretty good.
  1303. if keyType == valueTypeString {
  1304. if js && encNameAsciiAlphaNum { // keyType == valueTypeString
  1305. w.writeqstr(encName)
  1306. } else { // keyType == valueTypeString
  1307. ee.EncodeString(encName)
  1308. }
  1309. } else if keyType == valueTypeInt {
  1310. ee.EncodeInt(must.Int(strconv.ParseInt(encName, 10, 64)))
  1311. } else if keyType == valueTypeUint {
  1312. ee.EncodeUint(must.Uint(strconv.ParseUint(encName, 10, 64)))
  1313. } else if keyType == valueTypeFloat {
  1314. ee.EncodeFloat64(must.Float(strconv.ParseFloat(encName, 64)))
  1315. } else {
  1316. halt.errorf("invalid struct key type: %v", keyType)
  1317. }
  1318. }