mirror of
https://github.com/protocolbuffers/protobuf-go.git
synced 2025-01-27 21:35:28 +00:00
proto: fix self-merging
While odd, it is possible to merge a message into itself. In such a situation, the material impact is that repeated and unknown fields are duplicated. The previous logic would inifinite loop since the list iteration logic uses the current length, but since the current length is ever growing, this loop will never terminate. Instead, record the list length once and iterate exactly that many times. Change-Id: Ief98afa1b20bd950a9c2422d4462b170dbe6fa11 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/196857 Reviewed-by: Damien Neil <dneil@google.com>
This commit is contained in:
parent
c908144c88
commit
641611d984
@ -45,7 +45,7 @@ func mergeMessage(dst, src protoreflect.Message) {
|
||||
}
|
||||
|
||||
func mergeList(dst, src protoreflect.List, fd protoreflect.FieldDescriptor) {
|
||||
for i := 0; i < src.Len(); i++ {
|
||||
for i, n := 0, src.Len(); i < n; i++ {
|
||||
switch v := src.Get(i); {
|
||||
case fd.Message() != nil:
|
||||
dstv := dst.NewElement()
|
||||
|
@ -401,3 +401,41 @@ func TestMergeRace(t *testing.T) {
|
||||
}(src)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeSelf(t *testing.T) {
|
||||
got := &testpb.TestAllTypes{
|
||||
OptionalInt32: proto.Int32(1),
|
||||
OptionalString: proto.String("hello"),
|
||||
RepeatedInt32: []int32{2, 3, 4},
|
||||
RepeatedString: []string{"goodbye"},
|
||||
MapStringString: map[string]string{"key": "value"},
|
||||
OptionalNestedMessage: &testpb.TestAllTypes_NestedMessage{
|
||||
A: proto.Int32(5),
|
||||
},
|
||||
}
|
||||
got.ProtoReflect().SetUnknown(pack.Message{
|
||||
pack.Tag{Number: 50000, Type: pack.VarintType}, pack.Svarint(-5),
|
||||
}.Marshal())
|
||||
proto.Merge(got, got)
|
||||
|
||||
// The main impact of merging to self is that repeated fields and
|
||||
// unknown fields are doubled.
|
||||
want := &testpb.TestAllTypes{
|
||||
OptionalInt32: proto.Int32(1),
|
||||
OptionalString: proto.String("hello"),
|
||||
RepeatedInt32: []int32{2, 3, 4, 2, 3, 4},
|
||||
RepeatedString: []string{"goodbye", "goodbye"},
|
||||
MapStringString: map[string]string{"key": "value"},
|
||||
OptionalNestedMessage: &testpb.TestAllTypes_NestedMessage{
|
||||
A: proto.Int32(5),
|
||||
},
|
||||
}
|
||||
want.ProtoReflect().SetUnknown(pack.Message{
|
||||
pack.Tag{Number: 50000, Type: pack.VarintType}, pack.Svarint(-5),
|
||||
pack.Tag{Number: 50000, Type: pack.VarintType}, pack.Svarint(-5),
|
||||
}.Marshal())
|
||||
|
||||
if !proto.Equal(got, want) {
|
||||
t.Errorf("Equal mismatch:\ngot %v\nwant %v", got, want)
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user