Skip to content

Commit

Permalink
encoding/binary: reject types with implementation-dependent sizes
Browse files Browse the repository at this point in the history
Fixes #1201.

R=rsc
CC=golang-dev
https://golang.org/cl/3787044
  • Loading branch information
pgavlin authored and rsc committed Jan 4, 2011
1 parent 3cd10e3 commit 236f963
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/pkg/encoding/binary/binary.go
Expand Up @@ -198,6 +198,10 @@ func sizeof(v reflect.Type) int {
return sum

case *reflect.UintType, *reflect.IntType, *reflect.FloatType, *reflect.ComplexType:
switch t := t.Kind(); t {
case reflect.Int, reflect.Uint, reflect.Uintptr, reflect.Float, reflect.Complex:
return -1
}
return int(v.Size())
}
return -1
Expand Down
26 changes: 26 additions & 0 deletions src/pkg/encoding/binary/binary_test.go
Expand Up @@ -28,6 +28,15 @@ type Struct struct {
Array [4]uint8
}

type T struct {
Int int
Uint uint
Float float
Complex complex
Uintptr uintptr
Array [4]int
}

var s = Struct{
0x01,
0x0203,
Expand Down Expand Up @@ -136,3 +145,20 @@ func TestWriteSlice(t *testing.T) {
err := Write(buf, BigEndian, res)
checkResult(t, "WriteSlice", BigEndian, err, buf.Bytes(), src)
}

func TestWriteT(t *testing.T) {
buf := new(bytes.Buffer)
ts := T{}
err := Write(buf, BigEndian, ts)
if err == nil {
t.Errorf("WriteT: have nil, want non-nil")
}

tv := reflect.Indirect(reflect.NewValue(ts)).(*reflect.StructValue)
for i, n := 0, tv.NumField(); i < n; i++ {
err = Write(buf, BigEndian, tv.Field(i).Interface())
if err == nil {
t.Errorf("WriteT.%v: have nil, want non-nil", tv.Field(i).Type())
}
}
}

0 comments on commit 236f963

Please sign in to comment.