diff options
author | Bjørn Erik Pedersen <[email protected]> | 2023-06-14 09:44:18 +0200 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2023-06-14 20:18:54 +0200 |
commit | f73c5675341d41cb41b886b089544701022b5c12 (patch) | |
tree | a0815d89c447b9941f508ab3de3f78787499a6bc | |
parent | d178fe94fe26ce2cf8096f330f3d160af3ec818d (diff) | |
download | hugo-f73c5675341d41cb41b886b089544701022b5c12.tar.gz hugo-f73c5675341d41cb41b886b089544701022b5c12.zip |
common/collections: Always make a copy of the input slice in Append
Fixes #10458.
-rw-r--r-- | common/collections/append.go | 7 | ||||
-rw-r--r-- | common/collections/append_test.go | 12 |
2 files changed, 19 insertions, 0 deletions
diff --git a/common/collections/append.go b/common/collections/append.go index fe8792fc4..91abc46d3 100644 --- a/common/collections/append.go +++ b/common/collections/append.go @@ -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) } diff --git a/common/collections/append_test.go b/common/collections/append_test.go index f997e7a20..415eb2f25 100644 --- a/common/collections/append_test.go +++ b/common/collections/append_test.go @@ -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"}) +} |