Sfoglia il codice sorgente

proto: fix MarshalAppend fast path

Was overwriting the output buffer rather than appending to it.

Change-Id: I6ffb72a440f464f4259cfebc42c1dc75b73fb5ae
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/171117
Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
Damien Neil 6 anni fa
parent
commit
3016b73382
2 ha cambiato i file con 20 aggiunte e 4 eliminazioni
  1. 4 4
      proto/encode.go
  2. 16 0
      proto/encode_test.go

+ 4 - 4
proto/encode.go

@@ -65,18 +65,18 @@ func (o MarshalOptions) Marshal(m Message) ([]byte, error) {
 // MarshalAppend appends the wire-format encoding of m to b,
 // returning the result.
 func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) {
-	b, err := o.marshalMessageFast(b, m)
+	out, err := o.marshalMessageFast(b, m)
 	if err == errInternalNoFast {
-		b, err = o.marshalMessage(b, m.ProtoReflect())
+		out, err = o.marshalMessage(b, m.ProtoReflect())
 	}
 	var nerr errors.NonFatal
 	if !nerr.Merge(err) {
-		return b, err
+		return out, err
 	}
 	if !o.AllowPartial {
 		nerr.Merge(IsInitialized(m))
 	}
-	return b, nerr.E
+	return out, nerr.E
 }
 
 func (o MarshalOptions) marshalMessageFast(b []byte, m Message) ([]byte, error) {

+ 16 - 0
proto/encode_test.go

@@ -9,6 +9,8 @@ import (
 	protoV1 "github.com/golang/protobuf/proto"
 	"github.com/golang/protobuf/v2/proto"
 	"github.com/google/go-cmp/cmp"
+
+	test3pb "github.com/golang/protobuf/v2/internal/testprotos/test3"
 )
 
 func TestEncode(t *testing.T) {
@@ -105,3 +107,17 @@ func TestEncodeRequiredFieldChecks(t *testing.T) {
 		}
 	}
 }
+
+func TestMarshalAppend(t *testing.T) {
+	want := []byte("prefix")
+	got := append([]byte(nil), want...)
+	got, err := proto.MarshalOptions{}.MarshalAppend(got, &test3pb.TestAllTypes{
+		OptionalString: "value",
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if !bytes.HasPrefix(got, want) {
+		t.Fatalf("MarshalAppend modified prefix: got %v, want prefix %v", got, want)
+	}
+}