mirror of
https://github.com/golang/go
synced 2024-09-28 22:14:28 -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:
parent
aa9dd50095
commit
d67ac93895
@ -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.
|
// 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)].
|
// Delete zeroes the elements s[len(s)-(j-i):len(s)].
|
||||||
func Delete[S ~[]E, E any](s S, i, j int) 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)
|
oldlen := len(s)
|
||||||
s = append(s[:i], s[j:]...)
|
s = append(s[:i], s[j:]...)
|
||||||
|
@ -679,8 +679,10 @@ func TestDeletePanics(t *testing.T) {
|
|||||||
{"with negative second index", []int{42}, 1, -1},
|
{"with negative second index", []int{42}, 1, -1},
|
||||||
{"with out-of-bounds first index", []int{42}, 2, 3},
|
{"with out-of-bounds first index", []int{42}, 2, 3},
|
||||||
{"with out-of-bounds second index", []int{42}, 0, 2},
|
{"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},
|
{"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 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) }) {
|
if !panics(func() { Delete(test.s, test.i, test.j) }) {
|
||||||
t.Errorf("Delete %s: got no panic, want panic", test.name)
|
t.Errorf("Delete %s: got no panic, want panic", test.name)
|
||||||
|
Loading…
Reference in New Issue
Block a user