Skip to content

Commit f73c567

Browse files
committedJun 14, 2023
common/collections: Always make a copy of the input slice in Append
Fixes #10458.
1 parent d178fe9 commit f73c567

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed
 

‎common/collections/append.go

+7
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ func Append(to any, from ...any) (any, error) {
3131
var tot reflect.Type
3232

3333
if !toIsNil {
34+
if tov.Kind() == reflect.Slice {
35+
// Create a copy of tov, so we don't modify the original.
36+
c := reflect.MakeSlice(tov.Type(), tov.Len(), tov.Len()+len(from))
37+
reflect.Copy(c, tov)
38+
tov = c
39+
}
40+
3441
if tov.Kind() != reflect.Slice {
3542
return nil, fmt.Errorf("expected a slice, got %T", to)
3643
}

‎common/collections/append_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,15 @@ func TestAppendToMultiDimensionalSlice(t *testing.T) {
129129
}
130130

131131
}
132+
133+
func TestAppendShouldMakeACopyOfTheInputSlice(t *testing.T) {
134+
t.Parallel()
135+
c := qt.New(t)
136+
slice := make([]string, 0, 100)
137+
slice = append(slice, "a", "b")
138+
result, err := Append(slice, "c")
139+
c.Assert(err, qt.IsNil)
140+
slice[0] = "d"
141+
c.Assert(result, qt.DeepEquals, []string{"a", "b", "c"})
142+
c.Assert(slice, qt.DeepEquals, []string{"d", "b"})
143+
}

0 commit comments

Comments
 (0)
Please sign in to comment.