aboutsummaryrefslogtreecommitdiff
path: root/src/slices
diff options
context:
space:
mode:
authorJes Cok <xigua67damn@gmail.com>2023-11-07 20:37:26 +0000
committerKeith Randall <khr@golang.org>2023-11-08 18:36:53 +0000
commit15d985a67529c45dcaad07461611e9a029c662f6 (patch)
tree2bc12f9f5247984e756ac2192f4efcb90a1f611d /src/slices
parent0891b17ce53de8350689a89e55583794a12d302e (diff)
downloadgo-15d985a67529c45dcaad07461611e9a029c662f6.tar.gz
go-15d985a67529c45dcaad07461611e9a029c662f6.zip
slices: make Insert panic if index is out of range and there are no values
Fixes #63913 Change-Id: I514190b104a2c4bd5a6b0d96659b52904185e91f GitHub-Last-Rev: 90e7195193b8e50009fc0d9dcbda953b1ec509b4 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>
Diffstat (limited to 'src/slices')
-rw-r--r--src/slices/slices.go5
-rw-r--r--src/slices/slices_test.go20
2 files changed, 24 insertions, 1 deletions
diff --git a/src/slices/slices.go b/src/slices/slices.go
index 465af14f8e..fe50a91d48 100644
--- a/src/slices/slices.go
+++ b/src/slices/slices.go
@@ -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...)
}
diff --git a/src/slices/slices_test.go b/src/slices/slices_test.go
index ac779f5bd9..7d4fc34b2e 100644
--- a/src/slices/slices_test.go
+++ b/src/slices/slices_test.go
@@ -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