1
0
mirror of https://github.com/golang/go synced 2024-11-26 16:07:00 -07:00

slices: make Insert panic if index is out of range and there are no values

Fixes #63913

Change-Id: I514190b104a2c4bd5a6b0d96659b52904185e91f
GitHub-Last-Rev: 90e7195193
GitHub-Pull-Request: golang/go#63965
Reviewed-on: https://go-review.googlesource.com/c/go/+/540155
Reviewed-by: Keith Randall <khr@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Run-TryBot: Jes Cok <xigua67damn@gmail.com>
Reviewed-by: Keith Randall <khr@google.com>
This commit is contained in:
Jes Cok 2023-11-07 20:37:26 +00:00 committed by Keith Randall
parent 0891b17ce5
commit 15d985a675
2 changed files with 24 additions and 1 deletions

View File

@ -130,11 +130,14 @@ func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool {
// Insert panics if i is out of range.
// This function is O(len(s) + len(v)).
func Insert[S ~[]E, E any](s S, i int, v ...E) S {
n := len(s)
m := len(v)
if m == 0 {
// Panic if i is not in the range [0:n] inclusive.
// See issue 63913.
_ = s[:n:n][i:]
return s
}
n := len(s)
if i == n {
return append(s, v...)
}

View File

@ -536,6 +536,26 @@ func TestInsertOverlap(t *testing.T) {
}
}
func TestInsertPanics(t *testing.T) {
a := [3]int{}
for _, test := range []struct {
name string
s []int
i int
v []int
}{
// There are no values.
{"with negative index", a[:1:1], -1, nil},
{"with out-of-bounds index and > cap", a[:1:1], 2, nil},
{"with out-of-bounds index and = cap", a[:1:2], 2, nil},
{"with out-of-bounds index and < cap", a[:1:3], 2, nil},
} {
if !panics(func() { Insert(test.s, test.i, test.v...) }) {
t.Errorf("Insert %s: got no panic, want panic", test.name)
}
}
}
var deleteTests = []struct {
s []int
i, j int