Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,21 @@ func BenchmarkStructMarshal(b *testing.B) {
}
}

func BenchmarkStructMarshalAppend(b *testing.B) {
in := structForBenchmark()
buf := make([]byte, 0, 2048)

b.ResetTimer()

for i := 0; i < b.N; i++ {
var err error
buf, err = msgpack.MarshalAppend(buf[:0], in)
if err != nil {
b.Fatal(err)
}
}
}

func BenchmarkStructUnmarshal(b *testing.B) {
in := structForBenchmark()
buf, err := msgpack.Marshal(in)
Expand Down
25 changes: 14 additions & 11 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,26 @@ func PutEncoder(enc *Encoder) {

// Marshal returns the MessagePack encoding of v.
func Marshal(v interface{}) ([]byte, error) {
return MarshalAppend(nil, v)
}

// MarshalAppend is like Marshal but appends the encoded bytes to dst.
// This allows callers to reuse buffers and reduce allocations:
//
// buf = buf[:0]
// buf, err = msgpack.MarshalAppend(buf, v)
func MarshalAppend(dst []byte, v interface{}) ([]byte, error) {
enc := GetEncoder()
enc.resetForMarshal()

err := enc.Encode(v)

var b []byte
if err == nil {
b = make([]byte, len(enc.wbuf))
copy(b, enc.wbuf)
if err := enc.Encode(v); err != nil {
PutEncoder(enc)
return dst, err
}

dst = append(dst, enc.wbuf...)
PutEncoder(enc)

if err != nil {
return nil, err
}
return b, nil
return dst, nil
}

type Encoder struct {
Expand Down