encode.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  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) HandleName() string {
  869. return e.hh.Name()
  870. }
  871. func (e *Encoder) init(h Handle) {
  872. initHandle(h)
  873. e.err = errEncoderNotInitialized
  874. e.bytes = true
  875. e.hh = h
  876. e.h = h.getBasicHandle()
  877. e.be = e.hh.isBinary()
  878. }
  879. func (e *Encoder) w() *encWr {
  880. return &e.encWr
  881. }
  882. func (e *Encoder) resetCommon() {
  883. e.e.reset()
  884. if e.ci != nil {
  885. e.ci = e.ci[:0]
  886. }
  887. e.c = 0
  888. e.calls = 0
  889. e.seq = 0
  890. e.err = nil
  891. }
  892. // Reset resets the Encoder with a new output stream.
  893. //
  894. // This accommodates using the state of the Encoder,
  895. // where it has "cached" information about sub-engines.
  896. func (e *Encoder) Reset(w io.Writer) {
  897. e.bytes = false
  898. if e.wf == nil {
  899. e.wf = new(bufioEncWriter)
  900. }
  901. e.wf.reset(w, e.h.WriterBufferSize, &e.blist)
  902. e.resetCommon()
  903. }
  904. // ResetBytes resets the Encoder with a new destination output []byte.
  905. func (e *Encoder) ResetBytes(out *[]byte) {
  906. e.bytes = true
  907. e.wb.reset(encInBytes(out), out)
  908. e.resetCommon()
  909. }
  910. // Encode writes an object into a stream.
  911. //
  912. // Encoding can be configured via the struct tag for the fields.
  913. // The key (in the struct tags) that we look at is configurable.
  914. //
  915. // By default, we look up the "codec" key in the struct field's tags,
  916. // and fall bak to the "json" key if "codec" is absent.
  917. // That key in struct field's tag value is the key name,
  918. // followed by an optional comma and options.
  919. //
  920. // To set an option on all fields (e.g. omitempty on all fields), you
  921. // can create a field called _struct, and set flags on it. The options
  922. // which can be set on _struct are:
  923. // - omitempty: so all fields are omitted if empty
  924. // - toarray: so struct is encoded as an array
  925. // - int: so struct key names are encoded as signed integers (instead of strings)
  926. // - uint: so struct key names are encoded as unsigned integers (instead of strings)
  927. // - float: so struct key names are encoded as floats (instead of strings)
  928. //
  929. // More details on these below.
  930. //
  931. // Struct values "usually" encode as maps. Each exported struct field is encoded unless:
  932. // - the field's tag is "-", OR
  933. // - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
  934. //
  935. // When encoding as a map, the first string in the tag (before the comma)
  936. // is the map key string to use when encoding.
  937. // ...
  938. // This key is typically encoded as a string.
  939. // However, there are instances where the encoded stream has mapping keys encoded as numbers.
  940. // For example, some cbor streams have keys as integer codes in the stream, but they should map
  941. // to fields in a structured object. Consequently, a struct is the natural representation in code.
  942. // For these, configure the struct to encode/decode the keys as numbers (instead of string).
  943. // This is done with the int,uint or float option on the _struct field (see above).
  944. //
  945. // However, struct values may encode as arrays. This happens when:
  946. // - StructToArray Encode option is set, OR
  947. // - the tag on the _struct field sets the "toarray" option
  948. //
  949. // Note that omitempty is ignored when encoding struct values as arrays,
  950. // as an entry must be encoded for each field, to maintain its position.
  951. //
  952. // Values with types that implement MapBySlice are encoded as stream maps.
  953. //
  954. // The empty values (for omitempty option) are false, 0, any nil pointer
  955. // or interface value, and any array, slice, map, or string of length zero.
  956. //
  957. // Anonymous fields are encoded inline except:
  958. // - the struct tag specifies a replacement name (first value)
  959. // - the field is of an interface type
  960. //
  961. // Examples:
  962. //
  963. // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
  964. // type MyStruct struct {
  965. // _struct bool `codec:",omitempty"` //set omitempty for every field
  966. // Field1 string `codec:"-"` //skip this field
  967. // Field2 int `codec:"myName"` //Use key "myName" in encode stream
  968. // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
  969. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
  970. // io.Reader //use key "Reader".
  971. // MyStruct `codec:"my1" //use key "my1".
  972. // MyStruct //inline it
  973. // ...
  974. // }
  975. //
  976. // type MyStruct struct {
  977. // _struct bool `codec:",toarray"` //encode struct as an array
  978. // }
  979. //
  980. // type MyStruct struct {
  981. // _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys
  982. // Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1)
  983. // Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2)
  984. // }
  985. //
  986. // The mode of encoding is based on the type of the value. When a value is seen:
  987. // - If a Selfer, call its CodecEncodeSelf method
  988. // - If an extension is registered for it, call that extension function
  989. // - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method
  990. // - Else encode it based on its reflect.Kind
  991. //
  992. // Note that struct field names and keys in map[string]XXX will be treated as symbols.
  993. // Some formats support symbols (e.g. binc) and will properly encode the string
  994. // only once in the stream, and use a tag to refer to it thereafter.
  995. func (e *Encoder) Encode(v interface{}) (err error) {
  996. // tried to use closure, as runtime optimizes defer with no params.
  997. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  998. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  999. if !debugging {
  1000. defer func() {
  1001. // if error occurred during encoding, return that error;
  1002. // else if error occurred on end'ing (i.e. during flush), return that error.
  1003. if x := recover(); x != nil {
  1004. panicValToErr(e, x, &e.err)
  1005. err = e.err
  1006. }
  1007. }()
  1008. }
  1009. e.MustEncode(v)
  1010. return
  1011. }
  1012. // MustEncode is like Encode, but panics if unable to Encode.
  1013. //
  1014. // Note: This provides insight to the code location that triggered the error.
  1015. func (e *Encoder) MustEncode(v interface{}) {
  1016. halt.onerror(e.err)
  1017. if e.hh == nil {
  1018. halt.onerror(errNoFormatHandle)
  1019. }
  1020. e.calls++
  1021. e.encode(v)
  1022. e.calls--
  1023. if e.calls == 0 {
  1024. e.atEndOfEncode()
  1025. e.w().end()
  1026. }
  1027. }
  1028. // Release is a no-op.
  1029. //
  1030. // Deprecated: 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. }