Passed
Pull Request — master (#83)
by ertugrul
02:10
created

internal/uint32-completed.go   A

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 50
dl 0
loc 73
rs 10
c 0
b 0
f 0

6 Methods

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