另客网go项目公用的代码库

encode.go 43KB

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