mirror of https://github.com/golang/go.git
encoding/binary: on invalid type return -1 from Size
Size is defined as returning -1 if the type is not fixed-size. Before this CL cases like Size((*[]int)(nil)) would crash. Fixes #60892 Change-Id: Iee8e20a0aee24b542b78cb4160c3b2c5a3eb02c2 Reviewed-on: https://go-review.googlesource.com/c/go/+/504575 Auto-Submit: Ian Lance Taylor <iant@golang.org> Run-TryBot: Ian Lance Taylor <iant@golang.org> Reviewed-by: Robert Griesemer <gri@google.com> TryBot-Result: Gopher Robot <gobot@golang.org> Reviewed-by: Bryan Mills <bcmills@google.com>
This commit is contained in:
parent
8484f2fe02
commit
e122ebabb6
|
|
@ -479,7 +479,6 @@ func dataSize(v reflect.Value) int {
|
||||||
if s := sizeof(v.Type().Elem()); s >= 0 {
|
if s := sizeof(v.Type().Elem()); s >= 0 {
|
||||||
return s * v.Len()
|
return s * v.Len()
|
||||||
}
|
}
|
||||||
return -1
|
|
||||||
|
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
t := v.Type()
|
t := v.Type()
|
||||||
|
|
@ -491,8 +490,12 @@ func dataSize(v reflect.Value) int {
|
||||||
return size
|
return size
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
if v.IsValid() {
|
||||||
return sizeof(v.Type())
|
return sizeof(v.Type())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1
|
||||||
}
|
}
|
||||||
|
|
||||||
// sizeof returns the size >= 0 of variables for the given type or -1 if the type is not acceptable.
|
// sizeof returns the size >= 0 of variables for the given type or -1 if the type is not acceptable.
|
||||||
|
|
|
||||||
|
|
@ -351,6 +351,26 @@ func TestSizeStructCache(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSizeInvalid(t *testing.T) {
|
||||||
|
testcases := []any{
|
||||||
|
int(0),
|
||||||
|
new(int),
|
||||||
|
(*int)(nil),
|
||||||
|
[1]uint{},
|
||||||
|
new([1]uint),
|
||||||
|
(*[1]uint)(nil),
|
||||||
|
[]int{},
|
||||||
|
[]int(nil),
|
||||||
|
new([]int),
|
||||||
|
(*[]int)(nil),
|
||||||
|
}
|
||||||
|
for _, tc := range testcases {
|
||||||
|
if got := Size(tc); got != -1 {
|
||||||
|
t.Errorf("Size(%T) = %d, want -1", tc, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// An attempt to read into a struct with an unexported field will
|
// An attempt to read into a struct with an unexported field will
|
||||||
// panic. This is probably not the best choice, but at this point
|
// panic. This is probably not the best choice, but at this point
|
||||||
// anything else would be an API change.
|
// anything else would be an API change.
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue