From d3e827d371ac2e6bb68c81d992f99ccd4b1b2cf1 Mon Sep 17 00:00:00 2001 From: Deleplace Date: Thu, 22 Feb 2024 23:44:31 +0100 Subject: [PATCH] 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 Reviewed-by: Keith Randall Auto-Submit: Keith Randall LUCI-TryBot-Result: Go LUCI Reviewed-by: Keith Randall --- src/slices/slices.go | 6 +++++- src/slices/slices_test.go | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/slices/slices.go b/src/slices/slices.go index b0f048a6566..3e01eb2fb77 100644 --- a/src/slices/slices.go +++ b/src/slices/slices.go @@ -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:]) diff --git a/src/slices/slices_test.go b/src/slices/slices_test.go index 31d59abe17b..4b5f0355df2 100644 --- a/src/slices/slices_test.go +++ b/src/slices/slices_test.go @@ -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