encode.go 45 KB

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