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