diff --git a/cast.go b/cast.go index 54737a7..10ab9b3 100644 --- a/cast.go +++ b/cast.go @@ -169,6 +169,12 @@ func ToIntSlice(i interface{}) []int { return v } +// ToUintSlice casts an interface to a []uint type. +func ToUintSlice(i interface{}) []uint { + v, _ := ToUintSliceE(i) + return v +} + // ToFloat64Slice casts an interface to a []float64 type. func ToFloat64Slice(i interface{}) []float64 { v, _ := ToFloat64SliceE(i) diff --git a/cast_test.go b/cast_test.go index 4035b0e..134ba73 100644 --- a/cast_test.go +++ b/cast_test.go @@ -693,6 +693,9 @@ func TestToFloat64SliceE(t *testing.T) { {[]string{"1.2", "3.2"}, []float64{1.2, 3.2}, false}, {[2]string{"2", "3"}, []float64{2, 3}, false}, {[2]string{"1.2", "3.2"}, []float64{1.2, 3.2}, false}, + {[]int32{1, 3}, []float64{1.0, 3.0}, false}, + {[]int64{1, 3}, []float64{1.0, 3.0}, false}, + {[]bool{true, false}, []float64{1.0, 0.0}, false}, // errors {nil, nil, true}, {testing.T{}, nil, true}, @@ -717,6 +720,47 @@ func TestToFloat64SliceE(t *testing.T) { } } +func TestToUintSliceE(t *testing.T) { + c := qt.New(t) + + tests := []struct { + input interface{} + expect []uint + iserr bool + }{ + {[]uint{1, 3}, []uint{1, 3}, false}, + {[]interface{}{1, 3}, []uint{1, 3}, false}, + {[]string{"2", "3"}, []uint{2, 3}, false}, + {[]int{1, 3}, []uint{1, 3}, false}, + {[]int32{1, 3}, []uint{1, 3}, false}, + {[]int64{1, 3}, []uint{1, 3}, false}, + {[]float32{1.0, 3.0}, []uint{1, 3}, false}, + {[]float64{1.0, 3.0}, []uint{1, 3}, false}, + {[]bool{true, false}, []uint{1, 0}, false}, + // errors + {nil, nil, true}, + {testing.T{}, nil, true}, + {[]string{"foo", "bar"}, nil, true}, + } + + for i, test := range tests { + errmsg := qt.Commentf("i = %d", i) // assert helper message + + v, err := ToUintSliceE(test.input) + if test.iserr { + c.Assert(err, qt.IsNotNil) + continue + } + + c.Assert(err, qt.IsNil) + c.Assert(v, qt.DeepEquals, test.expect, errmsg) + + // Non-E test + v = ToUintSlice(test.input) + c.Assert(v, qt.DeepEquals, test.expect, errmsg) + } +} + func TestToSliceE(t *testing.T) { c := qt.New(t) diff --git a/caste.go b/caste.go index 7311418..0aee9f4 100644 --- a/caste.go +++ b/caste.go @@ -615,9 +615,6 @@ func ToUint64E(i interface{}) (uint64, error) { case string: v, err := strconv.ParseUint(trimZeroDecimal(s), 0, 0) if err == nil { - if v < 0 { - return 0, errNegativeNotAllowed - } return v, nil } return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i) @@ -1329,6 +1326,11 @@ func ToIntSliceE(i interface{}) ([]int, error) { return toSliceE(i, ToIntE) } +// ToUintSliceE casts an interface to a []uint type. +func ToUintSliceE(i interface{}) ([]uint, error) { + return toSliceE(i, ToUintE) +} + // ToFloat64SliceE casts an interface to a []float64 type. func ToFloat64SliceE(i interface{}) ([]float64, error) { return toSliceE(i, ToFloat64E)