encode.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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, rtelem reflect.Type, timeout time.Duration) (rvcs reflect.Value) {
  213. rvcs = reflect.Zero(reflect.SliceOf(rtelem))
  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) kSlice(f *codecFnInfo, rv reflect.Value) {
  242. // array may be non-addressable, so we have to manage with care
  243. // (don't call rv.Bytes, rv.Slice, etc).
  244. // E.g. type struct S{B [2]byte};
  245. // Encode(S{}) will bomb on "panic: slice of unaddressable array".
  246. mbs := f.ti.mbs
  247. if f.seq != seqTypeArray {
  248. if rvIsNil(rv) {
  249. e.e.EncodeNil()
  250. return
  251. }
  252. // If in this method, then there was no extension function defined.
  253. // So it's okay to treat as []byte.
  254. if !mbs && f.ti.rtid == uint8SliceTypId {
  255. e.e.EncodeStringBytesRaw(rvGetBytes(rv))
  256. return
  257. }
  258. }
  259. if f.seq == seqTypeChan && f.ti.chandir&uint8(reflect.RecvDir) == 0 {
  260. e.errorf("send-only channel cannot be encoded")
  261. }
  262. rtelem := f.ti.elem
  263. var l int
  264. // if a slice, array or chan of bytes, treat specially
  265. if !mbs && uint8TypId == rt2id(rtelem) { // NOT rtelem.Kind() == reflect.Uint8
  266. switch f.seq {
  267. case seqTypeSlice:
  268. e.e.EncodeStringBytesRaw(rvGetBytes(rv))
  269. case seqTypeArray:
  270. e.e.EncodeStringBytesRaw(rvGetArrayBytesRO(rv, e.b[:]))
  271. case seqTypeChan:
  272. e.kSliceBytesChan(rv)
  273. }
  274. return
  275. }
  276. // if chan, consume chan into a slice, and work off that slice.
  277. if f.seq == seqTypeChan {
  278. rv = chanToSlice(rv, rtelem, e.h.ChanRecvTimeout)
  279. }
  280. l = rv.Len() // rv may be slice or array
  281. if mbs {
  282. if l%2 == 1 {
  283. e.errorf("mapBySlice requires even slice length, but got %v", l)
  284. return
  285. }
  286. e.mapStart(l / 2)
  287. } else {
  288. e.arrayStart(l)
  289. }
  290. if l > 0 {
  291. var fn *codecFn
  292. for rtelem.Kind() == reflect.Ptr {
  293. rtelem = rtelem.Elem()
  294. }
  295. // if kind is reflect.Interface, do not pre-determine the
  296. // encoding type, because preEncodeValue may break it down to
  297. // a concrete type and kInterface will bomb.
  298. if rtelem.Kind() != reflect.Interface {
  299. fn = e.h.fn(rtelem)
  300. }
  301. for j := 0; j < l; j++ {
  302. if mbs {
  303. if j%2 == 0 {
  304. e.mapElemKey()
  305. } else {
  306. e.mapElemValue()
  307. }
  308. } else {
  309. e.arrayElem()
  310. }
  311. e.encodeValue(rv.Index(j), fn)
  312. }
  313. }
  314. if mbs {
  315. e.mapEnd()
  316. } else {
  317. e.arrayEnd()
  318. }
  319. }
  320. func (e *Encoder) kSliceBytesChan(rv reflect.Value) {
  321. // do not use range, so that the number of elements encoded
  322. // does not change, and encoding does not hang waiting on someone to close chan.
  323. // for b := range rv2i(rv).(<-chan byte) { bs = append(bs, b) }
  324. // ch := rv2i(rv).(<-chan byte) // fix error - that this is a chan byte, not a <-chan byte.
  325. bs := e.b[:0]
  326. irv := rv2i(rv)
  327. ch, ok := irv.(<-chan byte)
  328. if !ok {
  329. ch = irv.(chan byte)
  330. }
  331. L1:
  332. switch timeout := e.h.ChanRecvTimeout; {
  333. case timeout == 0: // only consume available
  334. for {
  335. select {
  336. case b := <-ch:
  337. bs = append(bs, b)
  338. default:
  339. break L1
  340. }
  341. }
  342. case timeout > 0: // consume until timeout
  343. tt := time.NewTimer(timeout)
  344. for {
  345. select {
  346. case b := <-ch:
  347. bs = append(bs, b)
  348. case <-tt.C:
  349. // close(tt.C)
  350. break L1
  351. }
  352. }
  353. default: // consume until close
  354. for b := range ch {
  355. bs = append(bs, b)
  356. }
  357. }
  358. e.e.EncodeStringBytesRaw(bs)
  359. }
  360. func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) {
  361. sfn := structFieldNode{v: rv, update: false}
  362. if f.ti.toArray || e.h.StructToArray { // toArray
  363. e.arrayStart(len(f.ti.sfiSrc))
  364. for _, si := range f.ti.sfiSrc {
  365. e.arrayElem()
  366. e.encodeValue(sfn.field(si), nil)
  367. }
  368. e.arrayEnd()
  369. } else {
  370. e.mapStart(len(f.ti.sfiSort))
  371. for _, si := range f.ti.sfiSort {
  372. e.mapElemKey()
  373. e.kStructFieldKey(f.ti.keyType, si.encNameAsciiAlphaNum, si.encName)
  374. e.mapElemValue()
  375. e.encodeValue(sfn.field(si), nil)
  376. }
  377. e.mapEnd()
  378. }
  379. }
  380. func (e *Encoder) kStructFieldKey(keyType valueType, encNameAsciiAlphaNum bool, encName string) {
  381. encStructFieldKey(encName, e.e, e.w(), keyType, encNameAsciiAlphaNum, e.js)
  382. }
  383. func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) {
  384. var newlen int
  385. toMap := !(f.ti.toArray || e.h.StructToArray)
  386. var mf map[string]interface{}
  387. if f.ti.isFlag(tiflagMissingFielder) {
  388. mf = rv2i(rv).(MissingFielder).CodecMissingFields()
  389. toMap = true
  390. newlen += len(mf)
  391. } else if f.ti.isFlag(tiflagMissingFielderPtr) {
  392. if rv.CanAddr() {
  393. mf = rv2i(rv.Addr()).(MissingFielder).CodecMissingFields()
  394. } else {
  395. // make a new addressable value of same one, and use it
  396. rv2 := reflect.New(rv.Type())
  397. rvSetDirect(rv2.Elem(), rv)
  398. mf = rv2i(rv2).(MissingFielder).CodecMissingFields()
  399. }
  400. toMap = true
  401. newlen += len(mf)
  402. }
  403. newlen += len(f.ti.sfiSrc)
  404. var fkvs = e.slist.get(newlen)
  405. recur := e.h.RecursiveEmptyCheck
  406. sfn := structFieldNode{v: rv, update: false}
  407. var kv sfiRv
  408. var j int
  409. if toMap {
  410. newlen = 0
  411. for _, si := range f.ti.sfiSort { // use sorted array
  412. kv.r = sfn.field(si)
  413. if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) {
  414. continue
  415. }
  416. kv.v = si // si.encName
  417. fkvs[newlen] = kv
  418. newlen++
  419. }
  420. var mflen int
  421. for k, v := range mf {
  422. if k == "" {
  423. delete(mf, k)
  424. continue
  425. }
  426. if f.ti.infoFieldOmitempty && isEmptyValue(rv4i(v), e.h.TypeInfos, recur, recur) {
  427. delete(mf, k)
  428. continue
  429. }
  430. mflen++
  431. }
  432. // encode it all
  433. e.mapStart(newlen + mflen)
  434. for j = 0; j < newlen; j++ {
  435. kv = fkvs[j]
  436. e.mapElemKey()
  437. e.kStructFieldKey(f.ti.keyType, kv.v.encNameAsciiAlphaNum, kv.v.encName)
  438. e.mapElemValue()
  439. e.encodeValue(kv.r, nil)
  440. }
  441. // now, add the others
  442. for k, v := range mf {
  443. e.mapElemKey()
  444. e.kStructFieldKey(f.ti.keyType, false, k)
  445. e.mapElemValue()
  446. e.encode(v)
  447. }
  448. e.mapEnd()
  449. } else {
  450. newlen = len(f.ti.sfiSrc)
  451. for i, si := range f.ti.sfiSrc { // use unsorted array (to match sequence in struct)
  452. kv.r = sfn.field(si)
  453. // use the zero value.
  454. // if a reference or struct, set to nil (so you do not output too much)
  455. if si.omitEmpty() && isEmptyValue(kv.r, e.h.TypeInfos, recur, recur) {
  456. switch kv.r.Kind() {
  457. case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice:
  458. kv.r = reflect.Value{} //encode as nil
  459. }
  460. }
  461. fkvs[i] = kv
  462. }
  463. // encode it all
  464. e.arrayStart(newlen)
  465. for j = 0; j < newlen; j++ {
  466. e.arrayElem()
  467. e.encodeValue(fkvs[j].r, nil)
  468. }
  469. e.arrayEnd()
  470. }
  471. // do not use defer. Instead, use explicit pool return at end of function.
  472. // defer has a cost we are trying to avoid.
  473. // If there is a panic and these slices are not returned, it is ok.
  474. // spool.end()
  475. e.slist.put(fkvs)
  476. }
  477. func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) {
  478. if rvIsNil(rv) {
  479. e.e.EncodeNil()
  480. return
  481. }
  482. l := rv.Len()
  483. e.mapStart(l)
  484. if l == 0 {
  485. e.mapEnd()
  486. return
  487. }
  488. // determine the underlying key and val encFn's for the map.
  489. // This eliminates some work which is done for each loop iteration i.e.
  490. // rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn.
  491. //
  492. // However, if kind is reflect.Interface, do not pre-determine the
  493. // encoding type, because preEncodeValue may break it down to
  494. // a concrete type and kInterface will bomb.
  495. var keyFn, valFn *codecFn
  496. ktypeKind := f.ti.key.Kind()
  497. vtypeKind := f.ti.elem.Kind()
  498. rtval := f.ti.elem
  499. rtvalkind := vtypeKind
  500. for rtvalkind == reflect.Ptr {
  501. rtval = rtval.Elem()
  502. rtvalkind = rtval.Kind()
  503. }
  504. if rtvalkind != reflect.Interface {
  505. valFn = e.h.fn(rtval)
  506. }
  507. var rvv = mapAddressableRV(f.ti.elem, vtypeKind)
  508. if e.h.Canonical {
  509. e.kMapCanonical(f.ti.key, f.ti.elem, rv, rvv, valFn)
  510. e.mapEnd()
  511. return
  512. }
  513. rtkey := f.ti.key
  514. var keyTypeIsString = stringTypId == rt2id(rtkey) // rtkeyid
  515. if !keyTypeIsString {
  516. for rtkey.Kind() == reflect.Ptr {
  517. rtkey = rtkey.Elem()
  518. }
  519. if rtkey.Kind() != reflect.Interface {
  520. keyFn = e.h.fn(rtkey)
  521. }
  522. }
  523. var rvk = mapAddressableRV(f.ti.key, ktypeKind)
  524. var it mapIter
  525. mapRange(&it, rv, rvk, rvv, true)
  526. validKV := it.ValidKV()
  527. var vx reflect.Value
  528. for it.Next() {
  529. e.mapElemKey()
  530. if validKV {
  531. vx = it.Key()
  532. } else {
  533. vx = rvk
  534. }
  535. if keyTypeIsString {
  536. e.e.EncodeString(vx.String())
  537. } else {
  538. e.encodeValue(vx, keyFn)
  539. }
  540. e.mapElemValue()
  541. if validKV {
  542. vx = it.Value()
  543. } else {
  544. vx = rvv
  545. }
  546. e.encodeValue(vx, valFn)
  547. }
  548. it.Done()
  549. e.mapEnd()
  550. }
  551. func (e *Encoder) kMapCanonical(rtkey, rtval reflect.Type, rv, rvv reflect.Value, valFn *codecFn) {
  552. // we previously did out-of-band if an extension was registered.
  553. // This is not necessary, as the natural kind is sufficient for ordering.
  554. mks := rv.MapKeys()
  555. switch rtkey.Kind() {
  556. case reflect.Bool:
  557. mksv := make([]boolRv, len(mks))
  558. for i, k := range mks {
  559. v := &mksv[i]
  560. v.r = k
  561. v.v = k.Bool()
  562. }
  563. sort.Sort(boolRvSlice(mksv))
  564. for i := range mksv {
  565. e.mapElemKey()
  566. e.e.EncodeBool(mksv[i].v)
  567. e.mapElemValue()
  568. e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
  569. }
  570. case reflect.String:
  571. mksv := make([]stringRv, len(mks))
  572. for i, k := range mks {
  573. v := &mksv[i]
  574. v.r = k
  575. v.v = k.String()
  576. }
  577. sort.Sort(stringRvSlice(mksv))
  578. for i := range mksv {
  579. e.mapElemKey()
  580. e.e.EncodeString(mksv[i].v)
  581. e.mapElemValue()
  582. e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
  583. }
  584. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
  585. mksv := make([]uint64Rv, len(mks))
  586. for i, k := range mks {
  587. v := &mksv[i]
  588. v.r = k
  589. v.v = k.Uint()
  590. }
  591. sort.Sort(uint64RvSlice(mksv))
  592. for i := range mksv {
  593. e.mapElemKey()
  594. e.e.EncodeUint(mksv[i].v)
  595. e.mapElemValue()
  596. e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
  597. }
  598. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  599. mksv := make([]int64Rv, len(mks))
  600. for i, k := range mks {
  601. v := &mksv[i]
  602. v.r = k
  603. v.v = k.Int()
  604. }
  605. sort.Sort(int64RvSlice(mksv))
  606. for i := range mksv {
  607. e.mapElemKey()
  608. e.e.EncodeInt(mksv[i].v)
  609. e.mapElemValue()
  610. e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
  611. }
  612. case reflect.Float32:
  613. mksv := make([]float64Rv, len(mks))
  614. for i, k := range mks {
  615. v := &mksv[i]
  616. v.r = k
  617. v.v = k.Float()
  618. }
  619. sort.Sort(float64RvSlice(mksv))
  620. for i := range mksv {
  621. e.mapElemKey()
  622. e.e.EncodeFloat32(float32(mksv[i].v))
  623. e.mapElemValue()
  624. e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
  625. }
  626. case reflect.Float64:
  627. mksv := make([]float64Rv, len(mks))
  628. for i, k := range mks {
  629. v := &mksv[i]
  630. v.r = k
  631. v.v = k.Float()
  632. }
  633. sort.Sort(float64RvSlice(mksv))
  634. for i := range mksv {
  635. e.mapElemKey()
  636. e.e.EncodeFloat64(mksv[i].v)
  637. e.mapElemValue()
  638. e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
  639. }
  640. case reflect.Struct:
  641. if rtkey == timeTyp {
  642. mksv := make([]timeRv, len(mks))
  643. for i, k := range mks {
  644. v := &mksv[i]
  645. v.r = k
  646. v.v = rv2i(k).(time.Time)
  647. }
  648. sort.Sort(timeRvSlice(mksv))
  649. for i := range mksv {
  650. e.mapElemKey()
  651. e.e.EncodeTime(mksv[i].v)
  652. e.mapElemValue()
  653. e.encodeValue(mapGet(rv, mksv[i].r, rvv), valFn)
  654. }
  655. break
  656. }
  657. fallthrough
  658. default:
  659. // out-of-band
  660. // first encode each key to a []byte first, then sort them, then record
  661. var mksv []byte = e.blist.get(len(mks) * 16)[:0]
  662. e2 := NewEncoderBytes(&mksv, e.hh)
  663. mksbv := make([]bytesRv, len(mks))
  664. for i, k := range mks {
  665. v := &mksbv[i]
  666. l := len(mksv)
  667. e2.MustEncode(k)
  668. v.r = k
  669. v.v = mksv[l:]
  670. }
  671. sort.Sort(bytesRvSlice(mksbv))
  672. for j := range mksbv {
  673. e.mapElemKey()
  674. e.encWr.writeb(mksbv[j].v) // e.asis(mksbv[j].v)
  675. e.mapElemValue()
  676. e.encodeValue(mapGet(rv, mksbv[j].r, rvv), valFn)
  677. }
  678. e.blist.put(mksv)
  679. }
  680. }
  681. // Encoder writes an object to an output stream in a supported format.
  682. //
  683. // Encoder is NOT safe for concurrent use i.e. a Encoder cannot be used
  684. // concurrently in multiple goroutines.
  685. //
  686. // However, as Encoder could be allocation heavy to initialize, a Reset method is provided
  687. // so its state can be reused to decode new input streams repeatedly.
  688. // This is the idiomatic way to use.
  689. type Encoder struct {
  690. panicHdl
  691. e encDriver
  692. h *BasicHandle
  693. // hopefully, reduce derefencing cost by laying the encWriter inside the Encoder
  694. encWr
  695. // ---- cpu cache line boundary
  696. hh Handle
  697. blist bytesFreelist
  698. err error
  699. // ---- cpu cache line boundary
  700. // ---- writable fields during execution --- *try* to keep in sep cache line
  701. ci set // holds set of addresses found during an encoding (if CheckCircularRef=true)
  702. slist sfiRvFreelist
  703. b [(2 * 8)]byte // for encoding chan byte, (non-addressable) [N]byte, etc
  704. // ---- cpu cache line boundary?
  705. }
  706. // NewEncoder returns an Encoder for encoding into an io.Writer.
  707. //
  708. // For efficiency, Users are encouraged to configure WriterBufferSize on the handle
  709. // OR pass in a memory buffered writer (eg bufio.Writer, bytes.Buffer).
  710. func NewEncoder(w io.Writer, h Handle) *Encoder {
  711. e := h.newEncDriver().encoder()
  712. e.Reset(w)
  713. return e
  714. }
  715. // NewEncoderBytes returns an encoder for encoding directly and efficiently
  716. // into a byte slice, using zero-copying to temporary slices.
  717. //
  718. // It will potentially replace the output byte slice pointed to.
  719. // After encoding, the out parameter contains the encoded contents.
  720. func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
  721. e := h.newEncDriver().encoder()
  722. e.ResetBytes(out)
  723. return e
  724. }
  725. func (e *Encoder) init(h Handle) {
  726. e.err = errEncoderNotInitialized
  727. e.bytes = true
  728. e.hh = h
  729. e.h = basicHandle(h)
  730. e.be = e.hh.isBinary()
  731. }
  732. func (e *Encoder) w() *encWr {
  733. return &e.encWr
  734. }
  735. func (e *Encoder) resetCommon() {
  736. e.e.reset()
  737. if e.ci == nil {
  738. // e.ci = (set)(e.cidef[:0])
  739. } else {
  740. e.ci = e.ci[:0]
  741. }
  742. e.c = 0
  743. e.err = nil
  744. }
  745. // Reset resets the Encoder with a new output stream.
  746. //
  747. // This accommodates using the state of the Encoder,
  748. // where it has "cached" information about sub-engines.
  749. func (e *Encoder) Reset(w io.Writer) {
  750. if w == nil {
  751. return
  752. }
  753. e.bytes = false
  754. if e.wf == nil {
  755. e.wf = new(bufioEncWriter)
  756. }
  757. e.wf.reset(w, e.h.WriterBufferSize, &e.blist)
  758. e.resetCommon()
  759. }
  760. // ResetBytes resets the Encoder with a new destination output []byte.
  761. func (e *Encoder) ResetBytes(out *[]byte) {
  762. if out == nil {
  763. return
  764. }
  765. var in []byte = *out
  766. if in == nil {
  767. in = make([]byte, defEncByteBufSize)
  768. }
  769. e.bytes = true
  770. e.wb.reset(in, out)
  771. e.resetCommon()
  772. }
  773. // Encode writes an object into a stream.
  774. //
  775. // Encoding can be configured via the struct tag for the fields.
  776. // The key (in the struct tags) that we look at is configurable.
  777. //
  778. // By default, we look up the "codec" key in the struct field's tags,
  779. // and fall bak to the "json" key if "codec" is absent.
  780. // That key in struct field's tag value is the key name,
  781. // followed by an optional comma and options.
  782. //
  783. // To set an option on all fields (e.g. omitempty on all fields), you
  784. // can create a field called _struct, and set flags on it. The options
  785. // which can be set on _struct are:
  786. // - omitempty: so all fields are omitted if empty
  787. // - toarray: so struct is encoded as an array
  788. // - int: so struct key names are encoded as signed integers (instead of strings)
  789. // - uint: so struct key names are encoded as unsigned integers (instead of strings)
  790. // - float: so struct key names are encoded as floats (instead of strings)
  791. // More details on these below.
  792. //
  793. // Struct values "usually" encode as maps. Each exported struct field is encoded unless:
  794. // - the field's tag is "-", OR
  795. // - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
  796. //
  797. // When encoding as a map, the first string in the tag (before the comma)
  798. // is the map key string to use when encoding.
  799. // ...
  800. // This key is typically encoded as a string.
  801. // However, there are instances where the encoded stream has mapping keys encoded as numbers.
  802. // For example, some cbor streams have keys as integer codes in the stream, but they should map
  803. // to fields in a structured object. Consequently, a struct is the natural representation in code.
  804. // For these, configure the struct to encode/decode the keys as numbers (instead of string).
  805. // This is done with the int,uint or float option on the _struct field (see above).
  806. //
  807. // However, struct values may encode as arrays. This happens when:
  808. // - StructToArray Encode option is set, OR
  809. // - the tag on the _struct field sets the "toarray" option
  810. // Note that omitempty is ignored when encoding struct values as arrays,
  811. // as an entry must be encoded for each field, to maintain its position.
  812. //
  813. // Values with types that implement MapBySlice are encoded as stream maps.
  814. //
  815. // The empty values (for omitempty option) are false, 0, any nil pointer
  816. // or interface value, and any array, slice, map, or string of length zero.
  817. //
  818. // Anonymous fields are encoded inline except:
  819. // - the struct tag specifies a replacement name (first value)
  820. // - the field is of an interface type
  821. //
  822. // Examples:
  823. //
  824. // // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
  825. // type MyStruct struct {
  826. // _struct bool `codec:",omitempty"` //set omitempty for every field
  827. // Field1 string `codec:"-"` //skip this field
  828. // Field2 int `codec:"myName"` //Use key "myName" in encode stream
  829. // Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
  830. // Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
  831. // io.Reader //use key "Reader".
  832. // MyStruct `codec:"my1" //use key "my1".
  833. // MyStruct //inline it
  834. // ...
  835. // }
  836. //
  837. // type MyStruct struct {
  838. // _struct bool `codec:",toarray"` //encode struct as an array
  839. // }
  840. //
  841. // type MyStruct struct {
  842. // _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys
  843. // Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1)
  844. // Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2)
  845. // }
  846. //
  847. // The mode of encoding is based on the type of the value. When a value is seen:
  848. // - If a Selfer, call its CodecEncodeSelf method
  849. // - If an extension is registered for it, call that extension function
  850. // - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method
  851. // - Else encode it based on its reflect.Kind
  852. //
  853. // Note that struct field names and keys in map[string]XXX will be treated as symbols.
  854. // Some formats support symbols (e.g. binc) and will properly encode the string
  855. // only once in the stream, and use a tag to refer to it thereafter.
  856. func (e *Encoder) Encode(v interface{}) (err error) {
  857. // tried to use closure, as runtime optimizes defer with no params.
  858. // This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
  859. // Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
  860. // defer func() { e.deferred(&err) }() }
  861. // { x, y := e, &err; defer func() { x.deferred(y) }() }
  862. if e.err != nil {
  863. return e.err
  864. }
  865. if recoverPanicToErr {
  866. defer func() {
  867. // if error occurred during encoding, return that error;
  868. // else if error occurred on end'ing (i.e. during flush), return that error.
  869. err = e.w().endErr()
  870. x := recover()
  871. if x == nil {
  872. if e.err != err {
  873. e.err = err
  874. }
  875. } else {
  876. panicValToErr(e, x, &e.err)
  877. if e.err != err {
  878. err = e.err
  879. }
  880. }
  881. }()
  882. }
  883. // defer e.deferred(&err)
  884. e.mustEncode(v)
  885. return
  886. }
  887. // MustEncode is like Encode, but panics if unable to Encode.
  888. // This provides insight to the code location that triggered the error.
  889. func (e *Encoder) MustEncode(v interface{}) {
  890. if e.err != nil {
  891. panic(e.err)
  892. }
  893. e.mustEncode(v)
  894. }
  895. func (e *Encoder) mustEncode(v interface{}) {
  896. e.calls++
  897. e.encode(v)
  898. e.calls--
  899. if e.calls == 0 {
  900. e.e.atEndOfEncode()
  901. e.w().end()
  902. }
  903. }
  904. // Release releases shared (pooled) resources.
  905. //
  906. // It is important to call Release() when done with an Encoder, so those resources
  907. // are released instantly for use by subsequently created Encoders.
  908. //
  909. // Deprecated: Release is a no-op as pooled resources are not used with an Encoder.
  910. // This method is kept for compatibility reasons only.
  911. func (e *Encoder) Release() {
  912. }
  913. func (e *Encoder) encode(iv interface{}) {
  914. // a switch with only concrete types can be optimized.
  915. // consequently, we deal with nil and interfaces outside the switch.
  916. if iv == nil {
  917. e.e.EncodeNil()
  918. return
  919. }
  920. rv, ok := isNil(iv)
  921. if ok {
  922. e.e.EncodeNil()
  923. return
  924. }
  925. var vself Selfer
  926. switch v := iv.(type) {
  927. // case nil:
  928. // case Selfer:
  929. case Raw:
  930. e.rawBytes(v)
  931. case reflect.Value:
  932. e.encodeValue(v, nil)
  933. case string:
  934. e.e.EncodeString(v)
  935. case bool:
  936. e.e.EncodeBool(v)
  937. case int:
  938. e.e.EncodeInt(int64(v))
  939. case int8:
  940. e.e.EncodeInt(int64(v))
  941. case int16:
  942. e.e.EncodeInt(int64(v))
  943. case int32:
  944. e.e.EncodeInt(int64(v))
  945. case int64:
  946. e.e.EncodeInt(v)
  947. case uint:
  948. e.e.EncodeUint(uint64(v))
  949. case uint8:
  950. e.e.EncodeUint(uint64(v))
  951. case uint16:
  952. e.e.EncodeUint(uint64(v))
  953. case uint32:
  954. e.e.EncodeUint(uint64(v))
  955. case uint64:
  956. e.e.EncodeUint(v)
  957. case uintptr:
  958. e.e.EncodeUint(uint64(v))
  959. case float32:
  960. e.e.EncodeFloat32(v)
  961. case float64:
  962. e.e.EncodeFloat64(v)
  963. case time.Time:
  964. e.e.EncodeTime(v)
  965. case []uint8:
  966. e.e.EncodeStringBytesRaw(v)
  967. case *Raw:
  968. e.rawBytes(*v)
  969. case *string:
  970. e.e.EncodeString(*v)
  971. case *bool:
  972. e.e.EncodeBool(*v)
  973. case *int:
  974. e.e.EncodeInt(int64(*v))
  975. case *int8:
  976. e.e.EncodeInt(int64(*v))
  977. case *int16:
  978. e.e.EncodeInt(int64(*v))
  979. case *int32:
  980. e.e.EncodeInt(int64(*v))
  981. case *int64:
  982. e.e.EncodeInt(*v)
  983. case *uint:
  984. e.e.EncodeUint(uint64(*v))
  985. case *uint8:
  986. e.e.EncodeUint(uint64(*v))
  987. case *uint16:
  988. e.e.EncodeUint(uint64(*v))
  989. case *uint32:
  990. e.e.EncodeUint(uint64(*v))
  991. case *uint64:
  992. e.e.EncodeUint(*v)
  993. case *uintptr:
  994. e.e.EncodeUint(uint64(*v))
  995. case *float32:
  996. e.e.EncodeFloat32(*v)
  997. case *float64:
  998. e.e.EncodeFloat64(*v)
  999. case *time.Time:
  1000. e.e.EncodeTime(*v)
  1001. case *[]uint8:
  1002. if *v == nil {
  1003. e.e.EncodeNil()
  1004. } else {
  1005. e.e.EncodeStringBytesRaw(*v)
  1006. }
  1007. default:
  1008. if vself, ok = iv.(Selfer); ok {
  1009. vself.CodecEncodeSelf(e)
  1010. } else if !fastpathEncodeTypeSwitch(iv, e) {
  1011. if !rv.IsValid() {
  1012. rv = rv4i(iv)
  1013. }
  1014. e.encodeValue(rv, nil)
  1015. }
  1016. }
  1017. }
  1018. func (e *Encoder) encodeValue(rv reflect.Value, fn *codecFn) {
  1019. // if a valid fn is passed, it MUST BE for the dereferenced type of rv
  1020. // We considered using a uintptr (a pointer) retrievable via rv.UnsafeAddr.
  1021. // However, it is possible for the same pointer to point to 2 different types e.g.
  1022. // type T struct { tHelper }
  1023. // Here, for var v T; &v and &v.tHelper are the same pointer.
  1024. // Consequently, we need a tuple of type and pointer, which interface{} natively provides.
  1025. var sptr interface{} // uintptr
  1026. var rvp reflect.Value
  1027. var rvpValid bool
  1028. TOP:
  1029. switch rv.Kind() {
  1030. case reflect.Ptr:
  1031. if rvIsNil(rv) {
  1032. e.e.EncodeNil()
  1033. return
  1034. }
  1035. rvpValid = true
  1036. rvp = rv
  1037. rv = rv.Elem()
  1038. if e.h.CheckCircularRef && rv.Kind() == reflect.Struct {
  1039. sptr = rv2i(rvp) // rv.UnsafeAddr()
  1040. break TOP
  1041. }
  1042. goto TOP
  1043. case reflect.Interface:
  1044. if rvIsNil(rv) {
  1045. e.e.EncodeNil()
  1046. return
  1047. }
  1048. rv = rv.Elem()
  1049. goto TOP
  1050. case reflect.Slice, reflect.Map:
  1051. if rvIsNil(rv) {
  1052. e.e.EncodeNil()
  1053. return
  1054. }
  1055. case reflect.Invalid, reflect.Func:
  1056. e.e.EncodeNil()
  1057. return
  1058. }
  1059. if sptr != nil && (&e.ci).add(sptr) {
  1060. e.errorf("circular reference found: # %p, %T", sptr, sptr)
  1061. }
  1062. var rt reflect.Type
  1063. if fn == nil {
  1064. rt = rv.Type()
  1065. fn = e.h.fn(rt)
  1066. }
  1067. if fn.i.addrE {
  1068. if rvpValid {
  1069. fn.fe(e, &fn.i, rvp)
  1070. } else if rv.CanAddr() {
  1071. fn.fe(e, &fn.i, rv.Addr())
  1072. } else {
  1073. if rt == nil {
  1074. rt = rv.Type()
  1075. }
  1076. rv2 := reflect.New(rt)
  1077. rvSetDirect(rv2.Elem(), rv)
  1078. fn.fe(e, &fn.i, rv2)
  1079. }
  1080. } else {
  1081. fn.fe(e, &fn.i, rv)
  1082. }
  1083. if sptr != 0 {
  1084. (&e.ci).remove(sptr)
  1085. }
  1086. }
  1087. func (e *Encoder) marshalUtf8(bs []byte, fnerr error) {
  1088. if fnerr != nil {
  1089. panic(fnerr)
  1090. }
  1091. if bs == nil {
  1092. e.e.EncodeNil()
  1093. } else {
  1094. e.e.EncodeString(stringView(bs))
  1095. // e.e.EncodeStringEnc(cUTF8, stringView(bs))
  1096. }
  1097. }
  1098. func (e *Encoder) marshalAsis(bs []byte, fnerr error) {
  1099. if fnerr != nil {
  1100. panic(fnerr)
  1101. }
  1102. if bs == nil {
  1103. e.e.EncodeNil()
  1104. } else {
  1105. e.encWr.writeb(bs) // e.asis(bs)
  1106. }
  1107. }
  1108. func (e *Encoder) marshalRaw(bs []byte, fnerr error) {
  1109. if fnerr != nil {
  1110. panic(fnerr)
  1111. }
  1112. if bs == nil {
  1113. e.e.EncodeNil()
  1114. } else {
  1115. e.e.EncodeStringBytesRaw(bs)
  1116. }
  1117. }
  1118. func (e *Encoder) rawBytes(vv Raw) {
  1119. v := []byte(vv)
  1120. if !e.h.Raw {
  1121. e.errorf("Raw values cannot be encoded: %v", v)
  1122. }
  1123. e.encWr.writeb(v) // e.asis(v)
  1124. }
  1125. func (e *Encoder) wrapErr(v interface{}, err *error) {
  1126. *err = encodeError{codecError{name: e.hh.Name(), err: v}}
  1127. }
  1128. // ---- container tracker methods
  1129. // Note: We update the .c after calling the callback.
  1130. // This way, the callback can know what the last status was.
  1131. func (e *Encoder) mapStart(length int) {
  1132. e.e.WriteMapStart(length)
  1133. e.c = containerMapStart
  1134. }
  1135. func (e *Encoder) mapElemKey() {
  1136. if e.js {
  1137. e.jsondriver().WriteMapElemKey()
  1138. }
  1139. e.c = containerMapKey
  1140. }
  1141. func (e *Encoder) mapElemValue() {
  1142. if e.js {
  1143. e.jsondriver().WriteMapElemValue()
  1144. }
  1145. e.c = containerMapValue
  1146. }
  1147. func (e *Encoder) mapEnd() {
  1148. e.e.WriteMapEnd()
  1149. // e.c = containerMapEnd
  1150. e.c = 0
  1151. }
  1152. func (e *Encoder) arrayStart(length int) {
  1153. e.e.WriteArrayStart(length)
  1154. e.c = containerArrayStart
  1155. }
  1156. func (e *Encoder) arrayElem() {
  1157. if e.js {
  1158. e.jsondriver().WriteArrayElem()
  1159. }
  1160. e.c = containerArrayElem
  1161. }
  1162. func (e *Encoder) arrayEnd() {
  1163. e.e.WriteArrayEnd()
  1164. e.c = 0
  1165. // e.c = containerArrayEnd
  1166. }
  1167. // ----------
  1168. func (e *Encoder) sideEncode(v interface{}, bs *[]byte) {
  1169. rv := baseRV(v)
  1170. e2 := NewEncoderBytes(bs, e.hh)
  1171. e2.encodeValue(rv, e.h.fnNoExt(rv.Type()))
  1172. e2.e.atEndOfEncode()
  1173. e2.w().end()
  1174. }
  1175. func encStructFieldKey(encName string, ee encDriver, w *encWr,
  1176. keyType valueType, encNameAsciiAlphaNum bool, js bool) {
  1177. var m must
  1178. // use if-else-if, not switch (which compiles to binary-search)
  1179. // since keyType is typically valueTypeString, branch prediction is pretty good.
  1180. if keyType == valueTypeString {
  1181. if js && encNameAsciiAlphaNum { // keyType == valueTypeString
  1182. w.writeqstr(encName)
  1183. } else { // keyType == valueTypeString
  1184. ee.EncodeString(encName)
  1185. }
  1186. } else if keyType == valueTypeInt {
  1187. ee.EncodeInt(m.Int(strconv.ParseInt(encName, 10, 64)))
  1188. } else if keyType == valueTypeUint {
  1189. ee.EncodeUint(m.Uint(strconv.ParseUint(encName, 10, 64)))
  1190. } else if keyType == valueTypeFloat {
  1191. ee.EncodeFloat64(m.Float(strconv.ParseFloat(encName, 64)))
  1192. }
  1193. }