9 "github.com/vmihailenco/msgpack/codes"
12 type writer interface {
15 WriteString(string) (int, error)
18 type byteWriter struct {
25 func newByteWriter(w io.Writer) *byteWriter {
29 bw.buf = bw.bootstrap[:]
33 func (w *byteWriter) WriteByte(c byte) error {
36 _, err := w.Write(w.buf)
40 func (w *byteWriter) WriteString(s string) (int, error) {
41 w.buf = append(w.buf[:0], s...)
45 // Marshal returns the MessagePack encoding of v.
46 func Marshal(v interface{}) ([]byte, error) {
48 err := NewEncoder(&buf).Encode(v)
49 return buf.Bytes(), err
62 // NewEncoder returns a new encoder that writes to w.
63 func NewEncoder(w io.Writer) *Encoder {
74 // SortMapKeys causes the Encoder to encode map keys in increasing order.
75 // Supported map types are:
76 // - map[string]string
77 // - map[string]interface{}
78 func (e *Encoder) SortMapKeys(flag bool) *Encoder {
83 // StructAsArray causes the Encoder to encode Go structs as MessagePack arrays.
84 func (e *Encoder) StructAsArray(flag bool) *Encoder {
85 e.structAsArray = flag
89 // UseJSONTag causes the Encoder to use json struct tag as fallback option
90 // if there is no msgpack tag.
91 func (e *Encoder) UseJSONTag(flag bool) *Encoder {
96 // UseCompactEncoding causes the Encoder to chose the most compact encoding.
97 // For example, it allows to encode Go int64 as msgpack int8 saving 7 bytes.
98 func (e *Encoder) UseCompactEncoding(flag bool) *Encoder {
103 func (e *Encoder) Encode(v interface{}) error {
104 switch v := v.(type) {
108 return e.EncodeString(v)
110 return e.EncodeBytes(v)
112 return e.encodeInt64Cond(int64(v))
114 return e.encodeInt64Cond(v)
116 return e.encodeUint64Cond(uint64(v))
118 return e.encodeUint64Cond(v)
120 return e.EncodeBool(v)
122 return e.EncodeFloat32(v)
124 return e.EncodeFloat64(v)
126 return e.encodeInt64Cond(int64(v))
128 return e.EncodeTime(v)
130 return e.EncodeValue(reflect.ValueOf(v))
133 func (e *Encoder) EncodeMulti(v ...interface{}) error {
134 for _, vv := range v {
135 if err := e.Encode(vv); err != nil {
142 func (e *Encoder) EncodeValue(v reflect.Value) error {
143 fn := getEncoder(v.Type())
147 func (e *Encoder) EncodeNil() error {
148 return e.writeCode(codes.Nil)
151 func (e *Encoder) EncodeBool(value bool) error {
153 return e.writeCode(codes.True)
155 return e.writeCode(codes.False)
158 func (e *Encoder) writeCode(c codes.Code) error {
159 return e.w.WriteByte(byte(c))
162 func (e *Encoder) write(b []byte) error {
163 _, err := e.w.Write(b)
167 func (e *Encoder) writeString(s string) error {
168 _, err := e.w.WriteString(s)