Skip to content

Commit

Permalink
proto: extend Unmarshal documentation, include an example
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
stapelberg committed Mar 28, 2024
1 parent c69658e commit 4fd828f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions proto/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions proto/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}

0 comments on commit 4fd828f

Please sign in to comment.