Skip to content

Commit

Permalink
Marshal and unmarshal from [big]int <-> string
Browse files Browse the repository at this point in the history
  • Loading branch information
purohit committed Jan 20, 2015
1 parent 9b1007c commit 7e9cdd5
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
16 changes: 16 additions & 0 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"math/big"
"net"
"reflect"
"strconv"
"time"

"speter.net/go/exp/math/dec/inf"
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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)
Expand Down
40 changes: 40 additions & 0 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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"),
Expand Down

0 comments on commit 7e9cdd5

Please sign in to comment.