-
Notifications
You must be signed in to change notification settings - Fork 0
/
primitiveDecoders.go
104 lines (87 loc) · 2.3 KB
/
primitiveDecoders.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package confiq
import (
"errors"
"fmt"
"reflect"
"strconv"
)
var (
errCannotParseBool = errors.New("cannot parse bool")
errCannotParseFloat = errors.New("cannot parse float")
errCannotParseInt = errors.New("cannot parse int")
errCannotParseUint = errors.New("cannot parse uint")
)
func decodeString(targetValue reflect.Value, sourceValue any) error {
targetValue.SetString(castToString(sourceValue))
return nil
}
func decodeBool(targetValue reflect.Value, sourceValue any) error {
if boolValue, ok := sourceValue.(bool); ok {
targetValue.SetBool(boolValue)
return nil
} else {
parsedBool, err := strconv.ParseBool(castToString(sourceValue))
if err != nil {
return fmt.Errorf("%w: %w", errCannotParseBool, err)
}
targetValue.SetBool(parsedBool)
}
return nil
}
func decodeFloat(targetValue reflect.Value, sourceValue any) error {
switch sV := sourceValue.(type) {
case float32:
targetValue.SetFloat(float64(sV))
case float64:
targetValue.SetFloat(sV)
default:
parsedFloat, err := strconv.ParseFloat(castToString(sourceValue), targetValue.Type().Bits())
if err != nil {
return fmt.Errorf("%w: %w", errCannotParseFloat, err)
}
targetValue.SetFloat(parsedFloat)
}
return nil
}
func decodeInt(targetValue reflect.Value, sourceValue any) error {
switch sV := sourceValue.(type) {
case int:
targetValue.SetInt(int64(sV))
case int8:
targetValue.SetInt(int64(sV))
case int16:
targetValue.SetInt(int64(sV))
case int32:
targetValue.SetInt(int64(sV))
case int64:
targetValue.SetInt(sV)
default:
parsedInt, err := strconv.ParseInt(castToString(sourceValue), 0, targetValue.Type().Bits())
if err != nil {
return fmt.Errorf("%w: %w", errCannotParseInt, err)
}
targetValue.SetInt(parsedInt)
}
return nil
}
func decodeUint(targetValue reflect.Value, sourceValue any) error {
switch sV := sourceValue.(type) {
case uint:
targetValue.SetUint(uint64(sV))
case uint8:
targetValue.SetUint(uint64(sV))
case uint16:
targetValue.SetUint(uint64(sV))
case uint32:
targetValue.SetUint(uint64(sV))
case uint64:
targetValue.SetUint(sV)
default:
parsedUint, err := strconv.ParseUint(castToString(sourceValue), 0, targetValue.Type().Bits())
if err != nil {
return fmt.Errorf("%w: %w", errCannotParseUint, err)
}
targetValue.SetUint(parsedUint)
}
return nil
}