Bladeren bron

Marshal and unmarshal from [big]int <-> string

Ashwin Purohit 11 jaren geleden
bovenliggende
commit
7e9cdd5511
2 gewijzigde bestanden met toevoegingen van 56 en 0 verwijderingen
  1. 16 0
      marshal.go
  2. 40 0
      marshal_test.go

+ 16 - 0
marshal.go

@@ -12,6 +12,7 @@ import (
 	"math/big"
 	"net"
 	"reflect"
+	"strconv"
 	"time"
 
 	"speter.net/go/exp/math/dec/inf"
@@ -251,6 +252,12 @@ func marshalInt(info *TypeInfo, value interface{}) ([]byte, error) {
 		return encInt(int32(v)), nil
 	case uint8:
 		return encInt(int32(v)), nil
+	case string:
+		i, err := strconv.ParseInt(value.(string), 10, 32)
+		if err != nil {
+			return nil, marshalErrorf("can not marshal string to int: %s", err)
+		}
+		return encInt(int32(i)), nil
 	}
 	rv := reflect.ValueOf(value)
 	switch rv.Type().Kind() {
@@ -313,6 +320,12 @@ func marshalBigInt(info *TypeInfo, value interface{}) ([]byte, error) {
 		return encBigInt(int64(v)), nil
 	case big.Int:
 		return encBigInt2C(&v), nil
+	case string:
+		i, err := strconv.ParseInt(value.(string), 10, 64)
+		if err != nil {
+			return nil, marshalErrorf("can not marshal string to bigint: %s", err)
+		}
+		return encBigInt(i), nil
 	}
 	rv := reflect.ValueOf(value)
 	switch rv.Type().Kind() {
@@ -477,6 +490,9 @@ func unmarshalIntlike(info *TypeInfo, int64Val int64, data []byte, value interfa
 	case *big.Int:
 		decBigInt2C(data, v)
 		return nil
+	case *string:
+		*v = strconv.FormatInt(int64Val, 10)
+		return nil
 	}
 
 	rv := reflect.ValueOf(value)

+ 40 - 0
marshal_test.go

@@ -83,6 +83,26 @@ var marshalTests = []struct {
 		[]byte("\x7f\xff\xff\xff"),
 		int32(math.MaxInt32),
 	},
+	{
+		&TypeInfo{Type: TypeInt},
+		[]byte("\x00\x00\x00\x00"),
+		"0",
+	},
+	{
+		&TypeInfo{Type: TypeInt},
+		[]byte("\x01\x02\x03\x04"),
+		"16909060",
+	},
+	{
+		&TypeInfo{Type: TypeInt},
+		[]byte("\x80\x00\x00\x00"),
+		"-2147483648", // math.MinInt32
+	},
+	{
+		&TypeInfo{Type: TypeInt},
+		[]byte("\x7f\xff\xff\xff"),
+		"2147483647", // math.MaxInt32
+	},
 	{
 		&TypeInfo{Type: TypeBigInt},
 		[]byte("\x00\x00\x00\x00\x00\x00\x00\x00"),
@@ -103,6 +123,26 @@ var marshalTests = []struct {
 		[]byte("\x7f\xff\xff\xff\xff\xff\xff\xff"),
 		int64(math.MaxInt64),
 	},
+	{
+		&TypeInfo{Type: TypeBigInt},
+		[]byte("\x00\x00\x00\x00\x00\x00\x00\x00"),
+		"0",
+	},
+	{
+		&TypeInfo{Type: TypeBigInt},
+		[]byte("\x01\x02\x03\x04\x05\x06\x07\x08"),
+		"72623859790382856",
+	},
+	{
+		&TypeInfo{Type: TypeBigInt},
+		[]byte("\x80\x00\x00\x00\x00\x00\x00\x00"),
+		"-9223372036854775808", // math.MinInt64
+	},
+	{
+		&TypeInfo{Type: TypeBigInt},
+		[]byte("\x7f\xff\xff\xff\xff\xff\xff\xff"),
+		"9223372036854775807", // math.MaxInt64
+	},
 	{
 		&TypeInfo{Type: TypeBoolean},
 		[]byte("\x00"),