encode.go 39 KB

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