forked from ungerik/go-start
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.go
566 lines (497 loc) · 14.3 KB
/
functions.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
package reflection
import (
"fmt"
"reflect"
"strconv"
"unicode"
// "github.com/ungerik/go-start/debug"
)
// Built-in types
var (
// TypeOfError is the built-in error type
TypeOfError = reflect.TypeOf((*error)(nil)).Elem()
// TypeOfInterface is the type of an empty interface{}
TypeOfInterface = reflect.TypeOf((*interface{})(nil)).Elem()
)
func GenericSlice(sliceOrArray interface{}) []interface{} {
v := reflect.ValueOf(sliceOrArray)
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
panic(fmt.Errorf("Expected slice or array, got %T", sliceOrArray))
}
l := v.Len()
result := make([]interface{}, l)
for i := 0; i < l; i++ {
result[i] = v.Index(i).Interface()
}
return result
}
/*
DereferenceValue recursively dereferences v if it is a pointer or interface.
It will return ok == false if nil is encountered.
*/
func DereferenceValue(v reflect.Value) (result reflect.Value, ok bool) {
k := v.Kind()
if k == reflect.Ptr || k == reflect.Interface {
if v.IsNil() {
return v, false
} else {
return DereferenceValue(v.Elem())
}
}
return v, true
}
type MatchStructFieldFunc func(field *reflect.StructField) bool
func FindFlattenedStructField(t reflect.Type, matchFunc MatchStructFieldFunc) *reflect.StructField {
fieldCount := t.NumField()
for i := 0; i < fieldCount; i++ {
field := t.Field(i)
if IsExportedField(field) {
if field.Anonymous {
if field.Type.Kind() == reflect.Struct {
result := FindFlattenedStructField(field.Type, matchFunc)
if result != nil {
return result
}
}
} else {
if matchFunc(&field) {
return &field
}
}
}
}
return nil
}
/*
ExportedStructFields returns a map from exported struct field names to values,
inlining anonymous sub-structs so that their field names are available
at the base level.
Example:
type A struct {
X int
}
type B Struct {
A
Y int
}
// Yields X and Y instead of A and Y:
InlineAnonymousStructFields(reflect.ValueOf(B{}))
*/
func ExportedStructFields(v reflect.Value) map[string]reflect.Value {
t := v.Type()
if t.Kind() != reflect.Struct {
panic(fmt.Errorf("Expected a struct, got %s", t))
}
result := make(map[string]reflect.Value)
exportedStructFields(v, t, result)
return result
}
func exportedStructFields(v reflect.Value, t reflect.Type, result map[string]reflect.Value) {
for i := 0; i < t.NumField(); i++ {
structField := t.Field(i)
if IsExportedField(structField) {
if structField.Anonymous && structField.Type.Kind() == reflect.Struct {
exportedStructFields(v.Field(i), structField.Type, result)
} else {
result[structField.Name] = v.Field(i)
}
}
}
}
// Creates a new zero valued instance of prototype
func NewInstance(prototype interface{}) interface{} {
t := reflect.TypeOf(prototype)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return reflect.New(t).Interface()
}
// func CallMethod(object interface{}, method string, args ...interface{}) (results []interface{}, err error) {
// m := reflect.ValueOf(object).MethodByName(method)
// if !m.IsValid() {
// return nil, fmt.Errorf("%T has no method %s", object, method)
// }
// a := make([]reflect.Value, len(args))
// for i, arg := range args {
// a[i] = reflect.ValueOf(arg)
// }
// defer func() {
// if r := recover(); r != nil {
// err = errs.Format("utils.CallMethod() recovered from: %v", r)
// }
// }()
// r := m.Call(a)
// results = make([]interface{}, len(r))
// for i, result := range r {
// results[i] = result.Interface()
// }
// return results, nil
// }
// func CallMethod1(object interface{}, method string, args ...interface{}) (result interface{}, err error) {
// results, err := CallMethod(object, method, args...)
// if err != nil {
// return
// }
// if len(results) != 1 {
// return nil, fmt.Errorf("One result expected from method %s of %T, %d returned", method, object, len(results))
// }
// return results[0], nil
// }
func IsDefaultValue(value interface{}) bool {
if value == nil {
return true
}
switch v := reflect.ValueOf(value); v.Kind() {
case reflect.String:
return v.Len() == 0
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Bool:
return v.Bool() == false
case reflect.Ptr, reflect.Chan, reflect.Func, reflect.Interface, reflect.Slice, reflect.Map:
return v.IsNil()
case reflect.Struct:
return reflect.DeepEqual(value, reflect.Zero(v.Type()).Interface())
}
panic(fmt.Errorf("Unknown value kind %T", value))
}
// IsNilOrWrappedNil returns if i is nil, or wraps a nil pointer
// in a non nil interface.
func IsNilOrWrappedNil(i interface{}) bool {
if i == nil {
return true
}
switch v := reflect.ValueOf(i); v.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Slice:
return v.IsNil()
case reflect.Ptr, reflect.Interface:
return v.IsNil() || IsNilOrWrappedNil(v.Elem().Interface())
}
return false
}
// GetStruct returns reflect.Value for the struct found in s.
// s can be a struct, a struct pointer or a reflect.Value of
// a struct or struct pointer.
func GetStruct(s interface{}) reflect.Value {
v, ok := s.(reflect.Value)
if !ok {
v = reflect.ValueOf(s)
}
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
return v
}
func IsExportedName(name string) bool {
return name != "" && unicode.IsUpper(rune(name[0]))
}
func IsExportedField(structField reflect.StructField) bool {
return structField.PkgPath == ""
}
// CopyExportedStructFields copies all exported struct fields from src
// that are assignable to their name siblings at dstPtr to dstPtr.
// src can be a struct or a pointer to a struct, dstPtr must be
// a pointer to a struct.
func CopyExportedStructFields(src, dstPtr interface{}) (copied int) {
vsrc := reflect.ValueOf(src)
if vsrc.Kind() == reflect.Ptr {
vsrc = vsrc.Elem()
}
vdst := reflect.ValueOf(dstPtr).Elem()
return CopyExportedStructFieldsVal(vsrc, vdst)
}
func CopyExportedStructFieldsVal(src, dst reflect.Value) (copied int) {
if src.Kind() != reflect.Struct {
panic(fmt.Errorf("CopyExportedStructFieldsVal: src must be struct, got %s", src.Type()))
}
if dst.Kind() != reflect.Struct {
panic(fmt.Errorf("CopyExportedStructFieldsVal: dst must be struct, got %s", dst.Type()))
}
if !dst.CanSet() {
panic(fmt.Errorf("CopyExportedStructFieldsVal: dst (%s) is not set-able", dst.Type()))
}
srcFields := ExportedStructFields(src)
dstFields := ExportedStructFields(dst)
for name, srcV := range srcFields {
if dstV, ok := dstFields[name]; ok {
if srcV.Type().AssignableTo(dstV.Type()) {
dstV.Set(srcV)
copied++
}
}
}
return copied
}
func StringToValueOfType(s string, t reflect.Type) (interface{}, error) {
switch t.Kind() {
case reflect.String:
return s, nil
case reflect.Bool:
b, err := strconv.ParseBool(s)
if err != nil {
return nil, err
}
return b, nil
case reflect.Float32:
f, err := strconv.ParseFloat(s, 32)
if err != nil {
return nil, err
}
return float32(f), nil
case reflect.Float64:
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, err
}
return f, nil
case reflect.Int:
i, err := strconv.ParseInt(s, 0, 0)
if err != nil {
return nil, err
}
return int(i), nil
case reflect.Int8:
i, err := strconv.ParseInt(s, 0, 8)
if err != nil {
return nil, err
}
return int8(i), nil
case reflect.Int16:
i, err := strconv.ParseInt(s, 0, 16)
if err != nil {
return nil, err
}
return int16(i), nil
case reflect.Int32:
i, err := strconv.ParseInt(s, 0, 32)
if err != nil {
return nil, err
}
return int32(i), nil
case reflect.Int64:
i, err := strconv.ParseInt(s, 0, 64)
if err != nil {
return nil, err
}
return int64(i), nil
case reflect.Uint:
i, err := strconv.ParseUint(s, 0, 0)
if err != nil {
return nil, err
}
return uint(i), nil
case reflect.Uint8:
i, err := strconv.ParseUint(s, 0, 8)
if err != nil {
return nil, err
}
return uint8(i), nil
case reflect.Uint16:
i, err := strconv.ParseUint(s, 0, 16)
if err != nil {
return nil, err
}
return uint16(i), nil
case reflect.Uint32:
i, err := strconv.ParseUint(s, 0, 32)
if err != nil {
return nil, err
}
return uint32(i), nil
case reflect.Uint64:
i, err := strconv.ParseUint(s, 0, 64)
if err != nil {
return nil, err
}
return uint64(i), nil
}
return nil, fmt.Errorf("StringToValueOfType: can't convert string to type %s", t)
}
func CanStringToValueOfType(t reflect.Type) bool {
switch t.Kind() {
case reflect.String,
reflect.Bool,
reflect.Float32,
reflect.Float64,
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
return true
}
return false
}
// SetStructZero sets all elements of a struct to their zero values.
func SetStructZero(structVal reflect.Value) {
t := structVal.Type()
for i := 0; i < t.NumField(); i++ {
if IsExportedField(t.Field(i)) {
elem := structVal.Field(i)
if elem.Kind() == reflect.Struct {
SetStructZero(elem)
} else {
elem.Set(reflect.Zero(elem.Type()))
}
}
}
}
// Reset sets all elements of the object pointed to
// by resultRef to their default or zero values.
// But it works different from simply zeroing out everything,
// here are the exceptions:
// If resultRef is a pointer to a pointer, then
// the pointed to pointer will be reset to a new instance
// If resultRef is a pointer to a map, then the map
// will be reset to a new empty one.
// All other types pointed to by resultRef will be set
// to their default zero values.
func Reset(resultRef interface{}) {
ptr := reflect.ValueOf(resultRef)
if ptr.Kind() != reflect.Ptr {
panic(fmt.Errorf("reflection.Reset(): resultRef must be a pointer, got %T", resultRef))
}
val := ptr.Elem()
switch val.Kind() {
case reflect.Ptr:
// If resultRef is a pointer to a pointer,
// set the pointer to a new instance
// of the pointed to type
ptr.Set(reflect.New(val.Type().Elem()))
case reflect.Map:
// If resultRef is a pointer to a map,
// set make an empty new map
ptr.Set(reflect.MakeChan(val.Type(), 0))
case reflect.Struct:
SetStructZero(val)
default:
val.Set(reflect.Zero(val.Type()))
}
}
// SmartCopy copies struct or map fields from source
// to equally named struct or map fields of resultRef,
// by dereferencing source and resultRef if necessary
// to find a matching assignable type.
// All fields of the object referenced by resultPtr will be
// set to their default values before copying from source
// by calling Reset().
// SmartCopy is typically used for iterators with
// a method Next(resultRef interface{}) bool.
func SmartCopy(source, resultRef interface{}) {
resultRefVal := reflect.ValueOf(resultRef)
if resultRefVal.Kind() != reflect.Ptr && resultRefVal.Kind() != reflect.Map {
panic(fmt.Errorf("reflection.SmartCopy(): resultRef must be a pointer or a map, got %T", resultRef))
}
Reset(resultRef)
var resultVal reflect.Value
if resultRefVal.Kind() == reflect.Map {
resultVal = resultRefVal
} else {
resultVal = resultRefVal.Elem()
}
sourceVal := reflect.ValueOf(source)
if sourceVal.Kind() == reflect.Ptr {
sourceVal = sourceVal.Elem()
}
if !smartCopyVals(sourceVal, resultVal) {
panic(fmt.Errorf("reflection.SmartCopy(): Can't copy %T to %T", source, resultRef))
}
}
func smartCopyVals(sourceVal, resultVal reflect.Value) bool {
switch {
case sourceVal.Type().AssignableTo(resultVal.Type()):
resultVal.Set(sourceVal)
case sourceVal.Kind() == reflect.Struct && resultVal.Kind() == reflect.Struct:
CopyExportedStructFieldsVal(sourceVal, resultVal)
case sourceVal.Kind() == reflect.Ptr && sourceVal.Elem().Type().AssignableTo(resultVal.Type()):
smartCopyVals(sourceVal.Elem(), resultVal)
case sourceVal.Kind() == reflect.Map && sourceVal.Type().Key().Kind() == reflect.String &&
resultVal.Kind() == reflect.Struct:
resultMap := ExportedStructFields(resultVal)
for _, key := range sourceVal.MapKeys() {
if dst, ok := resultMap[key.String()]; ok {
src := sourceVal.MapIndex(key)
if src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
}
}
}
case sourceVal.Kind() == reflect.Struct &&
resultVal.Kind() == reflect.Map && resultVal.Type().Key().Kind() == reflect.String:
sourceMap := ExportedStructFields(sourceVal)
for key, src := range sourceMap {
dst := resultVal.MapIndex(reflect.ValueOf(key))
if dst.IsValid() && src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
}
}
case sourceVal.Kind() == reflect.Map && sourceVal.Type().Key().Kind() == reflect.String &&
resultVal.Kind() == reflect.Map && resultVal.Type().Key().Kind() == reflect.String &&
sourceVal.Type().Elem().AssignableTo(resultVal.Type().Elem()):
for _, key := range sourceVal.MapKeys() {
if dst := resultVal.MapIndex(key); dst.IsValid() {
dst.Set(sourceVal.MapIndex(key))
}
}
default:
return false
}
return true
}
func checkFunctionSignatureNums(t reflect.Type, args, results int) error {
if t.Kind() != reflect.Func {
return fmt.Errorf("Expected a function but got a %s", t)
}
if t.NumIn() != args {
return fmt.Errorf("Expected %d function arguments, got %d", args, t.NumIn())
}
if t.NumOut() != results {
return fmt.Errorf("Expected %d function results, got %d", results, t.NumOut())
}
return nil
}
func CheckFunctionSignature(f interface{}, args, results []reflect.Type) error {
t := reflect.TypeOf(f)
err := checkFunctionSignatureNums(t, len(args), len(results))
if err != nil {
return err
}
for i := range args {
if args[i] != t.In(i) {
return fmt.Errorf("Function argument %d must be %s, got %s", i, args[i], t.In(i))
}
}
for i := range results {
if results[i] != t.Out(i) {
return fmt.Errorf("Function result %d must be %s, got %s", i, results[i], t.Out(i))
}
}
return nil
}
func CheckFunctionSignatureKind(f interface{}, args, results []reflect.Kind) error {
t := reflect.TypeOf(f)
err := checkFunctionSignatureNums(t, len(args), len(results))
if err != nil {
return err
}
for i := range args {
if args[i] != t.In(i).Kind() {
return fmt.Errorf("Function argument %d must be %s kind, got %s kind", i, args[i], t.In(i).Kind())
}
}
for i := range results {
if results[i] != t.Out(i).Kind() {
return fmt.Errorf("Function result %d must be %s kind, got %s kind", i, results[i], t.Out(i).Kind())
}
}
return nil
}