protobuf.go 949 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package mhayaSerializer
  2. import (
  3. cerr "github.com/mhaya/error"
  4. "google.golang.org/protobuf/proto"
  5. )
  6. // Protobuf implements the serialize.Protobuf interface
  7. type Protobuf struct{}
  8. // NewProtobuf NewSerializer returns a new Protobuf.
  9. func NewProtobuf() *Protobuf {
  10. return &Protobuf{}
  11. }
  12. // Marshal returns the protobuf encoding of v.
  13. func (p *Protobuf) Marshal(v interface{}) ([]byte, error) {
  14. if data, ok := v.([]byte); ok {
  15. return data, nil
  16. }
  17. pb, ok := v.(proto.Message)
  18. if !ok {
  19. return nil, cerr.ProtobufWrongValueType
  20. }
  21. return proto.Marshal(pb)
  22. }
  23. // Unmarshal parses the protobuf-encoded data and stores the result
  24. // in the value pointed to by v.
  25. func (p *Protobuf) Unmarshal(data []byte, v interface{}) error {
  26. pb, ok := v.(proto.Message)
  27. if !ok {
  28. return cerr.ProtobufWrongValueType
  29. }
  30. return proto.Unmarshal(data, pb)
  31. }
  32. // Name returns the name of the serializer.
  33. func (p *Protobuf) Name() string {
  34. return "protobuf"
  35. }