From 4fd828fdbf4719ded75c6f44681aea87a10968c2 Mon Sep 17 00:00:00 2001 From: Michael Stapelberg Date: Wed, 27 Mar 2024 10:26:55 +0100 Subject: [PATCH] proto: extend Unmarshal documentation, include an example This example uses the same protobuf and wire format encoding as the corresponding Marshal example added in commit https://go.googlesource.com/protobuf/+/c69658e23457d4e09 Change-Id: Ifd64a93a14589595cbe9b218235b57fb15d423c2 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/574635 Reviewed-by: Lasse Folger Reviewed-by: Damien Neil LUCI-TryBot-Result: Go LUCI --- proto/decode.go | 2 ++ proto/decode_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/proto/decode.go b/proto/decode.go index e5b03b56..d75a6534 100644 --- a/proto/decode.go +++ b/proto/decode.go @@ -51,6 +51,8 @@ type UnmarshalOptions struct { // Unmarshal parses the wire-format message in b and places the result in m. // The provided message must be mutable (e.g., a non-nil pointer to a message). +// +// See the [UnmarshalOptions] type if you need more control. func Unmarshal(b []byte, m Message) error { _, err := UnmarshalOptions{RecursionLimit: protowire.DefaultRecursionLimit}.unmarshal(b, m.ProtoReflect()) return err diff --git a/proto/decode_test.go b/proto/decode_test.go index 1b2f2166..d9db9468 100644 --- a/proto/decode_test.go +++ b/proto/decode_test.go @@ -14,6 +14,7 @@ import ( "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/testing/protopack" + "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/internal/errors" testpb "google.golang.org/protobuf/internal/testprotos/test" @@ -155,3 +156,20 @@ func extend(desc protoreflect.ExtensionType, value interface{}) buildOpt { proto.SetExtension(m, desc, value) } } + +// This example illustrates how to unmarshal (decode) wire format encoding into +// a Protobuf message. +func ExampleUnmarshal() { + // This is the wire format encoding produced by the Marshal example. + // Typically you would read from the network, from disk, etc. + b := []byte{0x10, 0x7d} + + var dur durationpb.Duration + if err := proto.Unmarshal(b, &dur); err != nil { + panic(err) + } + + fmt.Printf("Protobuf wire format decoded to duration %v\n", dur.AsDuration()) + + // Output: Protobuf wire format decoded to duration 125ns +}