github.com/TrueCloudLab/frostfs-api-go/v2@v2.0.0-20230228134343-196241c4e79a/rpc/message/encoding.go (about)

     1  package message
     2  
     3  import (
     4  	"github.com/TrueCloudLab/frostfs-api-go/v2/rpc/grpc"
     5  	"google.golang.org/protobuf/encoding/protojson"
     6  	"google.golang.org/protobuf/proto"
     7  )
     8  
     9  // GRPCConvertedMessage is an interface
    10  // of the gRPC message that is used
    11  // for Message encoding/decoding.
    12  type GRPCConvertedMessage interface {
    13  	grpc.Message
    14  	proto.Message
    15  }
    16  
    17  // Unmarshal decodes m from its Protobuf binary representation
    18  // via related gRPC message.
    19  //
    20  // gm should be tof the same type as the m.ToGRPCMessage() return.
    21  func Unmarshal(m Message, data []byte, gm GRPCConvertedMessage) error {
    22  	if err := proto.Unmarshal(data, gm); err != nil {
    23  		return err
    24  	}
    25  
    26  	return m.FromGRPCMessage(gm)
    27  }
    28  
    29  // MarshalJSON encodes m to Protobuf JSON representation.
    30  func MarshalJSON(m Message) ([]byte, error) {
    31  	return protojson.MarshalOptions{
    32  		EmitUnpopulated: true,
    33  	}.Marshal(
    34  		m.ToGRPCMessage().(proto.Message),
    35  	)
    36  }
    37  
    38  // UnmarshalJSON decodes m from its Protobuf JSON representation
    39  // via related gRPC message.
    40  //
    41  // gm should be tof the same type as the m.ToGRPCMessage() return.
    42  func UnmarshalJSON(m Message, data []byte, gm GRPCConvertedMessage) error {
    43  	if err := protojson.Unmarshal(data, gm); err != nil {
    44  		return err
    45  	}
    46  
    47  	return m.FromGRPCMessage(gm)
    48  }