blob: f65d1a2676b871aa03f3362c6d150c14baba268a [file] [log] [blame]
khenaidoo59ce9dd2019-11-11 13:05:32 -05001package runtime
2
3import (
4 "io"
5
6 "errors"
7 "github.com/golang/protobuf/proto"
8 "io/ioutil"
9)
10
11// ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes
12type ProtoMarshaller struct{}
13
14// ContentType always returns "application/octet-stream".
15func (*ProtoMarshaller) ContentType() string {
16 return "application/octet-stream"
17}
18
19// Marshal marshals "value" into Proto
20func (*ProtoMarshaller) Marshal(value interface{}) ([]byte, error) {
21 message, ok := value.(proto.Message)
22 if !ok {
23 return nil, errors.New("unable to marshal non proto field")
24 }
25 return proto.Marshal(message)
26}
27
28// Unmarshal unmarshals proto "data" into "value"
29func (*ProtoMarshaller) Unmarshal(data []byte, value interface{}) error {
30 message, ok := value.(proto.Message)
31 if !ok {
32 return errors.New("unable to unmarshal non proto field")
33 }
34 return proto.Unmarshal(data, message)
35}
36
37// NewDecoder returns a Decoder which reads proto stream from "reader".
38func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
39 return DecoderFunc(func(value interface{}) error {
40 buffer, err := ioutil.ReadAll(reader)
41 if err != nil {
42 return err
43 }
44 return marshaller.Unmarshal(buffer, value)
45 })
46}
47
48// NewEncoder returns an Encoder which writes proto stream into "writer".
49func (marshaller *ProtoMarshaller) NewEncoder(writer io.Writer) Encoder {
50 return EncoderFunc(func(value interface{}) error {
51 buffer, err := marshaller.Marshal(value)
52 if err != nil {
53 return err
54 }
55 _, err = writer.Write(buffer)
56 if err != nil {
57 return err
58 }
59
60 return nil
61 })
62}