gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

marshal_proto.go (1600B)


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