-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassign.go
223 lines (201 loc) · 6.19 KB
/
assign.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
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
package retable
import (
"encoding"
"errors"
"fmt"
"reflect"
"strconv"
)
// SmartAssign assigns src to dst by converting src to dst type
// as smart as possible using the passed dstScanner and srcFormatter
// to convert types from and to strings.
//
// Both dstScanner and srcFormatter can be nil.
func SmartAssign(dst, src reflect.Value, dstScanner Scanner, srcFormatter Formatter) (err error) {
if !dst.IsValid() {
return fmt.Errorf("dst value is invalid")
}
if !dst.CanSet() {
return fmt.Errorf("cannot set dst value")
}
if !src.IsValid() {
return fmt.Errorf("src value is invalid")
}
var (
srcType = src.Type()
srcKind = srcType.Kind()
dstType = dst.Type()
dstKind = dstType.Kind()
)
// Package reflect might panic in some edge cases
// like converting a slice to an array with non matching length.
// Recover and return as error instead to make code more robust.
// defer func() {
// if r := recover(); r != nil {
// err = errors.Join(err, fmt.Errorf("%+v", r))
// }
// }()
// Assign zero value in case of IsNull.
// Conversions further down might assign something
// different than the zero value dependent on the
// underlying type.
if nullable, ok := src.Interface().(interface{ IsNull() bool }); ok && nullable.IsNull() {
dst.Set(reflect.Zero(dstType))
return nil
}
// Convert assigns directly if possible
if srcType.ConvertibleTo(dstType) {
// Check because conversion can panic
if srcKind == reflect.Slice && dstKind == reflect.Pointer && dstType.Elem().Kind() == reflect.Array && dst.Elem().Len() > src.Len() {
return fmt.Errorf("cannot convert slice of length %d to array pointer with length %d", src.Len(), dst.Elem().Len())
}
dst.Set(src.Convert(dstType))
return nil
}
// Assign zero value in case of a nil pointer
if srcKind == reflect.Pointer && src.IsNil() {
dst.Set(reflect.Zero(dstType))
return nil
}
// Try formatStr if dst is a string type
if dstKind == reflect.String && srcFormatter != nil {
str, err := srcFormatter.Format(src)
if err == nil {
dst.SetString(str)
return nil
}
if !errors.Is(err, errors.ErrUnsupported) {
return err
}
// Continue after errors.ErrUnsupported
}
// Try assigning string from MarshalText method
if m, ok := src.Interface().(encoding.TextMarshaler); ok {
txt, err := m.MarshalText()
if err != nil {
return err
}
err = SmartAssign(dst, reflect.ValueOf(string(txt)), dstScanner, srcFormatter)
if !errors.Is(err, errors.ErrUnsupported) {
return err // nil or other than errors.ErrUnsupported
}
// Continue after errors.ErrUnsupported
}
// Try assigning string from String method
if m, ok := src.Interface().(fmt.Stringer); ok {
err = SmartAssign(dst, reflect.ValueOf(m.String()), dstScanner, srcFormatter)
if !errors.Is(err, errors.ErrUnsupported) {
return err // nil or other than errors.ErrUnsupported
}
// Continue after errors.ErrUnsupported
}
// Try converting string to time.Time
if srcKind == reflect.String && (dstType == typeOfTime || dstKind == reflect.Pointer && dstType.Elem() == typeOfTime) {
if t, _, err := ParseTime(src.String()); err == nil {
if dstType == typeOfTime {
dst.Set(reflect.ValueOf(t))
} else {
dst.Set(reflect.ValueOf(&t))
}
return nil
}
}
// Try assigning the dereferenced value
if srcKind == reflect.Pointer && !src.IsNil() {
err := SmartAssign(dst, src.Elem(), dstScanner, srcFormatter)
if !errors.Is(err, errors.ErrUnsupported) {
return err // nil or other than errors.ErrUnsupported
}
// Continue after errors.ErrUnsupported
}
// A pure empty struct represents the zero value
if srcType == typeOfEmptyStruct {
dst.Set(reflect.Zero(dstType))
return nil
}
// Convert bool to 0 / 1 numbers, or "true" / "false" strings
if srcKind == reflect.Bool {
switch dstKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if src.Bool() {
dst.SetInt(1)
} else {
dst.SetInt(0)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if src.Bool() {
dst.SetUint(1)
} else {
dst.SetUint(0)
}
case reflect.Float32, reflect.Float64:
if src.Bool() {
dst.SetFloat(1)
} else {
dst.SetFloat(0)
}
case reflect.String:
dst.SetString(strconv.FormatBool(src.Bool()))
}
}
switch dstKind {
// Convert 0 / 1 numbers, or "true" / "false" strings to bool
case reflect.Bool:
switch srcKind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
dst.SetBool(src.Int() != 0)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
dst.SetBool(src.Uint() != 0)
case reflect.Float32, reflect.Float64:
dst.SetBool(src.Float() != 0)
case reflect.String:
b, err := strconv.ParseBool(src.String())
if err == nil {
dst.SetBool(b)
return nil
}
}
// Convert string to integers
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if srcKind == reflect.String {
if i, e := strconv.ParseInt(src.String(), 10, 64); e == nil {
dst.SetInt(i)
return nil
}
}
// Convert string to unsigned integers
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
if srcKind == reflect.String {
if i, e := strconv.ParseUint(src.String(), 10, 64); e == nil {
dst.SetUint(i)
return nil
}
}
case reflect.Float32, reflect.Float64:
if srcKind == reflect.String {
if f, e := strconv.ParseFloat(src.String(), 64); e == nil {
dst.SetFloat(f)
return nil
}
}
// Convert any type to string with fmt.Sprint
case reflect.String:
dst.SetString(fmt.Sprint(src.Interface()))
return nil
// If all other failed and dest is a pointer,
// try to create a new instance and assign to that
// then assign the pointer to the new instance.
case reflect.Pointer:
newDest := reflect.New(dstType.Elem())
err = SmartAssign(newDest.Elem(), src, dstScanner, srcFormatter)
if err != nil && !errors.Is(err, errors.ErrUnsupported) {
return err
}
if err == nil {
dst.Set(newDest)
return nil
}
// Continue after errors.ErrUnsupported
}
return fmt.Errorf("%w: assigning %s %#v to %s", errors.ErrUnsupported, srcType, src, dstType)
}