]> Cypherpunks.ru repositories - gostls13.git/commitdiff
slices: make Insert panic if index is out of range and there are no values
authorJes Cok <xigua67damn@gmail.com>
Tue, 7 Nov 2023 20:37:26 +0000 (20:37 +0000)
committerKeith Randall <khr@golang.org>
Wed, 8 Nov 2023 18:36:53 +0000 (18:36 +0000)
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>
src/slices/slices.go
src/slices/slices_test.go

index 465af14f8e5eeeec2535c2d2d3a64fb1ee61d23e..fe50a91d4844f38e517926f7e390126c218c64b0 100644 (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...)
        }
index ac779f5bd955dbb1c7ab9b40bd0851199c21314f..7d4fc34b2e6bdbae2d6c52e14d11ad1acf7023b6 100644 (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