2019-01-10 09:42:02 +00:00
|
|
|
package proto
|
|
|
|
|
|
|
|
import (
|
2020-04-08 12:50:19 +03:00
|
|
|
"bytes"
|
|
|
|
|
2019-01-10 09:42:02 +00:00
|
|
|
"github.com/golang/protobuf/proto"
|
2020-04-08 12:50:19 +03:00
|
|
|
"github.com/micro/go-micro/v2/codec"
|
|
|
|
"github.com/oxtoacart/bpool"
|
2019-01-10 09:42:02 +00:00
|
|
|
)
|
|
|
|
|
2020-04-08 12:50:19 +03:00
|
|
|
// create buffer pool with 16 instances each preallocated with 256 bytes
|
|
|
|
var bufferPool = bpool.NewSizedBufferPool(16, 256)
|
|
|
|
|
2019-01-10 09:42:02 +00:00
|
|
|
type Marshaler struct{}
|
|
|
|
|
|
|
|
func (Marshaler) Marshal(v interface{}) ([]byte, error) {
|
2020-04-08 12:50:19 +03:00
|
|
|
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 09:42:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (Marshaler) Unmarshal(data []byte, v interface{}) error {
|
2020-04-08 12:50:19 +03:00
|
|
|
pb, ok := v.(proto.Message)
|
|
|
|
if !ok {
|
|
|
|
return codec.ErrInvalidMessage
|
|
|
|
}
|
|
|
|
|
|
|
|
return proto.Unmarshal(data, pb)
|
2019-01-10 09:42:02 +00:00
|
|
|
}
|
|
|
|
|
2019-06-01 16:14:06 +08:00
|
|
|
func (Marshaler) String() string {
|
2019-01-10 09:42:02 +00:00
|
|
|
return "proto"
|
|
|
|
}
|