1
0
mirror of https://github.com/golang/go synced 2024-09-28 20:24:29 -06:00

slices: optimize Delete

Makes Delete return early if no elements need to be deleted.

Change-Id: Id64f716b1529e9dd5972c920a54823dba75aafe9
GitHub-Last-Rev: 885c1afb5d
GitHub-Pull-Request: golang/go#63411
Reviewed-on: https://go-review.googlesource.com/c/go/+/533276
Reviewed-by: Keith Randall <khr@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Keith Randall <khr@golang.org>
This commit is contained in:
go101 2023-11-15 17:55:46 +00:00 committed by Keith Randall
parent aa9dd50095
commit d67ac93895
2 changed files with 7 additions and 1 deletions

View File

@ -217,7 +217,11 @@ func Insert[S ~[]E, E any](s S, i int, v ...E) S {
// make a single call deleting them all together than to delete one at a time.
// Delete zeroes the elements s[len(s)-(j-i):len(s)].
func Delete[S ~[]E, E any](s S, i, j int) S {
_ = s[i:j] // bounds check
_ = s[i:j:len(s)] // bounds check
if i == j {
return s
}
oldlen := len(s)
s = append(s[:i], s[j:]...)

View File

@ -679,8 +679,10 @@ func TestDeletePanics(t *testing.T) {
{"with negative second index", []int{42}, 1, -1},
{"with out-of-bounds first index", []int{42}, 2, 3},
{"with out-of-bounds second index", []int{42}, 0, 2},
{"with out-of-bounds both indexes", []int{42}, 2, 2},
{"with invalid i>j", []int{42}, 1, 0},
{"s[i:j] is valid and j > len(s)", s, 0, 4},
{"s[i:j] is valid and i == j > len(s)", s, 3, 3},
} {
if !panics(func() { Delete(test.s, test.i, test.j) }) {
t.Errorf("Delete %s: got no panic, want panic", test.name)