1
0
mirror of https://github.com/golang/go synced 2024-11-22 14:04:48 -07:00

slices: Delete clears the tail when j == len(s)

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>
This commit is contained in:
Deleplace 2024-02-22 23:44:31 +01:00 committed by Gopher Robot
parent b847d4cd2c
commit d3e827d371
2 changed files with 18 additions and 1 deletions

View 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:])

View 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