Skip to content

Commit

Permalink
types/known/anypb: gracefully handle nil sources
Browse files Browse the repository at this point in the history
Add checks so that MarshalFrom and UnmarshalTo consistently matches
the behavior of the proto package with regard to nil messages.
In particular, using a nil message as the destination results in
a panic (which is already the current behavior), while using a
nil message as the source does not panic (it is usually treated as
an untyped empty message). Since an untyped message has no
sensible meaning in the context of Any, return an error.

Change-Id: I99e86c2cdfbd8be57cc039efd550458dc56aadbc
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/237920
Reviewed-by: Damien Neil <dneil@google.com>
  • Loading branch information
dsnet committed Jun 15, 2020
1 parent beaa552 commit bfc3102
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
6 changes: 6 additions & 0 deletions cmd/protoc-gen-go/internal_gengo/well_known_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ func genMessageKnownFunctions(g *protogen.GeneratedFile, f *fileInfo, m *message
g.P("// If no options are specified, call dst.MarshalFrom instead.")
g.P("func MarshalFrom(dst *Any, src ", protoPackage.Ident("Message"), ", opts ", protoPackage.Ident("MarshalOptions"), ") error {")
g.P(" const urlPrefix = \"type.googleapis.com/\"")
g.P(" if src == nil {")
g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil source message\")")
g.P(" }")
g.P(" b, err := opts.Marshal(src)")
g.P(" if err != nil {")
g.P(" return err")
Expand All @@ -41,6 +44,9 @@ func genMessageKnownFunctions(g *protogen.GeneratedFile, f *fileInfo, m *message
g.P("//")
g.P("// If no options are specified, call src.UnmarshalTo instead.")
g.P("func UnmarshalTo(src *Any, dst ", protoPackage.Ident("Message"), ", opts ", protoPackage.Ident("UnmarshalOptions"), ") error {")
g.P(" if src.GetTypeUrl() == \"\" {")
g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid empty type URL\")")
g.P(" }")
g.P(" if !src.MessageIs(dst) {")
g.P(" got := dst.ProtoReflect().Descriptor().FullName()")
g.P(" want := src.MessageName()")
Expand Down
6 changes: 6 additions & 0 deletions types/known/anypb/any.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit bfc3102

Please sign in to comment.