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.
|
|
|
package protobuf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"git.noahlan.cn/northlan/nnet/core/serialize"
|
|
|
|
"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() serialize.Serializer {
|
|
|
|
return &Serializer{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Serializer) Marshal(v interface{}) ([]byte, error) {
|
|
|
|
pb, ok := v.(proto.Message)
|
|
|
|
if !ok {
|
|
|
|
return nil, ErrWrongValueType
|
|
|
|
}
|
|
|
|
return proto.Marshal(pb)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Serializer) Unmarshal(data []byte, v interface{}) error {
|
|
|
|
pb, ok := v.(proto.Message)
|
|
|
|
if !ok {
|
|
|
|
return ErrWrongValueType
|
|
|
|
}
|
|
|
|
return proto.Unmarshal(data, pb)
|
|
|
|
}
|