]> git.maquefel.me Git - brevno-suite/hugo/commitdiff
common/collections: Always make a copy of the input slice in Append
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Wed, 14 Jun 2023 07:44:18 +0000 (09:44 +0200)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Wed, 14 Jun 2023 18:18:54 +0000 (20:18 +0200)
Fixes #10458.

common/collections/append.go
common/collections/append_test.go

index fe8792fc421d390e73f6a37d4a59bf3670669d1d..91abc46d348db66fcd591a7455aab55ea2cffb72 100644 (file)
@@ -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)
                }
index f997e7a20b0a01d8745f8fac7bb59016d8ee0fdf..415eb2f257e77c1cf513e89744adf977b4d57044 100644 (file)
@@ -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"})
+}