Passed
Pull Request — master (#66)
by Hayrullah
56s
created

internal.ToInt8   B

Complexity

Conditions 7

Size

Total Lines 15
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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