]> Cypherpunks repositories - gostls13.git/commitdiff
slices: optimize Delete
authorgo101 <tapir.liu@gmail.com>
Wed, 15 Nov 2023 17:55:46 +0000 (17:55 +0000)
committerKeith Randall <khr@golang.org>
Sun, 19 Nov 2023 07:31:43 +0000 (07:31 +0000)
Makes Delete return early if no elements need to be deleted.

Change-Id: Id64f716b1529e9dd5972c920a54823dba75aafe9
GitHub-Last-Rev: 885c1afb5dcc76423791508e21ab84c67820efb2
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>
src/slices/slices.go
src/slices/slices_test.go

index f92a25da6afe066ac1cc09f2ed0bd0030d39227f..38b0fc14ad406a7a1c54345e5932cf97dcb4e001 100644 (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:]...)
index 8772fe1f1982eb0abd22a84666e0c27ec3391209..ab25bd8dfd980b8f82284bf6bb4f2f6208dba78b 100644 (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)