encode.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  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. e.wb.reset(in, out)
  820. e.resetCommon()
  821. }
  822. // Encode writes an object into a stream.
  823. //
  824. // Encoding can be configured via the struct tag for the fields.
  825. // The key (in the struct tags) that we look at is configurable.
  826. //
  827. // By default, we look up the "codec" key in the struct field's tags,
  828. // and fall bak to the "json" key if "codec" is absent.
  829. // That key in struct field's tag value is the key name,
  830. // followed by an optional comma and options.
  831. //
  832. // To set an option on all fields (e.g. omitempty on all fields), you
  833. // can create a field called _struct, and set flags on it. The options
  834. // which can be set on _struct are:
  835. // - omitempty: so all fields are omitted if empty
  836. // - toarray: so struct is encoded as an array
  837. // - int: so struct key names are encoded as signed integers (instead of strings)
  838. // - uint: so struct key names are encoded as unsigned integers (instead of strings)
  839. // - float: so struct key names are encoded as floats (instead of strings)
  840. // More details on these below.
  841. //
  842. // Struct values "usually" encode as maps. Each exported struct field is encoded unless:
  843. // - the field's tag is "-", OR
  844. // - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
  845. //
  846. // When encoding as a map, the first string in the tag (before the comma)
  847. // is the map key string to use when encoding.
  848. // ...
  849. // This key is typically encoded as a string.
  850. // However, there are instances where the encoded stream has mapping keys encoded as numbers.
  851. // For example, some cbor streams have keys as integer codes in the stream, but they should map
  852. // to fields in a structured object. Consequently, a struct is the natural representation in code.
  853. // For these, configure the struct to encode/decode the keys as numbers (instead of string).
  854. // This is done with the int,uint or float option on the _struct field (see above).
  855. //
  856. // However, struct values may encode as arrays. This happens when:
  857. // - StructToArray Encode option is set, OR
  858. // - the tag on the _struct field sets the "toarray" option
  859. // Note that omitempty is ignored when encoding struct values as arrays,
  860. // as an entry must be encoded for each field, to maintain its position.
  861. //
  862. // Values with types that implement MapBySlice are encoded as stream maps.
  863. //
  864. // The empty values (for omitempty option) are false, 0, any nil pointer
  865. // or interface value, and any array, slice, map, or string of length zero.
  866. //
  867. // Anonymous fields are encoded inline except:
  868. // - the struct tag specifies a replacement name (first value)
  869. // - the field is of an interface type
  870. //
  871. // Examples:
  872. //
  873. // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
  874. // type MyStruct struct {
  875. // _struct bool `codec:",omitempty"` //set omitempty for every field
  876. // Field1 string `codec:"-"` //skip this field
  877. // Field2 int `codec:"myName"` //Use key "myName" in encode stream
  878. // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
  879. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
  880. // io.Reader //use key "Reader".
  881. // MyStruct `codec:"my1" //use key "my1".
  882. // MyStruct //inline it
  883. // ...
  884. // }
  885. //
  886. // type MyStruct struct {
  887. // _struct bool `codec:",toarray"` //encode struct as an array
  888. // }
  889. //
  890. // type MyStruct struct {
  891. // _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys
  892. // Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1)
  893. // Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2)
  894. // }
  895. //
  896. // The mode of encoding is based on the type of the value. When a value is seen:
  897. // - If a Selfer, call its CodecEncodeSelf method
  898. // - If an extension is registered for it, call that extension function
  899. // - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method
  900. // - Else encode it based on its reflect.Kind
  901. //
  902. // Note that struct field names and keys in map[string]XXX will be treated as symbols.
  903. // Some formats support symbols (e.g. binc) and will properly encode the string
  904. // only once in the stream, and use a tag to refer to it thereafter.
  905. func (e *Encoder) Encode(v interface{}) (err error) {
  906. // tried to use closure, as runtime optimizes defer with no params.
  907. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  908. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  909. // defer func() { e.deferred(&err) }() }
  910. // { x, y := e, &err; defer func() { x.deferred(y) }() }
  911. if e.err != nil {
  912. return e.err
  913. }
  914. if recoverPanicToErr {
  915. defer func() {
  916. // if error occurred during encoding, return that error;
  917. // else if error occurred on end'ing (i.e. during flush), return that error.
  918. err = e.w().endErr()
  919. x := recover()
  920. if x == nil {
  921. if e.err != err {
  922. e.err = err
  923. }
  924. } else {
  925. panicValToErr(e, x, &e.err)
  926. if e.err != err {
  927. err = e.err
  928. }
  929. }
  930. }()
  931. }
  932. // defer e.deferred(&err)
  933. e.mustEncode(v)
  934. return
  935. }
  936. // MustEncode is like Encode, but panics if unable to Encode.
  937. // This provides insight to the code location that triggered the error.
  938. func (e *Encoder) MustEncode(v interface{}) {
  939. if e.err != nil {
  940. panic(e.err)
  941. }
  942. e.mustEncode(v)
  943. }
  944. func (e *Encoder) mustEncode(v interface{}) {
  945. e.calls++
  946. e.encode(v)
  947. e.calls--
  948. if e.calls == 0 {
  949. e.e.atEndOfEncode()
  950. e.w().end()
  951. }
  952. }
  953. // Release releases shared (pooled) resources.
  954. //
  955. // It is important to call Release() when done with an Encoder, so those resources
  956. // are released instantly for use by subsequently created Encoders.
  957. //
  958. // Deprecated: Release is a no-op as pooled resources are not used with an Encoder.
  959. // This method is kept for compatibility reasons only.
  960. func (e *Encoder) Release() {
  961. }
  962. func (e *Encoder) encode(iv interface{}) {
  963. // a switch with only concrete types can be optimized.
  964. // consequently, we deal with nil and interfaces outside the switch.
  965. if iv == nil {
  966. e.e.EncodeNil()
  967. return
  968. }
  969. rv, ok := isNil(iv)
  970. if ok {
  971. e.e.EncodeNil()
  972. return
  973. }
  974. var vself Selfer
  975. switch v := iv.(type) {
  976. // case nil:
  977. // case Selfer:
  978. case Raw:
  979. e.rawBytes(v)
  980. case reflect.Value:
  981. e.encodeValue(v, nil)
  982. case string:
  983. e.e.EncodeString(v)
  984. case bool:
  985. e.e.EncodeBool(v)
  986. case int:
  987. e.e.EncodeInt(int64(v))
  988. case int8:
  989. e.e.EncodeInt(int64(v))
  990. case int16:
  991. e.e.EncodeInt(int64(v))
  992. case int32:
  993. e.e.EncodeInt(int64(v))
  994. case int64:
  995. e.e.EncodeInt(v)
  996. case uint:
  997. e.e.EncodeUint(uint64(v))
  998. case uint8:
  999. e.e.EncodeUint(uint64(v))
  1000. case uint16:
  1001. e.e.EncodeUint(uint64(v))
  1002. case uint32:
  1003. e.e.EncodeUint(uint64(v))
  1004. case uint64:
  1005. e.e.EncodeUint(v)
  1006. case uintptr:
  1007. e.e.EncodeUint(uint64(v))
  1008. case float32:
  1009. e.e.EncodeFloat32(v)
  1010. case float64:
  1011. e.e.EncodeFloat64(v)
  1012. case time.Time:
  1013. e.e.EncodeTime(v)
  1014. case []uint8:
  1015. e.e.EncodeStringBytesRaw(v)
  1016. case *Raw:
  1017. e.rawBytes(*v)
  1018. case *string:
  1019. e.e.EncodeString(*v)
  1020. case *bool:
  1021. e.e.EncodeBool(*v)
  1022. case *int:
  1023. e.e.EncodeInt(int64(*v))
  1024. case *int8:
  1025. e.e.EncodeInt(int64(*v))
  1026. case *int16:
  1027. e.e.EncodeInt(int64(*v))
  1028. case *int32:
  1029. e.e.EncodeInt(int64(*v))
  1030. case *int64:
  1031. e.e.EncodeInt(*v)
  1032. case *uint:
  1033. e.e.EncodeUint(uint64(*v))
  1034. case *uint8:
  1035. e.e.EncodeUint(uint64(*v))
  1036. case *uint16:
  1037. e.e.EncodeUint(uint64(*v))
  1038. case *uint32:
  1039. e.e.EncodeUint(uint64(*v))
  1040. case *uint64:
  1041. e.e.EncodeUint(*v)
  1042. case *uintptr:
  1043. e.e.EncodeUint(uint64(*v))
  1044. case *float32:
  1045. e.e.EncodeFloat32(*v)
  1046. case *float64:
  1047. e.e.EncodeFloat64(*v)
  1048. case *time.Time:
  1049. e.e.EncodeTime(*v)
  1050. case *[]uint8:
  1051. if *v == nil {
  1052. e.e.EncodeNil()
  1053. } else {
  1054. e.e.EncodeStringBytesRaw(*v)
  1055. }
  1056. default:
  1057. if vself, ok = iv.(Selfer); ok {
  1058. vself.CodecEncodeSelf(e)
  1059. } else if !fastpathEncodeTypeSwitch(iv, e) {
  1060. if !rv.IsValid() {
  1061. rv = rv4i(iv)
  1062. }
  1063. e.encodeValue(rv, nil)
  1064. }
  1065. }
  1066. }
  1067. func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn) {
  1068. // if a valid fn is passed, it MUST BE for the dereferenced type of rv
  1069. // We considered using a uintptr (a pointer) retrievable via rv.UnsafeAddr.
  1070. // However, it is possible for the same pointer to point to 2 different types e.g.
  1071. // type T struct { tHelper }
  1072. // Here, for var v T; &v and &v.tHelper are the same pointer.
  1073. // Consequently, we need a tuple of type and pointer, which interface{} natively provides.
  1074. var sptr interface{} // uintptr
  1075. var rvp reflect.Value
  1076. var rvpValid bool
  1077. TOP:
  1078. switch rv.Kind() {
  1079. case reflect.Ptr:
  1080. if rvIsNil(rv) {
  1081. e.e.EncodeNil()
  1082. return
  1083. }
  1084. rvpValid = true
  1085. rvp = rv
  1086. rv = rv.Elem()
  1087. if e.h.CheckCircularRef && rv.Kind() == reflect.Struct {
  1088. sptr = rv2i(rvp) // rv.UnsafeAddr()
  1089. break TOP
  1090. }
  1091. goto TOP
  1092. case reflect.Interface:
  1093. if rvIsNil(rv) {
  1094. e.e.EncodeNil()
  1095. return
  1096. }
  1097. rv = rv.Elem()
  1098. goto TOP
  1099. case reflect.Slice, reflect.Map:
  1100. if rvIsNil(rv) {
  1101. e.e.EncodeNil()
  1102. return
  1103. }
  1104. case reflect.Invalid, reflect.Func:
  1105. e.e.EncodeNil()
  1106. return
  1107. }
  1108. if sptr != nil && (&e.ci).add(sptr) {
  1109. e.errorf("circular reference found: # %p, %T", sptr, sptr)
  1110. }
  1111. var rt reflect.Type
  1112. if fn == nil {
  1113. rt = rv.Type()
  1114. fn = e.h.fn(rt)
  1115. }
  1116. if fn.i.addrE {
  1117. if rvpValid {
  1118. fn.fe(e, &fn.i, rvp)
  1119. } else if rv.CanAddr() {
  1120. fn.fe(e, &fn.i, rv.Addr())
  1121. } else {
  1122. if rt == nil {
  1123. rt = rv.Type()
  1124. }
  1125. rv2 := reflect.New(rt)
  1126. rvSetDirect(rv2.Elem(), rv)
  1127. fn.fe(e, &fn.i, rv2)
  1128. }
  1129. } else {
  1130. fn.fe(e, &fn.i, rv)
  1131. }
  1132. if sptr != 0 {
  1133. (&e.ci).remove(sptr)
  1134. }
  1135. }
  1136. func (e *Encoder) marshalUtf8(bs []byte, fnerr error) {
  1137. if fnerr != nil {
  1138. panic(fnerr)
  1139. }
  1140. if bs == nil {
  1141. e.e.EncodeNil()
  1142. } else {
  1143. e.e.EncodeString(stringView(bs))
  1144. // e.e.EncodeStringEnc(cUTF8, stringView(bs))
  1145. }
  1146. }
  1147. func (e *Encoder) marshalAsis(bs []byte, fnerr error) {
  1148. if fnerr != nil {
  1149. panic(fnerr)
  1150. }
  1151. if bs == nil {
  1152. e.e.EncodeNil()
  1153. } else {
  1154. e.encWr.writeb(bs) // e.asis(bs)
  1155. }
  1156. }
  1157. func (e *Encoder) marshalRaw(bs []byte, fnerr error) {
  1158. if fnerr != nil {
  1159. panic(fnerr)
  1160. }
  1161. if bs == nil {
  1162. e.e.EncodeNil()
  1163. } else {
  1164. e.e.EncodeStringBytesRaw(bs)
  1165. }
  1166. }
  1167. func (e *Encoder) rawBytes(vv Raw) {
  1168. v := []byte(vv)
  1169. if !e.h.Raw {
  1170. e.errorf("Raw values cannot be encoded: %v", v)
  1171. }
  1172. e.encWr.writeb(v) // e.asis(v)
  1173. }
  1174. func (e *Encoder) wrapErr(v interface{}, err *error) {
  1175. *err = encodeError{codecError{name: e.hh.Name(), err: v}}
  1176. }
  1177. // ---- container tracker methods
  1178. // Note: We update the .c after calling the callback.
  1179. // This way, the callback can know what the last status was.
  1180. func (e *Encoder) mapStart(length int) {
  1181. e.e.WriteMapStart(length)
  1182. e.c = containerMapStart
  1183. }
  1184. func (e *Encoder) mapElemKey() {
  1185. if e.js {
  1186. e.jsondriver().WriteMapElemKey()
  1187. }
  1188. e.c = containerMapKey
  1189. }
  1190. func (e *Encoder) mapElemValue() {
  1191. if e.js {
  1192. e.jsondriver().WriteMapElemValue()
  1193. }
  1194. e.c = containerMapValue
  1195. }
  1196. func (e *Encoder) mapEnd() {
  1197. e.e.WriteMapEnd()
  1198. // e.c = containerMapEnd
  1199. e.c = 0
  1200. }
  1201. func (e *Encoder) arrayStart(length int) {
  1202. e.e.WriteArrayStart(length)
  1203. e.c = containerArrayStart
  1204. }
  1205. func (e *Encoder) arrayElem() {
  1206. if e.js {
  1207. e.jsondriver().WriteArrayElem()
  1208. }
  1209. e.c = containerArrayElem
  1210. }
  1211. func (e *Encoder) arrayEnd() {
  1212. e.e.WriteArrayEnd()
  1213. e.c = 0
  1214. // e.c = containerArrayEnd
  1215. }
  1216. // ----------
  1217. func (e *Encoder) sideEncode(v interface{}, bs *[]byte) {
  1218. rv := baseRV(v)
  1219. e2 := NewEncoderBytes(bs, e.hh)
  1220. e2.encodeValue(rv, e.h.fnNoExt(rv.Type()))
  1221. e2.e.atEndOfEncode()
  1222. e2.w().end()
  1223. }
  1224. func encStructFieldKey(encName string, ee encDriver, w *encWr,
  1225. keyType valueType, encNameAsciiAlphaNum bool, js bool) {
  1226. var m must
  1227. // use if-else-if, not switch (which compiles to binary-search)
  1228. // since keyType is typically valueTypeString, branch prediction is pretty good.
  1229. if keyType == valueTypeString {
  1230. if js && encNameAsciiAlphaNum { // keyType == valueTypeString
  1231. w.writeqstr(encName)
  1232. } else { // keyType == valueTypeString
  1233. ee.EncodeString(encName)
  1234. }
  1235. } else if keyType == valueTypeInt {
  1236. ee.EncodeInt(m.Int(strconv.ParseInt(encName, 10, 64)))
  1237. } else if keyType == valueTypeUint {
  1238. ee.EncodeUint(m.Uint(strconv.ParseUint(encName, 10, 64)))
  1239. } else if keyType == valueTypeFloat {
  1240. ee.EncodeFloat64(m.Float(strconv.ParseFloat(encName, 64)))
  1241. }
  1242. }