2019-01-10 12:42:02 +03:00
|
|
|
package proto
|
|
|
|
|
|
|
|
import (
|
2020-04-08 12:50:19 +03:00
|
|
|
"bytes"
|
|
|
|
|
2019-01-10 12:42:02 +03:00
|
|
|
"github.com/golang/protobuf/proto"
|
2020-04-08 12:50:19 +03:00
|
|
|
"github.com/oxtoacart/bpool"
|
2020-08-20 15:23:41 +03:00
|
|
|
"github.com/unistack-org/micro/v3/codec"
|
2019-01-10 12:42:02 +03: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 12:42:02 +03: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 12:42:02 +03: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 12:42:02 +03:00
|
|
|
}
|
|
|
|
|
2019-06-01 11:14:06 +03:00
|
|
|
func (Marshaler) String() string {
|
2019-01-10 12:42:02 +03:00
|
|
|
return "proto"
|
|
|
|
}
|