You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.1 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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
}