-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.go
94 lines (81 loc) · 2.33 KB
/
function.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
package go_reflect
import (
"fmt"
"reflect"
)
// CheckFunction checks if a function is valid
func CheckFunction(fn interface{}, params ...interface{}) (
*reflect.Value,
*[]reflect.Value,
error,
) {
// Get the function and its parameters
fnValue := reflect.ValueOf(fn)
paramsValues := make([]reflect.Value, len(params))
for i, param := range params {
paramsValues[i] = reflect.ValueOf(param)
}
// Check if the function is valid
if fnValue.Kind() != reflect.Func {
return nil, nil, ErrNotAFunction
}
// Check if the function has the correct number of parameters
paramsCount := len(params)
fnParamsCount := fnValue.Type().NumIn()
if paramsCount != fnParamsCount {
return nil, nil, fmt.Errorf(
ErrFunctionParameterCountMismatch,
fnParamsCount,
paramsCount,
)
}
// Check if the parameter type matches the function's parameter type
var paramType, fnParamType reflect.Type
for i, paramValue := range paramsValues {
paramType = paramValue.Type()
fnParamType = fnValue.Type().In(i)
if paramType != fnParamType {
return nil, nil, fmt.Errorf(
ErrFunctionParameterTypeMismatch,
i,
fnParamType,
paramType,
)
}
}
return &fnValue, ¶msValues, nil
}
// UnsafeCallFunction calls a function with some typed parameters without checking if the function is valid
func UnsafeCallFunction(fnValue *reflect.Value, paramsValues ...reflect.Value) (
[]interface{},
error,
) {
// Check if the function or the parameters values are nil
if fnValue == nil {
return nil, ErrNilFunctionValue
}
if paramsValues == nil {
paramsValues = make([]reflect.Value, 0)
}
// Call the function with the parameter
results := fnValue.Call(paramsValues)
// Convert the results to an interface slice
interfaceResults := make([]interface{}, len(results))
for i, result := range results {
interfaceResults[i] = result.Interface()
}
return interfaceResults, nil
}
// SafeCallFunction calls a function with some typed parameters after checking if the function is valid
func SafeCallFunction(fn interface{}, params ...interface{}) (
[]interface{},
error,
) {
// Check if the function is valid
fnValue, paramsValues, err := CheckFunction(fn, params...)
if err != nil {
return nil, err
}
// Call the function with the parameter (now, we are sure that the function is valid)
return UnsafeCallFunction(fnValue, *paramsValues...)
}