1
|
|
|
package internal |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"reflect" |
5
|
|
|
"strconv" |
6
|
|
|
|
7
|
|
|
"github.com/gotilty/gotil/math" |
8
|
|
|
|
9
|
|
|
"github.com/gotilty/gotil/internal/errs" |
10
|
|
|
) |
11
|
|
|
|
12
|
|
|
//ToUint returns uint(0) with an error if the parameter is unsupported type. |
13
|
|
|
//Just works with all primitive types. |
14
|
|
|
func ToUint(a interface{}) (uint, error) { |
15
|
|
|
val := reflect.ValueOf(a) |
16
|
|
|
switch val.Kind() { |
17
|
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
18
|
|
|
return fromInt64ToUint(val.Int()) |
19
|
|
|
case reflect.Float32, reflect.Float64: |
20
|
|
|
return fromFloat64ToUint(val.Float()) |
21
|
|
|
case reflect.String: |
22
|
|
|
return fromStringToUint(val.String()) |
23
|
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
24
|
|
|
return fromUint64ToUint(val.Uint()) |
25
|
|
|
case reflect.Bool: |
26
|
|
|
return fromBoolToUint(val.Bool()) |
27
|
|
|
default: |
28
|
|
|
if a == nil { |
29
|
|
|
return 0, nil |
30
|
|
|
} |
31
|
|
|
return 0, errs.Int64Error(val.Kind().String()) |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
func fromInt64ToUint(s int64) (uint, error) { |
36
|
|
|
var maxInt int64 = math.MaxInt |
37
|
|
|
if s > maxInt { |
38
|
|
|
return 0, errs.CustomError("The entered number cannot be greater than max int.") |
39
|
|
|
} |
40
|
|
|
return uint(s), nil |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
func fromFloat64ToUint(s float64) (uint, error) { |
44
|
|
|
var maxUint uint64 = math.MaxUint |
45
|
|
|
if s > float64(maxUint) { |
46
|
|
|
return 0, errs.CustomError("the entered number cannot be greater than max uint.") |
47
|
|
|
} |
48
|
|
|
return uint(s), nil |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
func fromStringToUint(s string) (uint, error) { |
52
|
|
|
if s == "" { |
53
|
|
|
return 0, nil |
54
|
|
|
} |
55
|
|
|
d, err := strconv.ParseUint(s, 10, 8) |
56
|
|
|
if err == nil { |
57
|
|
|
return uint(d), nil |
58
|
|
|
} |
59
|
|
|
return 0, err |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
func fromUint64ToUint(s uint64) (uint, error) { |
63
|
|
|
var maxInt uint64 = math.MaxUint |
64
|
|
|
if s > uint64(maxInt) { |
65
|
|
|
return 0, errs.CustomError("The entered number cannot be greater than max uint.") |
66
|
|
|
} |
67
|
|
|
return uint(s), nil |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
func fromBoolToUint(s bool) (uint, error) { |
71
|
|
|
if s { |
72
|
|
|
return 1, nil |
73
|
|
|
} else { |
74
|
|
|
return 0, nil |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|