-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoder.go
More file actions
248 lines (208 loc) · 5.54 KB
/
decoder.go
File metadata and controls
248 lines (208 loc) · 5.54 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package csvx
import (
"encoding"
"fmt"
"reflect"
"strconv"
"strings"
)
type CustomDecoderFunc func(val string) (interface{}, error)
type Decoder struct {
FieldsMap map[string]int
NullText string
BoolTrueText, BoolFalseText []string
CustomDecoderMap map[string]CustomDecoderFunc
}
func NewDecoder(fields []string) *Decoder {
fieldsMap := make(map[string]int)
for i, field := range fields {
fieldsMap[field] = i
}
return &Decoder{
FieldsMap: fieldsMap,
NullText: "null",
BoolTrueText: []string{"true", "yes", "1", "1.0"},
BoolFalseText: []string{"false", "no", "0", "0.0"},
}
}
func (d *Decoder) Decode(values []string, target interface{}) error {
// check target is a non-nil pointer
rv := reflect.ValueOf(target)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return fmt.Errorf("csvx: unmarshal target must be a non-nil pointer, but got %s", rv.Type())
}
if len(values) != len(d.FieldsMap) {
return fmt.Errorf("csvx: amount of fields (%d) does not match amount of values passed in (%d)", len(d.FieldsMap), len(values))
}
onFieldFound := func(fieldCsvTag string, field reflect.Value) error {
isPtr := field.Kind() == reflect.Pointer
fieldIdx, ok := d.FieldsMap[fieldCsvTag]
if !ok {
return fmt.Errorf("csvx: field not found: %q", fieldCsvTag)
}
valueStr := values[fieldIdx]
err := d.setField(fieldCsvTag, field, field.Kind(), valueStr, isPtr)
if err != nil {
return err
}
return nil
}
err := traverseFields(target, true, onFieldFound)
if err != nil {
return err
}
return nil
}
func (d *Decoder) setField(fieldCsvTag string, field reflect.Value, fieldKind reflect.Kind, valueStr string, isPtr bool) error {
if !field.CanSet() {
return fmt.Errorf("cannot set field: %q", field.Type().Name())
}
if d.CustomDecoderMap != nil {
fn, ok := d.CustomDecoderMap[fieldCsvTag]
if ok {
val, err := fn(valueStr)
if err != nil {
return err
}
field.Set(reflect.ValueOf(val))
return nil
}
}
switch fieldKind {
case reflect.String:
if isPtr {
field.Set(reflect.ValueOf(&valueStr))
} else {
field.SetString(valueStr)
}
case reflect.Int:
val, err := strconv.Atoi(valueStr)
if err != nil {
return err
}
if isPtr {
field.Set(reflect.ValueOf(&val))
} else {
field.SetInt(int64(val))
}
case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
bitSize, err := bitSizeFromKind(fieldKind)
if err != nil {
return err
}
val, err := strconv.ParseInt(valueStr, 10, bitSize)
if err != nil {
return err
}
if isPtr {
field.Set(reflect.ValueOf(&val))
} else {
field.SetInt(int64(val))
}
case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8:
bitSize, err := bitSizeFromKind(fieldKind)
if err != nil {
return err
}
val, err := strconv.ParseUint(valueStr, 10, bitSize)
if err != nil {
return err
}
if isPtr {
field.Set(reflect.ValueOf(&val))
} else {
field.SetUint(val)
}
case reflect.Float64, reflect.Float32:
bitSize, err := bitSizeFromKind(fieldKind)
if err != nil {
return err
}
val, err := strconv.ParseFloat(valueStr, bitSize)
if err != nil {
return err
}
if isPtr {
field.Set(reflect.ValueOf(&val))
} else {
field.SetFloat(val)
}
case reflect.Bool:
val, err := d.boolValueFromStr(valueStr)
if err != nil {
return err
}
if isPtr {
field.Set(reflect.ValueOf(&val))
} else {
field.SetBool(val)
}
case reflect.Pointer:
if valueStr == "" || valueStr == d.NullText {
// leave field nil
return nil
}
err := d.setField(fieldCsvTag, field, field.Type().Elem().Kind(), valueStr, true)
if err != nil {
return err
}
case reflect.Struct:
val := field.Interface()
var isUsingPtrType bool
v, ok := val.(encoding.TextUnmarshaler)
if !ok {
// see if encoding.TextUnmarshaler is implemented on the pointer type of this struct. If it is, use that.
valPtr := reflect.New(reflect.Indirect(reflect.ValueOf(val)).Type()).Interface()
v, ok = valPtr.(encoding.TextUnmarshaler)
if !ok {
return fmt.Errorf("decoding not implemented for kind %q (type: %s). Encoding.TextUnmarshaler not implemented, implement it to unmarshal this field", fieldKind, field.Type().String())
}
isUsingPtrType = true
}
err := v.UnmarshalText([]byte(valueStr))
if err != nil {
return err
}
// get the reflect.Value to set on the field. If we have used a pointer type, extract the plain struct type from that.
objToSet := reflect.ValueOf(v)
if isUsingPtrType {
objToSet = objToSet.Elem()
}
field.Set(objToSet)
return nil
default:
return fmt.Errorf("field type not implemented: %s", fieldKind)
}
return nil
}
func (d *Decoder) boolValueFromStr(valueStr string) (bool, error) {
valToLower := strings.ToLower(valueStr)
if stringSliceContains(d.BoolTrueText, valToLower) {
return true, nil
}
if stringSliceContains(d.BoolFalseText, valToLower) {
return false, nil
}
return false, fmt.Errorf("couldn't understand value that should be a boolean field")
}
func bitSizeFromKind(kind reflect.Kind) (int, error) {
switch kind {
case reflect.Int64, reflect.Uint64, reflect.Float64:
return 64, nil
case reflect.Int32, reflect.Uint32, reflect.Float32:
return 32, nil
case reflect.Int16, reflect.Uint16:
return 16, nil
case reflect.Int8, reflect.Uint8:
return 8, nil
}
return 0, fmt.Errorf("kind not handled: %s", kind)
}
func stringSliceContains(searchingIn []string, lookingFor string) bool {
for _, item := range searchingIn {
if item == lookingFor {
return true
}
}
return false
}