]> Cypherpunks repositories - gostls13.git/commitdiff
reflect: make Field panic when out of bounds, as documented
authorEmmanuel Odeke <emm.odeke@gmail.com>
Tue, 10 May 2016 14:06:47 +0000 (07:06 -0700)
committerBrad Fitzpatrick <bradfitz@golang.org>
Tue, 10 May 2016 15:16:33 +0000 (15:16 +0000)
Fixes #15046.

Change-Id: Iba7216297735be8e1ec550ce5336d17dcd3fd6b7
Reviewed-on: https://go-review.googlesource.com/22992
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>

src/reflect/all_test.go
src/reflect/type.go

index d4c3e4e588a89d70bbd306fefc3bc741e334ff61..1a7952d7892d8346096a329fa89f425ea172439a 100644 (file)
@@ -5221,6 +5221,41 @@ func TestLargeGCProg(t *testing.T) {
        fv.Call([]Value{ValueOf([256]*byte{})})
 }
 
+func fieldIndexRecover(t Type, i int) (recovered interface{}) {
+       defer func() {
+               recovered = recover()
+       }()
+
+       t.Field(i)
+       return
+}
+
+// Issue 15046.
+func TestTypeFieldOutOfRangePanic(t *testing.T) {
+       typ := TypeOf(struct{ X int }{10})
+       testIndices := [...]struct {
+               i         int
+               mustPanic bool
+       }{
+               0: {-2, true},
+               1: {0, false},
+               2: {1, true},
+               3: {1 << 10, true},
+       }
+       for i, tt := range testIndices {
+               recoveredErr := fieldIndexRecover(typ, tt.i)
+               if tt.mustPanic {
+                       if recoveredErr == nil {
+                               t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
+                       }
+               } else {
+                       if recoveredErr != nil {
+                               t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
+                       }
+               }
+       }
+}
+
 // Issue 9179.
 func TestCallGC(t *testing.T) {
        f := func(a, b, c, d, e string) {
index 2ceb3d3f661726469a8d65a9ef6456f99a0f48bc..b499d01a2c734619784c0797abb97e36cb747459 100644 (file)
@@ -1178,7 +1178,7 @@ func (tag StructTag) Lookup(key string) (value string, ok bool) {
 // Field returns the i'th struct field.
 func (t *structType) Field(i int) (f StructField) {
        if i < 0 || i >= len(t.fields) {
-               return
+               panic("reflect: Field index out of bounds")
        }
        p := &t.fields[i]
        f.Type = toType(p.typ)