From 8abc913b287dd45cc1fc9b2d7998c224986a329b Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Fri, 1 Oct 2021 01:08:24 +0300 Subject: [PATCH] codec: add MarshalAppend func Signed-off-by: Vasiliy Tolstov --- codec/codec.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/codec/codec.go b/codec/codec.go index 5449da18..090e3260 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -67,3 +67,20 @@ type Message struct { func NewMessage(t MessageType) *Message { return &Message{Type: t, Header: metadata.New(0)} } + +// MarshalAppend calls codec.Marshal(v) and returns the data appended to buf. +// If codec implements MarshalAppend, that is called instead. +func MarshalAppend(buf []byte, c Codec, v interface{}, opts ...Option) ([]byte, error) { + if nc, ok := c.(interface { + MarshalAppend([]byte, interface{}, ...Option) ([]byte, error) + }); ok { + return nc.MarshalAppend(buf, v, opts...) + } + + mbuf, err := c.Marshal(v, opts...) + if err != nil { + return nil, err + } + + return append(buf, mbuf...), nil +}