write.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. package msgp
  2. import (
  3. "errors"
  4. "io"
  5. "math"
  6. "reflect"
  7. "sync"
  8. "time"
  9. )
  10. const (
  11. // min buffer size for the writer
  12. minWriterSize = 18
  13. )
  14. // Sizer is an interface implemented
  15. // by types that can estimate their
  16. // size when MessagePack encoded.
  17. // This interface is optional, but
  18. // encoding/marshaling implementations
  19. // may use this as a way to pre-allocate
  20. // memory for serialization.
  21. type Sizer interface {
  22. Msgsize() int
  23. }
  24. var (
  25. // Nowhere is an io.Writer to nowhere
  26. Nowhere io.Writer = nwhere{}
  27. btsType = reflect.TypeOf(([]byte)(nil))
  28. writerPool = sync.Pool{
  29. New: func() interface{} {
  30. return &Writer{buf: make([]byte, 2048)}
  31. },
  32. }
  33. )
  34. func popWriter(w io.Writer) *Writer {
  35. wr := writerPool.Get().(*Writer)
  36. wr.Reset(w)
  37. return wr
  38. }
  39. func pushWriter(wr *Writer) {
  40. wr.w = nil
  41. wr.wloc = 0
  42. writerPool.Put(wr)
  43. }
  44. // freeW frees a writer for use
  45. // by other processes. It is not necessary
  46. // to call freeW on a writer. However, maintaining
  47. // a reference to a *Writer after calling freeW on
  48. // it will cause undefined behavior.
  49. func freeW(w *Writer) { pushWriter(w) }
  50. // Require ensures that cap(old)-len(old) >= extra.
  51. func Require(old []byte, extra int) []byte {
  52. l := len(old)
  53. c := cap(old)
  54. r := l + extra
  55. if c >= r {
  56. return old
  57. } else if l == 0 {
  58. return make([]byte, 0, extra)
  59. }
  60. // the new size is the greater
  61. // of double the old capacity
  62. // and the sum of the old length
  63. // and the number of new bytes
  64. // necessary.
  65. c <<= 1
  66. if c < r {
  67. c = r
  68. }
  69. n := make([]byte, l, c)
  70. copy(n, old)
  71. return n
  72. }
  73. // nowhere writer
  74. type nwhere struct{}
  75. func (n nwhere) Write(p []byte) (int, error) { return len(p), nil }
  76. // Marshaler is the interface implemented
  77. // by types that know how to marshal themselves
  78. // as MessagePack. MarshalMsg appends the marshalled
  79. // form of the object to the provided
  80. // byte slice, returning the extended
  81. // slice and any errors encountered.
  82. type Marshaler interface {
  83. MarshalMsg([]byte) ([]byte, error)
  84. }
  85. // Encodable is the interface implemented
  86. // by types that know how to write themselves
  87. // as MessagePack using a *msgp.Writer.
  88. type Encodable interface {
  89. EncodeMsg(*Writer) error
  90. }
  91. // Writer is a buffered writer
  92. // that can be used to write
  93. // MessagePack objects to an io.Writer.
  94. // You must call *Writer.Flush() in order
  95. // to flush all of the buffered data
  96. // to the underlying writer.
  97. type Writer struct {
  98. w io.Writer
  99. buf []byte
  100. wloc int
  101. }
  102. // NewWriter returns a new *Writer.
  103. func NewWriter(w io.Writer) *Writer {
  104. if wr, ok := w.(*Writer); ok {
  105. return wr
  106. }
  107. return popWriter(w)
  108. }
  109. // NewWriterSize returns a writer with a custom buffer size.
  110. func NewWriterSize(w io.Writer, sz int) *Writer {
  111. // we must be able to require() 'minWriterSize'
  112. // contiguous bytes, so that is the
  113. // practical minimum buffer size
  114. if sz < minWriterSize {
  115. sz = minWriterSize
  116. }
  117. buf := make([]byte, sz)
  118. return NewWriterBuf(w, buf)
  119. }
  120. // NewWriterBuf returns a writer with a provided buffer.
  121. // 'buf' is not used when the capacity is smaller than 18,
  122. // custom buffer is allocated instead.
  123. func NewWriterBuf(w io.Writer, buf []byte) *Writer {
  124. if cap(buf) < minWriterSize {
  125. buf = make([]byte, minWriterSize)
  126. }
  127. buf = buf[:cap(buf)]
  128. return &Writer{
  129. w: w,
  130. buf: buf,
  131. }
  132. }
  133. // Encode encodes an Encodable to an io.Writer.
  134. func Encode(w io.Writer, e Encodable) error {
  135. wr := NewWriter(w)
  136. err := e.EncodeMsg(wr)
  137. if err == nil {
  138. err = wr.Flush()
  139. }
  140. freeW(wr)
  141. return err
  142. }
  143. func (mw *Writer) flush() error {
  144. if mw.wloc == 0 {
  145. return nil
  146. }
  147. n, err := mw.w.Write(mw.buf[:mw.wloc])
  148. if err != nil {
  149. if n > 0 {
  150. mw.wloc = copy(mw.buf, mw.buf[n:mw.wloc])
  151. }
  152. return err
  153. }
  154. mw.wloc = 0
  155. return nil
  156. }
  157. // Flush flushes all of the buffered
  158. // data to the underlying writer.
  159. func (mw *Writer) Flush() error { return mw.flush() }
  160. // Buffered returns the number bytes in the write buffer
  161. func (mw *Writer) Buffered() int { return len(mw.buf) - mw.wloc }
  162. func (mw *Writer) avail() int { return len(mw.buf) - mw.wloc }
  163. func (mw *Writer) bufsize() int { return len(mw.buf) }
  164. // NOTE: this should only be called with
  165. // a number that is guaranteed to be less than
  166. // len(mw.buf). typically, it is called with a constant.
  167. //
  168. // NOTE: this is a hot code path
  169. func (mw *Writer) require(n int) (int, error) {
  170. c := len(mw.buf)
  171. wl := mw.wloc
  172. if c-wl < n {
  173. if err := mw.flush(); err != nil {
  174. return 0, err
  175. }
  176. wl = mw.wloc
  177. }
  178. mw.wloc += n
  179. return wl, nil
  180. }
  181. func (mw *Writer) Append(b ...byte) error {
  182. if mw.avail() < len(b) {
  183. err := mw.flush()
  184. if err != nil {
  185. return err
  186. }
  187. }
  188. mw.wloc += copy(mw.buf[mw.wloc:], b)
  189. return nil
  190. }
  191. // push one byte onto the buffer
  192. //
  193. // NOTE: this is a hot code path
  194. func (mw *Writer) push(b byte) error {
  195. if mw.wloc == len(mw.buf) {
  196. if err := mw.flush(); err != nil {
  197. return err
  198. }
  199. }
  200. mw.buf[mw.wloc] = b
  201. mw.wloc++
  202. return nil
  203. }
  204. func (mw *Writer) prefix8(b byte, u uint8) error {
  205. const need = 2
  206. if len(mw.buf)-mw.wloc < need {
  207. if err := mw.flush(); err != nil {
  208. return err
  209. }
  210. }
  211. prefixu8(mw.buf[mw.wloc:], b, u)
  212. mw.wloc += need
  213. return nil
  214. }
  215. func (mw *Writer) prefix16(b byte, u uint16) error {
  216. const need = 3
  217. if len(mw.buf)-mw.wloc < need {
  218. if err := mw.flush(); err != nil {
  219. return err
  220. }
  221. }
  222. prefixu16(mw.buf[mw.wloc:], b, u)
  223. mw.wloc += need
  224. return nil
  225. }
  226. func (mw *Writer) prefix32(b byte, u uint32) error {
  227. const need = 5
  228. if len(mw.buf)-mw.wloc < need {
  229. if err := mw.flush(); err != nil {
  230. return err
  231. }
  232. }
  233. prefixu32(mw.buf[mw.wloc:], b, u)
  234. mw.wloc += need
  235. return nil
  236. }
  237. func (mw *Writer) prefix64(b byte, u uint64) error {
  238. const need = 9
  239. if len(mw.buf)-mw.wloc < need {
  240. if err := mw.flush(); err != nil {
  241. return err
  242. }
  243. }
  244. prefixu64(mw.buf[mw.wloc:], b, u)
  245. mw.wloc += need
  246. return nil
  247. }
  248. // Write implements io.Writer, and writes
  249. // data directly to the buffer.
  250. func (mw *Writer) Write(p []byte) (int, error) {
  251. l := len(p)
  252. if mw.avail() < l {
  253. if err := mw.flush(); err != nil {
  254. return 0, err
  255. }
  256. if l > len(mw.buf) {
  257. return mw.w.Write(p)
  258. }
  259. }
  260. mw.wloc += copy(mw.buf[mw.wloc:], p)
  261. return l, nil
  262. }
  263. // implements io.WriteString
  264. func (mw *Writer) writeString(s string) error {
  265. l := len(s)
  266. if mw.avail() < l {
  267. if err := mw.flush(); err != nil {
  268. return err
  269. }
  270. if l > len(mw.buf) {
  271. _, err := io.WriteString(mw.w, s)
  272. return err
  273. }
  274. }
  275. mw.wloc += copy(mw.buf[mw.wloc:], s)
  276. return nil
  277. }
  278. // Reset changes the underlying writer used by the Writer
  279. func (mw *Writer) Reset(w io.Writer) {
  280. mw.buf = mw.buf[:cap(mw.buf)]
  281. mw.w = w
  282. mw.wloc = 0
  283. }
  284. // WriteMapHeader writes a map header of the given
  285. // size to the writer
  286. func (mw *Writer) WriteMapHeader(sz uint32) error {
  287. switch {
  288. case sz <= 15:
  289. return mw.push(wfixmap(uint8(sz)))
  290. case sz <= math.MaxUint16:
  291. return mw.prefix16(mmap16, uint16(sz))
  292. default:
  293. return mw.prefix32(mmap32, sz)
  294. }
  295. }
  296. // WriteArrayHeader writes an array header of the
  297. // given size to the writer
  298. func (mw *Writer) WriteArrayHeader(sz uint32) error {
  299. switch {
  300. case sz <= 15:
  301. return mw.push(wfixarray(uint8(sz)))
  302. case sz <= math.MaxUint16:
  303. return mw.prefix16(marray16, uint16(sz))
  304. default:
  305. return mw.prefix32(marray32, sz)
  306. }
  307. }
  308. // WriteNil writes a nil byte to the buffer
  309. func (mw *Writer) WriteNil() error {
  310. return mw.push(mnil)
  311. }
  312. // WriteFloat64 writes a float64 to the writer
  313. func (mw *Writer) WriteFloat64(f float64) error {
  314. return mw.prefix64(mfloat64, math.Float64bits(f))
  315. }
  316. // WriteFloat32 writes a float32 to the writer
  317. func (mw *Writer) WriteFloat32(f float32) error {
  318. return mw.prefix32(mfloat32, math.Float32bits(f))
  319. }
  320. // WriteDuration writes a time.Duration to the writer
  321. func (mw *Writer) WriteDuration(d time.Duration) error {
  322. return mw.WriteInt64(int64(d))
  323. }
  324. // WriteInt64 writes an int64 to the writer
  325. func (mw *Writer) WriteInt64(i int64) error {
  326. if i >= 0 {
  327. switch {
  328. case i <= math.MaxInt8:
  329. return mw.push(wfixint(uint8(i)))
  330. case i <= math.MaxInt16:
  331. return mw.prefix16(mint16, uint16(i))
  332. case i <= math.MaxInt32:
  333. return mw.prefix32(mint32, uint32(i))
  334. default:
  335. return mw.prefix64(mint64, uint64(i))
  336. }
  337. }
  338. switch {
  339. case i >= -32:
  340. return mw.push(wnfixint(int8(i)))
  341. case i >= math.MinInt8:
  342. return mw.prefix8(mint8, uint8(i))
  343. case i >= math.MinInt16:
  344. return mw.prefix16(mint16, uint16(i))
  345. case i >= math.MinInt32:
  346. return mw.prefix32(mint32, uint32(i))
  347. default:
  348. return mw.prefix64(mint64, uint64(i))
  349. }
  350. }
  351. // WriteInt8 writes an int8 to the writer
  352. func (mw *Writer) WriteInt8(i int8) error { return mw.WriteInt64(int64(i)) }
  353. // WriteInt16 writes an int16 to the writer
  354. func (mw *Writer) WriteInt16(i int16) error { return mw.WriteInt64(int64(i)) }
  355. // WriteInt32 writes an int32 to the writer
  356. func (mw *Writer) WriteInt32(i int32) error { return mw.WriteInt64(int64(i)) }
  357. // WriteInt writes an int to the writer
  358. func (mw *Writer) WriteInt(i int) error { return mw.WriteInt64(int64(i)) }
  359. // WriteUint64 writes a uint64 to the writer
  360. func (mw *Writer) WriteUint64(u uint64) error {
  361. switch {
  362. case u <= (1<<7)-1:
  363. return mw.push(wfixint(uint8(u)))
  364. case u <= math.MaxUint8:
  365. return mw.prefix8(muint8, uint8(u))
  366. case u <= math.MaxUint16:
  367. return mw.prefix16(muint16, uint16(u))
  368. case u <= math.MaxUint32:
  369. return mw.prefix32(muint32, uint32(u))
  370. default:
  371. return mw.prefix64(muint64, u)
  372. }
  373. }
  374. // WriteByte is analogous to WriteUint8
  375. func (mw *Writer) WriteByte(u byte) error { return mw.WriteUint8(uint8(u)) }
  376. // WriteUint8 writes a uint8 to the writer
  377. func (mw *Writer) WriteUint8(u uint8) error { return mw.WriteUint64(uint64(u)) }
  378. // WriteUint16 writes a uint16 to the writer
  379. func (mw *Writer) WriteUint16(u uint16) error { return mw.WriteUint64(uint64(u)) }
  380. // WriteUint32 writes a uint32 to the writer
  381. func (mw *Writer) WriteUint32(u uint32) error { return mw.WriteUint64(uint64(u)) }
  382. // WriteUint writes a uint to the writer
  383. func (mw *Writer) WriteUint(u uint) error { return mw.WriteUint64(uint64(u)) }
  384. // WriteBytes writes binary as 'bin' to the writer
  385. func (mw *Writer) WriteBytes(b []byte) error {
  386. sz := uint32(len(b))
  387. var err error
  388. switch {
  389. case sz <= math.MaxUint8:
  390. err = mw.prefix8(mbin8, uint8(sz))
  391. case sz <= math.MaxUint16:
  392. err = mw.prefix16(mbin16, uint16(sz))
  393. default:
  394. err = mw.prefix32(mbin32, sz)
  395. }
  396. if err != nil {
  397. return err
  398. }
  399. _, err = mw.Write(b)
  400. return err
  401. }
  402. // WriteBytesHeader writes just the size header
  403. // of a MessagePack 'bin' object. The user is responsible
  404. // for then writing 'sz' more bytes into the stream.
  405. func (mw *Writer) WriteBytesHeader(sz uint32) error {
  406. switch {
  407. case sz <= math.MaxUint8:
  408. return mw.prefix8(mbin8, uint8(sz))
  409. case sz <= math.MaxUint16:
  410. return mw.prefix16(mbin16, uint16(sz))
  411. default:
  412. return mw.prefix32(mbin32, sz)
  413. }
  414. }
  415. // WriteBool writes a bool to the writer
  416. func (mw *Writer) WriteBool(b bool) error {
  417. if b {
  418. return mw.push(mtrue)
  419. }
  420. return mw.push(mfalse)
  421. }
  422. // WriteString writes a messagepack string to the writer.
  423. // (This is NOT an implementation of io.StringWriter)
  424. func (mw *Writer) WriteString(s string) error {
  425. sz := uint32(len(s))
  426. var err error
  427. switch {
  428. case sz <= 31:
  429. err = mw.push(wfixstr(uint8(sz)))
  430. case sz <= math.MaxUint8:
  431. err = mw.prefix8(mstr8, uint8(sz))
  432. case sz <= math.MaxUint16:
  433. err = mw.prefix16(mstr16, uint16(sz))
  434. default:
  435. err = mw.prefix32(mstr32, sz)
  436. }
  437. if err != nil {
  438. return err
  439. }
  440. return mw.writeString(s)
  441. }
  442. // WriteStringHeader writes just the string size
  443. // header of a MessagePack 'str' object. The user
  444. // is responsible for writing 'sz' more valid UTF-8
  445. // bytes to the stream.
  446. func (mw *Writer) WriteStringHeader(sz uint32) error {
  447. switch {
  448. case sz <= 31:
  449. return mw.push(wfixstr(uint8(sz)))
  450. case sz <= math.MaxUint8:
  451. return mw.prefix8(mstr8, uint8(sz))
  452. case sz <= math.MaxUint16:
  453. return mw.prefix16(mstr16, uint16(sz))
  454. default:
  455. return mw.prefix32(mstr32, sz)
  456. }
  457. }
  458. // WriteStringFromBytes writes a 'str' object
  459. // from a []byte.
  460. func (mw *Writer) WriteStringFromBytes(str []byte) error {
  461. sz := uint32(len(str))
  462. var err error
  463. switch {
  464. case sz <= 31:
  465. err = mw.push(wfixstr(uint8(sz)))
  466. case sz <= math.MaxUint8:
  467. err = mw.prefix8(mstr8, uint8(sz))
  468. case sz <= math.MaxUint16:
  469. err = mw.prefix16(mstr16, uint16(sz))
  470. default:
  471. err = mw.prefix32(mstr32, sz)
  472. }
  473. if err != nil {
  474. return err
  475. }
  476. _, err = mw.Write(str)
  477. return err
  478. }
  479. // WriteComplex64 writes a complex64 to the writer
  480. func (mw *Writer) WriteComplex64(f complex64) error {
  481. o, err := mw.require(10)
  482. if err != nil {
  483. return err
  484. }
  485. mw.buf[o] = mfixext8
  486. mw.buf[o+1] = Complex64Extension
  487. big.PutUint32(mw.buf[o+2:], math.Float32bits(real(f)))
  488. big.PutUint32(mw.buf[o+6:], math.Float32bits(imag(f)))
  489. return nil
  490. }
  491. // WriteComplex128 writes a complex128 to the writer
  492. func (mw *Writer) WriteComplex128(f complex128) error {
  493. o, err := mw.require(18)
  494. if err != nil {
  495. return err
  496. }
  497. mw.buf[o] = mfixext16
  498. mw.buf[o+1] = Complex128Extension
  499. big.PutUint64(mw.buf[o+2:], math.Float64bits(real(f)))
  500. big.PutUint64(mw.buf[o+10:], math.Float64bits(imag(f)))
  501. return nil
  502. }
  503. // WriteMapStrStr writes a map[string]string to the writer
  504. func (mw *Writer) WriteMapStrStr(mp map[string]string) (err error) {
  505. err = mw.WriteMapHeader(uint32(len(mp)))
  506. if err != nil {
  507. return
  508. }
  509. for key, val := range mp {
  510. err = mw.WriteString(key)
  511. if err != nil {
  512. return
  513. }
  514. err = mw.WriteString(val)
  515. if err != nil {
  516. return
  517. }
  518. }
  519. return nil
  520. }
  521. // WriteMapStrIntf writes a map[string]interface to the writer
  522. func (mw *Writer) WriteMapStrIntf(mp map[string]interface{}) (err error) {
  523. err = mw.WriteMapHeader(uint32(len(mp)))
  524. if err != nil {
  525. return
  526. }
  527. for key, val := range mp {
  528. err = mw.WriteString(key)
  529. if err != nil {
  530. return
  531. }
  532. err = mw.WriteIntf(val)
  533. if err != nil {
  534. return
  535. }
  536. }
  537. return
  538. }
  539. // WriteTime writes a time.Time object to the wire.
  540. //
  541. // Time is encoded as Unix time, which means that
  542. // location (time zone) data is removed from the object.
  543. // The encoded object itself is 12 bytes: 8 bytes for
  544. // a big-endian 64-bit integer denoting seconds
  545. // elapsed since "zero" Unix time, followed by 4 bytes
  546. // for a big-endian 32-bit signed integer denoting
  547. // the nanosecond offset of the time. This encoding
  548. // is intended to ease portability across languages.
  549. // (Note that this is *not* the standard time.Time
  550. // binary encoding, because its implementation relies
  551. // heavily on the internal representation used by the
  552. // time package.)
  553. func (mw *Writer) WriteTime(t time.Time) error {
  554. t = t.UTC()
  555. o, err := mw.require(15)
  556. if err != nil {
  557. return err
  558. }
  559. mw.buf[o] = mext8
  560. mw.buf[o+1] = 12
  561. mw.buf[o+2] = TimeExtension
  562. putUnix(mw.buf[o+3:], t.Unix(), int32(t.Nanosecond()))
  563. return nil
  564. }
  565. // WriteIntf writes the concrete type of 'v'.
  566. // WriteIntf will error if 'v' is not one of the following:
  567. // - A bool, float, string, []byte, int, uint, or complex
  568. // - A map of supported types (with string keys)
  569. // - An array or slice of supported types
  570. // - A pointer to a supported type
  571. // - A type that satisfies the msgp.Encodable interface
  572. // - A type that satisfies the msgp.Extension interface
  573. func (mw *Writer) WriteIntf(v interface{}) error {
  574. if v == nil {
  575. return mw.WriteNil()
  576. }
  577. switch v := v.(type) {
  578. // preferred interfaces
  579. case Encodable:
  580. return v.EncodeMsg(mw)
  581. case Extension:
  582. return mw.WriteExtension(v)
  583. // concrete types
  584. case bool:
  585. return mw.WriteBool(v)
  586. case float32:
  587. return mw.WriteFloat32(v)
  588. case float64:
  589. return mw.WriteFloat64(v)
  590. case complex64:
  591. return mw.WriteComplex64(v)
  592. case complex128:
  593. return mw.WriteComplex128(v)
  594. case uint8:
  595. return mw.WriteUint8(v)
  596. case uint16:
  597. return mw.WriteUint16(v)
  598. case uint32:
  599. return mw.WriteUint32(v)
  600. case uint64:
  601. return mw.WriteUint64(v)
  602. case uint:
  603. return mw.WriteUint(v)
  604. case int8:
  605. return mw.WriteInt8(v)
  606. case int16:
  607. return mw.WriteInt16(v)
  608. case int32:
  609. return mw.WriteInt32(v)
  610. case int64:
  611. return mw.WriteInt64(v)
  612. case int:
  613. return mw.WriteInt(v)
  614. case string:
  615. return mw.WriteString(v)
  616. case []byte:
  617. return mw.WriteBytes(v)
  618. case map[string]string:
  619. return mw.WriteMapStrStr(v)
  620. case map[string]interface{}:
  621. return mw.WriteMapStrIntf(v)
  622. case time.Time:
  623. return mw.WriteTime(v)
  624. case time.Duration:
  625. return mw.WriteDuration(v)
  626. }
  627. val := reflect.ValueOf(v)
  628. if !isSupported(val.Kind()) || !val.IsValid() {
  629. return errors.New("msgp: type " + val.String() + " not supported")
  630. }
  631. switch val.Kind() {
  632. case reflect.Ptr:
  633. if val.IsNil() {
  634. return mw.WriteNil()
  635. }
  636. return mw.WriteIntf(val.Elem().Interface())
  637. case reflect.Slice:
  638. return mw.writeSlice(val)
  639. case reflect.Map:
  640. return mw.writeMap(val)
  641. }
  642. return &ErrUnsupportedType{T: val.Type()}
  643. }
  644. func (mw *Writer) writeMap(v reflect.Value) (err error) {
  645. if v.Type().Key().Kind() != reflect.String {
  646. return errors.New("msgp: map keys must be strings")
  647. }
  648. ks := v.MapKeys()
  649. err = mw.WriteMapHeader(uint32(len(ks)))
  650. if err != nil {
  651. return
  652. }
  653. for _, key := range ks {
  654. val := v.MapIndex(key)
  655. err = mw.WriteString(key.String())
  656. if err != nil {
  657. return
  658. }
  659. err = mw.WriteIntf(val.Interface())
  660. if err != nil {
  661. return
  662. }
  663. }
  664. return
  665. }
  666. func (mw *Writer) writeSlice(v reflect.Value) (err error) {
  667. // is []byte
  668. if v.Type().ConvertibleTo(btsType) {
  669. return mw.WriteBytes(v.Bytes())
  670. }
  671. sz := uint32(v.Len())
  672. err = mw.WriteArrayHeader(sz)
  673. if err != nil {
  674. return
  675. }
  676. for i := uint32(0); i < sz; i++ {
  677. err = mw.WriteIntf(v.Index(int(i)).Interface())
  678. if err != nil {
  679. return
  680. }
  681. }
  682. return
  683. }
  684. // is the reflect.Kind encodable?
  685. func isSupported(k reflect.Kind) bool {
  686. switch k {
  687. case reflect.Func, reflect.Chan, reflect.Invalid, reflect.UnsafePointer:
  688. return false
  689. default:
  690. return true
  691. }
  692. }
  693. // GuessSize guesses the size of the underlying
  694. // value of 'i'. If the underlying value is not
  695. // a simple builtin (or []byte), GuessSize defaults
  696. // to 512.
  697. func GuessSize(i interface{}) int {
  698. if i == nil {
  699. return NilSize
  700. }
  701. switch i := i.(type) {
  702. case Sizer:
  703. return i.Msgsize()
  704. case Extension:
  705. return ExtensionPrefixSize + i.Len()
  706. case float64:
  707. return Float64Size
  708. case float32:
  709. return Float32Size
  710. case uint8, uint16, uint32, uint64, uint:
  711. return UintSize
  712. case int8, int16, int32, int64, int:
  713. return IntSize
  714. case []byte:
  715. return BytesPrefixSize + len(i)
  716. case string:
  717. return StringPrefixSize + len(i)
  718. case complex64:
  719. return Complex64Size
  720. case complex128:
  721. return Complex128Size
  722. case bool:
  723. return BoolSize
  724. case map[string]interface{}:
  725. s := MapHeaderSize
  726. for key, val := range i {
  727. s += StringPrefixSize + len(key) + GuessSize(val)
  728. }
  729. return s
  730. case map[string]string:
  731. s := MapHeaderSize
  732. for key, val := range i {
  733. s += 2*StringPrefixSize + len(key) + len(val)
  734. }
  735. return s
  736. default:
  737. return 512
  738. }
  739. }