github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/codec/proto/marshaler.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/codec/proto/marshaler.go 14 15 package proto 16 17 import ( 18 "bytes" 19 20 "github.com/golang/protobuf/proto" 21 "github.com/tickoalcantara12/micro/v3/util/codec" 22 "github.com/oxtoacart/bpool" 23 ) 24 25 // create buffer pool with 16 instances each preallocated with 256 bytes 26 var bufferPool = bpool.NewSizedBufferPool(16, 256) 27 28 type Marshaler struct{} 29 30 func (Marshaler) Marshal(v interface{}) ([]byte, error) { 31 pb, ok := v.(proto.Message) 32 if !ok { 33 return nil, codec.ErrInvalidMessage 34 } 35 36 // looks not good, but allows to reuse underlining bytes 37 buf := bufferPool.Get() 38 pbuf := proto.NewBuffer(buf.Bytes()) 39 defer func() { 40 bufferPool.Put(bytes.NewBuffer(pbuf.Bytes())) 41 }() 42 43 if err := pbuf.Marshal(pb); err != nil { 44 return nil, err 45 } 46 47 return pbuf.Bytes(), nil 48 } 49 50 func (Marshaler) Unmarshal(data []byte, v interface{}) error { 51 pb, ok := v.(proto.Message) 52 if !ok { 53 return codec.ErrInvalidMessage 54 } 55 56 return proto.Unmarshal(data, pb) 57 } 58 59 func (Marshaler) String() string { 60 return "proto" 61 }