khenaidoo | 59ce9dd | 2019-11-11 13:05:32 -0500 | [diff] [blame] | 1 | package runtime |
| 2 | |
| 3 | import ( |
| 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 |
| 12 | type ProtoMarshaller struct{} |
| 13 | |
| 14 | // ContentType always returns "application/octet-stream". |
| 15 | func (*ProtoMarshaller) ContentType() string { |
| 16 | return "application/octet-stream" |
| 17 | } |
| 18 | |
| 19 | // Marshal marshals "value" into Proto |
| 20 | func (*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" |
| 29 | func (*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". |
| 38 | func (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". |
| 49 | func (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 | } |