Skip to content

Commit

Permalink
proto: implement encoding.BufferedCodec for the protobuf codec
Browse files Browse the repository at this point in the history
The implementation uses the `proto.Buffer` API that allows passing a
pre-existing buffer for the library to marshal into.
  • Loading branch information
HippoBaro committed Sep 10, 2023
1 parent 6e1f970 commit 86d4698
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions encoding/proto/proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ func (codec) Unmarshal(data []byte, v any) error {
return proto.Unmarshal(data, vv)
}

func (c codec) MarshalWithBuffer(v any, pool encoding.SharedBufferPool) ([]byte, error) {
vv, ok := v.(proto.Message)
if !ok {
return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
}

protoSize := proto.Size(vv)
buffer := proto.NewBuffer(pool.Get(protoSize)[:0])
if err := buffer.Marshal(vv); err != nil {
return nil, err
}

return buffer.Unread()[:protoSize], nil
}

func (codec) Name() string {
return Name
}

0 comments on commit 86d4698

Please sign in to comment.