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