From 0084168af8481ecacedae9b627908fb0a96c6bbe Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Mon, 15 Jun 2020 12:22:20 -0700 Subject: [PATCH] types/known/anypb: add New constructor While the MarshalFrom method and function are more flexible since it permits the reuse of an existing Any, the most common use case by far is to construct a new Any. Optimize for that use case by providing a constructor that directly returns a new Any instance. We do not provide a variant that accepts a MarshalOptions since the more flexible MarshalFrom function can be used for that. Change-Id: Iab0219229c7d3aaa7390a2340a4f248002995293 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/237997 Reviewed-by: Damien Neil --- cmd/protoc-gen-go/internal_gengo/well_known_types.go | 10 ++++++++++ types/known/anypb/any.pb.go | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/cmd/protoc-gen-go/internal_gengo/well_known_types.go b/cmd/protoc-gen-go/internal_gengo/well_known_types.go index 4fc1cd73..7365075c 100644 --- a/cmd/protoc-gen-go/internal_gengo/well_known_types.go +++ b/cmd/protoc-gen-go/internal_gengo/well_known_types.go @@ -19,6 +19,16 @@ import ( func genMessageKnownFunctions(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { switch m.Desc.FullName() { case genid.Any_message_fullname: + g.P("// New marshals src into a new Any instance.") + g.P("func New(src ", protoPackage.Ident("Message"), ") (*Any, error) {") + g.P(" dst := new(Any)") + g.P(" if err := dst.MarshalFrom(src); err != nil {") + g.P(" return nil, err") + g.P(" }") + g.P(" return dst, nil") + g.P("}") + g.P() + g.P("// MarshalFrom marshals src into dst as the underlying message") g.P("// using the provided marshal options.") g.P("//") diff --git a/types/known/anypb/any.pb.go b/types/known/anypb/any.pb.go index 4a7f5bb8..061a9eeb 100644 --- a/types/known/anypb/any.pb.go +++ b/types/known/anypb/any.pb.go @@ -161,6 +161,15 @@ type Any struct { Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } +// New marshals src into a new Any instance. +func New(src proto.Message) (*Any, error) { + dst := new(Any) + if err := dst.MarshalFrom(src); err != nil { + return nil, err + } + return dst, nil +} + // MarshalFrom marshals src into dst as the underlying message // using the provided marshal options. //