Skip to content

Commit 4cc3b17

Browse files
Deleplacegopherbot
authored andcommitted
slices.Delete: fix behavior on invalid slice indices arguments
Now doing an explicit bounds check, to panic on invalid indices Fixes part (3) of golang/go#54650 Change-Id: I62a70c0f866e6c336d0c7feae5af33272fc568b6 Reviewed-on: https://go-review.googlesource.com/c/exp/+/425894 Auto-Submit: Keith Randall <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Run-TryBot: Keith Randall <[email protected]> Reviewed-by: Keith Randall <[email protected]> Reviewed-by: Keith Randall <[email protected]>
1 parent 807a232 commit 4cc3b17

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

slices/slices.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,8 @@ func Insert[S ~[]E, E any](s S, i int, v ...E) S {
154154
// Delete is O(len(s)-(j-i)), so if many items must be deleted, it is better to
155155
// make a single call deleting them all together than to delete one at a time.
156156
func Delete[S ~[]E, E any](s S, i, j int) S {
157+
_ = s[i:j] // bounds check
158+
157159
return append(s[:i], s[j:]...)
158160
}
159161

slices/slices_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,34 @@ func TestDelete(t *testing.T) {
447447
}
448448
}
449449

450+
func panics(f func()) (b bool) {
451+
defer func() {
452+
if x := recover(); x != nil {
453+
b = true
454+
}
455+
}()
456+
f()
457+
return false
458+
}
459+
460+
func TestDeletePanics(t *testing.T) {
461+
for _, test := range []struct {
462+
name string
463+
s []int
464+
i, j int
465+
}{
466+
{"with negative first index", []int{42}, -2, 1},
467+
{"with negative second index", []int{42}, 1, -1},
468+
{"with out-of-bounds first index", []int{42}, 2, 3},
469+
{"with out-of-bounds second index", []int{42}, 0, 2},
470+
{"with invalid i>j", []int{42}, 1, 0},
471+
} {
472+
if !panics(func() { Delete(test.s, test.i, test.j) }) {
473+
t.Errorf("Delete %s: got no panic, want panic", test.name)
474+
}
475+
}
476+
}
477+
450478
func TestClone(t *testing.T) {
451479
s1 := []int{1, 2, 3}
452480
s2 := Clone(s1)

0 commit comments

Comments
 (0)