2016-12-15 05:51:09 -05:00
|
|
|
package serial
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2021-06-19 09:36:54 -04:00
|
|
|
"google.golang.org/protobuf/types/known/anypb"
|
2020-12-19 21:50:46 -05:00
|
|
|
"reflect"
|
2021-06-04 19:42:53 -04:00
|
|
|
|
|
|
|
"github.com/golang/protobuf/proto"
|
2016-12-15 05:51:09 -05:00
|
|
|
)
|
|
|
|
|
2018-11-13 17:19:58 -05:00
|
|
|
// ToTypedMessage converts a proto Message into TypedMessage.
|
2021-06-19 09:36:54 -04:00
|
|
|
func ToTypedMessage(message proto.Message) *anypb.Any {
|
2016-12-15 05:51:09 -05:00
|
|
|
if message == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
settings, _ := proto.Marshal(message)
|
2021-06-19 09:36:54 -04:00
|
|
|
return &anypb.Any{
|
|
|
|
TypeUrl: GetMessageType(message),
|
|
|
|
Value: settings,
|
2016-12-15 05:51:09 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-13 16:46:01 -05:00
|
|
|
// GetMessageType returns the name of this proto Message.
|
2016-12-15 05:51:09 -05:00
|
|
|
func GetMessageType(message proto.Message) string {
|
|
|
|
return proto.MessageName(message)
|
|
|
|
}
|
|
|
|
|
2018-11-13 16:46:01 -05:00
|
|
|
// GetInstance creates a new instance of the message with messageType.
|
2016-12-15 05:51:09 -05:00
|
|
|
func GetInstance(messageType string) (interface{}, error) {
|
2016-12-30 17:12:00 -05:00
|
|
|
mType := proto.MessageType(messageType)
|
|
|
|
if mType == nil || mType.Elem() == nil {
|
2017-01-26 16:48:36 -05:00
|
|
|
return nil, errors.New("Serial: Unknown type: " + messageType)
|
2016-12-15 05:51:09 -05:00
|
|
|
}
|
2016-12-30 17:12:00 -05:00
|
|
|
return reflect.New(mType.Elem()).Interface(), nil
|
2016-12-15 05:51:09 -05:00
|
|
|
}
|
|
|
|
|
2021-06-19 09:36:54 -04:00
|
|
|
func GetInstanceOf(v *anypb.Any) (proto.Message, error) {
|
|
|
|
instance, err := GetInstance(v.TypeUrl)
|
2016-12-15 05:51:09 -05:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-01-06 09:32:36 -05:00
|
|
|
protoMessage := instance.(proto.Message)
|
|
|
|
if err := proto.Unmarshal(v.Value, protoMessage); err != nil {
|
2016-12-15 05:51:09 -05:00
|
|
|
return nil, err
|
|
|
|
}
|
2017-01-06 09:32:36 -05:00
|
|
|
return protoMessage, nil
|
2016-12-15 05:51:09 -05:00
|
|
|
}
|
2021-06-19 09:36:54 -04:00
|
|
|
|
|
|
|
func V2Type(v *anypb.Any) string {
|
2021-06-19 15:20:31 -04:00
|
|
|
return V2TypeFromURL(v.TypeUrl)
|
|
|
|
}
|
|
|
|
func V2TypeFromURL(string2 string) string {
|
|
|
|
return string2
|
|
|
|
}
|
|
|
|
func V2TypeHumanReadable(v *anypb.Any) string {
|
2021-06-19 09:36:54 -04:00
|
|
|
return v.TypeUrl
|
|
|
|
}
|
2021-06-19 15:20:31 -04:00
|
|
|
|
|
|
|
func V2URLFromV2Type(readableType string) string {
|
|
|
|
return readableType
|
|
|
|
}
|