forked from hydrogen18/stalecucumber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unpack.go
352 lines (303 loc) · 8.21 KB
/
unpack.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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package stalecucumber
import "io"
import "reflect"
import "fmt"
import "errors"
import "strings"
import "math/big"
import "bytes"
const PICKLE_TAG = "pickle"
type UnpackingError struct {
Source interface{}
Destination reflect.Value
Err error
}
/*
This type is returned when a call to From() fails.
Setting "AllowMissingFields" and "AllowMismatchedFields"
on the result of "UnpackInto" controls if this error is
returned or not.
*/
func (ue UnpackingError) Error() string {
var dv string
var dt string
k := ue.Destination.Kind()
switch k {
case reflect.Ptr:
dt = fmt.Sprintf("%s", ue.Destination.Type().Elem())
if !ue.Destination.IsNil() {
dv = fmt.Sprintf("%v", ue.Destination.Elem().Interface())
} else {
dv = "nil"
}
case reflect.Invalid:
dv = "invalid"
dt = dv
default:
dv = fmt.Sprintf("%v", ue.Destination.Interface())
dt = fmt.Sprintf("%s", ue.Destination.Type())
}
return fmt.Sprintf("Error unpacking %v(%T) into %s(%s):%v",
ue.Source,
ue.Source,
dv,
dt,
ue.Err)
}
var ErrNilPointer = errors.New("Destination cannot be a nil pointer")
var ErrNotPointer = errors.New("Destination must be a pointer type")
var ErrTargetTypeNotPointer = errors.New("Target type must be a pointer to unpack this value")
var ErrTargetTypeOverflow = errors.New("Value overflows target type")
var ErrTargetTypeMismatch = errors.New("Target type does not match source type")
type unpacker struct {
dest reflect.Value
AllowMissingFields bool
AllowMismatchedFields bool
}
func UnpackInto(dest interface{}) unpacker {
return unpacker{dest: reflect.ValueOf(dest),
AllowMissingFields: true,
AllowMismatchedFields: false}
}
func (u unpacker) From(srcI interface{}, err error) error {
//Check if an error occurred
if err != nil {
return err
}
return u.from(srcI)
}
func (u unpacker) from(srcI interface{}) error {
//Get the value of the destination
v := u.dest
//The destination must always be a pointer
if v.Kind() != reflect.Ptr {
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: ErrNotPointer}
}
//The destination can never be nil
if v.IsNil() {
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: ErrNilPointer}
}
//Indirect the destination. This gets the actual
//value pointed at
vIndirect := v
for vIndirect.Kind() == reflect.Ptr {
if vIndirect.IsNil() {
vIndirect.Set(reflect.New(vIndirect.Type().Elem()))
}
vIndirect = vIndirect.Elem()
}
//Check the input against known types
switch s := srcI.(type) {
default:
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: errors.New("Unknown source type")}
case PickleNone:
vElem := v.Elem()
for vElem.Kind() == reflect.Ptr {
next := vElem.Elem()
if next.Kind() == reflect.Ptr {
vElem = next
continue
}
if vElem.CanSet() {
vElem.Set(reflect.Zero(vElem.Type()))
return nil
}
}
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: ErrTargetTypeNotPointer}
case int64:
switch vIndirect.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int64, reflect.Int32:
if vIndirect.OverflowInt(s) {
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: ErrTargetTypeOverflow}
}
vIndirect.SetInt(s)
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if s < 0 || vIndirect.OverflowUint(uint64(s)) {
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: ErrTargetTypeOverflow}
}
vIndirect.SetUint(uint64(s))
return nil
}
dstBig, ok := vIndirect.Addr().Interface().(*big.Int)
if ok {
dstBig.SetInt64(s)
return nil
}
case string:
switch vIndirect.Kind() {
case reflect.String:
vIndirect.SetString(s)
return nil
}
case bool:
switch vIndirect.Kind() {
case reflect.Bool:
vIndirect.SetBool(s)
return nil
}
case float64:
switch vIndirect.Kind() {
case reflect.Float32, reflect.Float64:
vIndirect.SetFloat(s)
return nil
}
case *big.Int:
dstBig, ok := vIndirect.Addr().Interface().(*big.Int)
if ok {
dstBig.Set(s)
return nil
}
if vi, err := Int(srcI, nil); err == nil {
return unpacker{dest: v,
AllowMismatchedFields: u.AllowMismatchedFields,
AllowMissingFields: u.AllowMissingFields}.From(vi, nil)
}
case io.Reader:
var readerType = reflect.TypeOf((*io.Reader)(nil)).Elem()
// Check for exact match
if vIndirect.Kind() == reflect.Interface && vIndirect.Type().Implements(readerType) {
vIndirect.Set(reflect.ValueOf(s))
return nil
}
// Handle converting io.Reader to byte buffer if the caller passes that in
var byteBufferType = reflect.TypeOf((*bytes.Buffer)(nil)).Elem()
if vIndirect.Type() == byteBufferType {
buf := &bytes.Buffer{}
_, err := io.Copy(buf, s)
if err != nil {
return err
}
vIndirect.Set(reflect.ValueOf(*buf))
return nil
}
case []interface{}:
//Check that the destination is a slice
if vIndirect.Kind() != reflect.Slice {
return UnpackingError{Source: s,
Destination: u.dest,
Err: fmt.Errorf("Cannot unpack slice into destination")}
}
//Check for exact type match
if vIndirect.Type().Elem().Kind() == reflect.Interface {
vIndirect.Set(reflect.ValueOf(s))
return nil
}
//Build the value using reflection
var replacement reflect.Value
if vIndirect.IsNil() || vIndirect.Len() < len(s) {
replacement = reflect.MakeSlice(vIndirect.Type(),
len(s), len(s))
} else {
replacement = vIndirect.Slice(0, len(s))
}
for i, srcV := range s {
dstV := replacement.Index(i)
//Recurse to set the value
err := unpacker{dest: dstV.Addr(),
AllowMissingFields: u.AllowMissingFields,
AllowMismatchedFields: u.AllowMismatchedFields}.
From(srcV, nil)
if err != nil {
return err
}
}
vIndirect.Set(replacement)
return nil
case map[interface{}]interface{}:
//Check to see if the field is exactly
//of the type
if vIndirect.Kind() == reflect.Map {
dstT := vIndirect.Type()
if dstT.Key().Kind() == reflect.Interface &&
dstT.Elem().Kind() == reflect.Interface {
vIndirect.Set(reflect.ValueOf(s))
return nil
}
}
var src map[string]interface{}
var err error
src, err = DictString(srcI, err)
if err != nil {
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: fmt.Errorf("Cannot unpack source into struct")}
}
if vIndirect.Kind() != reflect.Struct {
return UnpackingError{Source: src,
Destination: u.dest,
Err: fmt.Errorf("Cannot unpack into %v", v.Kind().String())}
}
var fieldByTag map[string]int
vIndirectType := reflect.TypeOf(vIndirect.Interface())
numFields := vIndirectType.NumField()
for i := 0; i != numFields; i++ {
fv := vIndirectType.Field(i)
tag := fv.Tag.Get(PICKLE_TAG)
if len(tag) != 0 {
if fieldByTag == nil {
fieldByTag = make(map[string]int)
}
fieldByTag[tag] = i
}
}
for k, kv := range src {
var fv reflect.Value
if fieldIndex, ok := fieldByTag[k]; ok {
fv = vIndirect.Field(fieldIndex)
} else {
//Try the name verbatim. This catches
//embedded fields as well
fv = vIndirect.FieldByName(k)
if !fv.IsValid() {
//Capitalize the first character. Structs
//do not export fields with a lower case
//first character
capk := strings.ToUpper(k[0:1]) + k[1:]
fv = vIndirect.FieldByName(capk)
}
}
if !fv.IsValid() || !fv.CanSet() {
if !u.AllowMissingFields {
return UnpackingError{Source: src,
Destination: u.dest,
Err: fmt.Errorf("Cannot find field for key %q", k)}
}
continue
}
err := unpacker{dest: fv.Addr(),
AllowMismatchedFields: u.AllowMismatchedFields,
AllowMissingFields: u.AllowMissingFields}.from(kv)
if err != nil {
if u.AllowMismatchedFields {
if unpackingError, ok := err.(UnpackingError); ok {
switch unpackingError.Err {
case ErrTargetTypeOverflow,
ErrTargetTypeNotPointer,
ErrTargetTypeMismatch:
fv.Set(reflect.Zero(fv.Type()))
continue
}
}
}
return err
}
}
return nil
}
return UnpackingError{Source: srcI,
Destination: u.dest,
Err: ErrTargetTypeMismatch}
}