From: Jes Cok Date: Tue, 7 Nov 2023 20:37:26 +0000 (+0000) Subject: slices: make Insert panic if index is out of range and there are no values X-Git-Tag: go1.22rc1~378 X-Git-Url: http://www.git.cypherpunks.ru/?p=gostls13.git;a=commitdiff_plain;h=15d985a67529c45dcaad07461611e9a029c662f6 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 TryBot-Result: Gopher Robot Reviewed-by: Heschi Kreinick Run-TryBot: Jes Cok Reviewed-by: Keith Randall --- 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