github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/codec/protobuf.go (about)

     1  package codec
     2  
     3  import (
     4  	"fmt"
     5  
     6  	proto "github.com/gogo/protobuf/proto"
     7  )
     8  
     9  // pbCodec uses protobuf marshaler and unmarshaler.
    10  type pbCodec struct{}
    11  
    12  var ProtoBuffer SerializeType = RegisterCodec("ProtoBuffer", &pbCodec{})
    13  
    14  // Encode encodes an object into slice of bytes.
    15  func (c pbCodec) Encode(i interface{}) ([]byte, error) {
    16  	if m, ok := i.(proto.Marshaler); ok {
    17  		return m.Marshal()
    18  	}
    19  
    20  	if m, ok := i.(proto.Message); ok {
    21  		return proto.Marshal(m)
    22  	}
    23  
    24  	return nil, fmt.Errorf("%T is not a proto.Marshaler", i)
    25  }
    26  
    27  // Decode decodes an object from slice of bytes.
    28  func (c pbCodec) Decode(data []byte, i interface{}) error {
    29  	if m, ok := i.(proto.Unmarshaler); ok {
    30  		return m.Unmarshal(data)
    31  	}
    32  
    33  	if m, ok := i.(proto.Message); ok {
    34  		return proto.Unmarshal(data, m)
    35  	}
    36  
    37  	return fmt.Errorf("%T is not a proto.Unmarshaler", i)
    38  }
    39  
    40  func (c pbCodec) String() string {
    41  	return "ProtoBuffer"
    42  }