frostfs-api-go/rpc/message/encoding.go
Airat Arifullin f0642d7f13 [#40] types: Generate StableMarshaler methods for refs
* Add plugin option for protogen in Makefile
* Fix the generator for the plugin in util/protogen
* Fix marshaler.go for refs

Signed-off-by: Airat Arifullin a.arifullin@yadro.com
2023-06-13 01:33:53 +03:00

59 lines
1.7 KiB
Go

package message
import (
"git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/rpc/grpc"
protoutil "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/util/proto"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
// GRPCConvertedMessage is an interface
// of the gRPC message that is used
// for Message encoding/decoding.
type GRPCConvertedMessage interface {
grpc.Message
proto.Message
}
// Unmarshal decodes m from its Protobuf binary representation
// via related gRPC message.
//
// gm should be tof the same type as the m.ToGRPCMessage() return.
func Unmarshal(m Message, data []byte, gm GRPCConvertedMessage) error {
if err := proto.Unmarshal(data, gm); err != nil {
return err
}
return m.FromGRPCMessage(gm)
}
// MarshalJSON encodes m to Protobuf JSON representation.
func MarshalJSON(m Message) ([]byte, error) {
return protojson.MarshalOptions{
EmitUnpopulated: true,
}.Marshal(
m.ToGRPCMessage().(proto.Message),
)
}
// UnmarshalJSON decodes m from its Protobuf JSON representation
// via related gRPC message.
//
// gm should be tof the same type as the m.ToGRPCMessage() return.
func UnmarshalJSON(m Message, data []byte, gm GRPCConvertedMessage) error {
if err := protojson.Unmarshal(data, gm); err != nil {
return err
}
return m.FromGRPCMessage(gm)
}
// StableMarshal encodes message 'm' using the invocation from related gRPC message
func StableMarshal[M protoutil.StableMarshaller](m Message, buf []byte) []byte {
return m.ToGRPCMessage().(M).StableMarshal(buf)
}
// StableSize encodes message 'm' using the invocation from related gRPC message
func StableSize[M protoutil.StableMarshaller](m Message) int {
return m.ToGRPCMessage().(M).StableSize()
}