1
0
mirror of https://github.com/gusaul/grpcox.git synced 2025-01-26 06:14:40 +00:00
grpcox/vendor/github.com/jhump/protoreflect/dynamic/extension.go
2019-03-25 10:47:41 +07:00

45 lines
1.1 KiB
Go

package dynamic
import (
"fmt"
"github.com/golang/protobuf/proto"
"github.com/jhump/protoreflect/desc"
)
// SetExtension sets the given extension value. If the given message is not a
// dynamic message, the given extension may not be recognized (or may differ
// from the compiled and linked in version of the extension. So in that case,
// this function will serialize the given value to bytes and then use
// proto.SetRawExtension to set the value.
func SetExtension(msg proto.Message, extd *desc.FieldDescriptor, val interface{}) error {
if !extd.IsExtension() {
return fmt.Errorf("given field %s is not an extension", extd.GetFullyQualifiedName())
}
if dm, ok := msg.(*Message); ok {
return dm.TrySetField(extd, val)
}
md, err := desc.LoadMessageDescriptorForMessage(msg)
if err != nil {
return err
}
if err := checkField(extd, md); err != nil {
return err
}
val, err = validFieldValue(extd, val)
if err != nil {
return err
}
var b codedBuffer
if err := marshalField(extd.GetNumber(), extd, val, &b, defaultDeterminism); err != nil {
return err
}
proto.SetRawExtension(msg, extd.GetNumber(), b.buf)
return nil
}