github.com/annwntech/go-micro/v2@v2.9.5/codec/proto/marshaler.go (about) 1 package proto 2 3 import ( 4 "bytes" 5 6 "github.com/golang/protobuf/proto" 7 "github.com/annwntech/go-micro/v2/codec" 8 "github.com/oxtoacart/bpool" 9 ) 10 11 // create buffer pool with 16 instances each preallocated with 256 bytes 12 var bufferPool = bpool.NewSizedBufferPool(16, 256) 13 14 type Marshaler struct{} 15 16 func (Marshaler) Marshal(v interface{}) ([]byte, error) { 17 pb, ok := v.(proto.Message) 18 if !ok { 19 return nil, codec.ErrInvalidMessage 20 } 21 22 // looks not good, but allows to reuse underlining bytes 23 buf := bufferPool.Get() 24 pbuf := proto.NewBuffer(buf.Bytes()) 25 defer func() { 26 bufferPool.Put(bytes.NewBuffer(pbuf.Bytes())) 27 }() 28 29 if err := pbuf.Marshal(pb); err != nil { 30 return nil, err 31 } 32 33 return pbuf.Bytes(), nil 34 } 35 36 func (Marshaler) Unmarshal(data []byte, v interface{}) error { 37 pb, ok := v.(proto.Message) 38 if !ok { 39 return codec.ErrInvalidMessage 40 } 41 42 return proto.Unmarshal(data, pb) 43 } 44 45 func (Marshaler) String() string { 46 return "proto" 47 }