codec: add codec to support both vtproto and google.golang.org/protobuf and probably gogoproto

Signed-off-by: Adphi <philippe.adrien.nousse@gmail.com>
This commit is contained in:
Adphi 2022-03-17 15:22:31 +01:00
parent 60234cceb3
commit 884d59e280
Signed by: adphi
GPG Key ID: 46BE4062DB2397FF
1 changed files with 52 additions and 0 deletions

52
codec/codec.go Normal file
View File

@ -0,0 +1,52 @@
package codec
import (
"fmt"
"google.golang.org/protobuf/proto"
)
// Name is the name registered for the proto compressor.
const Name = "proto"
type Codec struct{}
type vtprotoMessage interface {
MarshalVT() ([]byte, error)
UnmarshalVT([]byte) error
}
type protoMessage interface {
Marshal() ([]byte, error)
Unmarshal([]byte) error
}
func (Codec) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case vtprotoMessage:
return m.MarshalVT()
case protoMessage:
return m.Marshal()
case proto.Message:
return proto.Marshal(m)
default:
return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v)
}
}
func (Codec) Unmarshal(data []byte, v interface{}) error {
switch m := v.(type) {
case vtprotoMessage:
return m.UnmarshalVT(data)
case protoMessage:
return m.Unmarshal(data)
case proto.Message:
return proto.Unmarshal(data, m)
default:
return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v)
}
}
func (Codec) Name() string {
return Name
}