package codec import ( "fmt" codecpkg "github.com/noahlann/nnet/pkg/codec" ) // ProtobufCodec Protobuf编解码器 // 注意:使用此编解码器需要实现Message接口 type ProtobufCodec struct{} // NewProtobufCodec 创建Protobuf编解码器 func NewProtobufCodec() codecpkg.Codec { return &ProtobufCodec{} } // Encode 编码 func (c *ProtobufCodec) Encode(v interface{}) ([]byte, error) { // 检查v是否实现了proto.Message接口 msg, ok := v.(protoMessage) if !ok { return nil, fmt.Errorf("value does not implement proto.Message interface") } return msg.Marshal() } // Decode 解码 func (c *ProtobufCodec) Decode(data []byte, v interface{}) error { msg, ok := v.(protoMessage) if !ok { return fmt.Errorf("value does not implement proto.Message interface") } return msg.Unmarshal(data) } // Name 获取编解码器名称 func (c *ProtobufCodec) Name() string { return "protobuf" } // protoMessage Protobuf消息接口(避免直接依赖protobuf库) type protoMessage interface { Marshal() ([]byte, error) Unmarshal(data []byte) error }