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