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 <lassefolger@google.com>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Michael Stapelberg 2024-03-27 10:26:55 +01:00
parent c69658e234
commit 4fd828fdbf
2 changed files with 20 additions and 0 deletions

View File

@ -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

View File

@ -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
}