Jelajahi Sumber

Merge pull request #525 from matope/panic-on-marshalInt

marshal: handle alias type of int correctly.
Chris Bannister 10 tahun lalu
induk
melakukan
b0afc6c193
2 mengubah file dengan 13 tambahan dan 6 penghapusan
  1. 6 6
      marshal.go
  2. 7 0
      marshal_test.go

+ 6 - 6
marshal.go

@@ -297,12 +297,7 @@ func marshalInt(info TypeInfo, value interface{}) ([]byte, error) {
 		return nil, nil
 	}
 
-	rv := reflect.ValueOf(value)
-	if rv.IsNil() {
-		return nil, nil
-	}
-
-	switch rv.Type().Kind() {
+	switch rv := reflect.ValueOf(value); rv.Type().Kind() {
 	case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
 		v := rv.Int()
 		if v > math.MaxInt32 || v < math.MinInt32 {
@@ -315,7 +310,12 @@ func marshalInt(info TypeInfo, value interface{}) ([]byte, error) {
 			return nil, marshalErrorf("marshal int: value %d out of range", v)
 		}
 		return encInt(int32(v)), nil
+	default:
+		if rv.IsNil() {
+			return nil, nil
+		}
 	}
+
 	return nil, marshalErrorf("can not marshal %T into %s", value, info)
 }
 

+ 7 - 0
marshal_test.go

@@ -15,6 +15,8 @@ import (
 	"gopkg.in/inf.v0"
 )
 
+type AliasInt int
+
 var marshalTests = []struct {
 	Info  TypeInfo
 	Data  []byte
@@ -73,6 +75,11 @@ var marshalTests = []struct {
 		[]byte("\x01\x02\x03\x04"),
 		int(16909060),
 	},
+	{
+		NativeType{proto: 2, typ: TypeInt},
+		[]byte("\x01\x02\x03\x04"),
+		AliasInt(16909060),
+	},
 	{
 		NativeType{proto: 2, typ: TypeInt},
 		[]byte("\x80\x00\x00\x00"),