]> Cypherpunks repositories - gostls13.git/commitdiff
slices: Delete clears the tail when j == len(s)
authorDeleplace <deleplace@google.com>
Thu, 22 Feb 2024 22:44:31 +0000 (23:44 +0100)
committerGopher Robot <gobot@golang.org>
Tue, 27 Feb 2024 21:29:43 +0000 (21:29 +0000)
Fixes #65669

Change-Id: Ifd2011dd604fef399e4352b804fc2f6a9e74096e
Reviewed-on: https://go-review.googlesource.com/c/go/+/566237
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Keith Randall <khr@google.com>
Auto-Submit: Keith Randall <khr@golang.org>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Keith Randall <khr@golang.org>
src/slices/slices.go
src/slices/slices_test.go

index b0f048a6566014875edd80606d12cb4b82fce2ce..3e01eb2fb7762f84881dd3dc26b48bf2cc199820 100644 (file)
@@ -258,7 +258,11 @@ func Replace[S ~[]E, E any](s S, i, j int, v ...E) S {
                return Insert(s, i, v...)
        }
        if j == len(s) {
-               return append(s[:i], v...)
+               s2 := append(s[:i], v...)
+               if len(s2) < len(s) {
+                       clear(s[len(s2):len(s)]) // zero/nil out the obsolete elements, for GC
+               }
+               return s2
        }
 
        tot := len(s[:i]) + len(v) + len(s[j:])
index 31d59abe17b3734d9e35fa0de9e1813d4eec5acc..4b5f0355df2af713a11f34e3d546a6117308050e 100644 (file)
@@ -1120,6 +1120,19 @@ func TestReplaceOverlap(t *testing.T) {
        }
 }
 
+func TestReplaceEndClearTail(t *testing.T) {
+       s := []int{11, 22, 33}
+       v := []int{99}
+       // case when j == len(s)
+       i, j := 1, 3
+       s = Replace(s, i, j, v...)
+
+       x := s[:3][2]
+       if want := 0; x != want {
+               t.Errorf("TestReplaceEndClearTail: obsolete element is %d, want %d", x, want)
+       }
+}
+
 func BenchmarkReplace(b *testing.B) {
        cases := []struct {
                name string