Add a ToInt64() and necessary plumbing

This commit is contained in:
Matt Keller 2016-01-28 13:41:34 -05:00 committed by Bjørn Erik Pedersen
parent 7c7add0129
commit 0eed3d1b35
3 changed files with 52 additions and 0 deletions

View File

@ -27,6 +27,11 @@ func ToFloat64(i interface{}) float64 {
return v
}
func ToInt64(i interface{}) int64 {
v, _ := ToInt64E(i)
return v
}
func ToInt(i interface{}) int {
v, _ := ToIntE(i)
return v

View File

@ -23,6 +23,17 @@ func TestToInt(t *testing.T) {
assert.Equal(t, ToInt(eight), 8)
}
func TestToInt64(t *testing.T) {
var eight interface{} = 8
assert.Equal(t, ToInt64(int64(8)), int64(8))
assert.Equal(t, ToInt64(8), int64(8))
assert.Equal(t, ToInt64(8.31), int64(8))
assert.Equal(t, ToInt64("8"), int64(8))
assert.Equal(t, ToInt64(true), int64(1))
assert.Equal(t, ToInt64(false), int64(0))
assert.Equal(t, ToInt64(eight), int64(8))
}
func TestToFloat64(t *testing.T) {
var eight interface{} = 8
assert.Equal(t, ToFloat64(8), 8.00)

View File

@ -111,6 +111,42 @@ func ToFloat64E(i interface{}) (float64, error) {
}
}
// ToInt64E casts an empty interface to an int64.
func ToInt64E(i interface{}) (int64, error) {
i = indirect(i)
jww.DEBUG.Println("ToInt64E called on type:", reflect.TypeOf(i))
switch s := i.(type) {
case int64:
return s, nil
case int:
return int64(s), nil
case int32:
return int64(s), nil
case int16:
return int64(s), nil
case int8:
return int64(s), nil
case string:
v, err := strconv.ParseInt(s, 0, 0)
if err == nil {
return v, nil
}
return 0, fmt.Errorf("Unable to Cast %#v to int64", i)
case float64:
return int64(s), nil
case bool:
if bool(s) {
return int64(1), nil
}
return int64(0), nil
case nil:
return int64(0), nil
default:
return int64(0), fmt.Errorf("Unable to Cast %#v to int64", i)
}
}
// ToIntE casts an empty interface to an int.
func ToIntE(i interface{}) (int, error) {
i = indirect(i)