micro/codec/proto/marshaler.go

48 lines
943 B
Go
Raw Normal View History

2019-01-10 12:42:02 +03:00
package proto
import (
"bytes"
2019-01-10 12:42:02 +03:00
"github.com/golang/protobuf/proto"
"github.com/micro/go-micro/v3/codec"
"github.com/oxtoacart/bpool"
2019-01-10 12:42:02 +03:00
)
// create buffer pool with 16 instances each preallocated with 256 bytes
var bufferPool = bpool.NewSizedBufferPool(16, 256)
2019-01-10 12:42:02 +03:00
type Marshaler struct{}
func (Marshaler) Marshal(v interface{}) ([]byte, error) {
pb, ok := v.(proto.Message)
if !ok {
return nil, codec.ErrInvalidMessage
}
// looks not good, but allows to reuse underlining bytes
buf := bufferPool.Get()
pbuf := proto.NewBuffer(buf.Bytes())
defer func() {
bufferPool.Put(bytes.NewBuffer(pbuf.Bytes()))
}()
if err := pbuf.Marshal(pb); err != nil {
return nil, err
}
return pbuf.Bytes(), nil
2019-01-10 12:42:02 +03:00
}
func (Marshaler) Unmarshal(data []byte, v interface{}) error {
pb, ok := v.(proto.Message)
if !ok {
return codec.ErrInvalidMessage
}
return proto.Unmarshal(data, pb)
2019-01-10 12:42:02 +03:00
}
func (Marshaler) String() string {
2019-01-10 12:42:02 +03:00
return "proto"
}