forked from elastic/go-structform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fold_user.go
56 lines (45 loc) · 1.31 KB
/
fold_user.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
package gotype
import (
"errors"
"fmt"
"reflect"
"unsafe"
structform "github.com/urso/go-structform"
stunsafe "github.com/urso/go-structform/internal/unsafe"
)
type userFoldFn func(unsafe.Pointer, structform.ExtVisitor) error
func makeUserFoldFn(fn reflect.Value) (userFoldFn, error) {
t := fn.Type()
if fn.Kind() != reflect.Func {
return nil, errors.New("function type required")
}
if t.NumIn() != 2 {
return nil, fmt.Errorf("function '%v' must accept 2 arguments", t.Name())
}
if t.NumOut() != 1 || t.Out(0) != tError {
return nil, fmt.Errorf("function '%v' does not return errors", t.Name())
}
ta0 := t.In(0)
if ta0.Kind() != reflect.Ptr {
return nil, fmt.Errorf("first argument in function '%v' must be a pointer", t.Name())
}
ta1 := t.In(1)
if ta1 != tExtVisitor {
return nil, fmt.Errorf("second arument in function '%v' must be structform.ExtVisitor", t.Name())
}
fptr := *((*userFoldFn)(stunsafe.UnsafeFnPtr(fn)))
return fptr, nil
}
func liftUserPtrFn(f userFoldFn) reFoldFn {
return func(c *foldContext, v reflect.Value) error {
if v.IsNil() {
return f(nil, c.visitor)
}
return f(stunsafe.ReflValuePtr(v.Elem()), c.visitor)
}
}
func liftUserValueFn(f userFoldFn) reFoldFn {
return func(c *foldContext, v reflect.Value) error {
return f(stunsafe.ReflValuePtr(v), c.visitor)
}
}