Skip to content

Commit

Permalink
common/collections: Always make a copy of the input slice in Append
Browse files Browse the repository at this point in the history
Fixes #10458.
  • Loading branch information
bep committed Jun 14, 2023
1 parent d178fe9 commit f73c567
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
7 changes: 7 additions & 0 deletions common/collections/append.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ func Append(to any, from ...any) (any, error) {
var tot reflect.Type

if !toIsNil {
if tov.Kind() == reflect.Slice {
// Create a copy of tov, so we don't modify the original.
c := reflect.MakeSlice(tov.Type(), tov.Len(), tov.Len()+len(from))
reflect.Copy(c, tov)
tov = c
}

if tov.Kind() != reflect.Slice {
return nil, fmt.Errorf("expected a slice, got %T", to)
}
Expand Down
12 changes: 12 additions & 0 deletions common/collections/append_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,15 @@ func TestAppendToMultiDimensionalSlice(t *testing.T) {
}

}

func TestAppendShouldMakeACopyOfTheInputSlice(t *testing.T) {
t.Parallel()
c := qt.New(t)
slice := make([]string, 0, 100)
slice = append(slice, "a", "b")
result, err := Append(slice, "c")
c.Assert(err, qt.IsNil)
slice[0] = "d"
c.Assert(result, qt.DeepEquals, []string{"a", "b", "c"})
c.Assert(slice, qt.DeepEquals, []string{"d", "b"})
}

0 comments on commit f73c567

Please sign in to comment.