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.
nnet/serialize/protobuf/protobuf.go

33 lines
686 B
Go

package protobuf
import (
"errors"
"git.noahlan.cn/noahlan/ntool/ndef"
"google.golang.org/protobuf/proto"
)
// ErrWrongValueType is the error used for marshal the value with protobuf encoding.
var ErrWrongValueType = errors.New("protobuf: convert on wrong type value")
type Serializer struct{}
func NewSerializer() ndef.Serializer {
return &Serializer{}
}
func (s *Serializer) Marshal(v any) ([]byte, error) {
pb, ok := v.(proto.Message)
if !ok {
return nil, ErrWrongValueType
}
return proto.Marshal(pb)
}
func (s *Serializer) Unmarshal(data []byte, v any) error {
pb, ok := v.(proto.Message)
if !ok {
return ErrWrongValueType
}
return proto.Unmarshal(data, pb)
}