encode.go 35 KB

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