forked from rainycape/gondola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
methods_unsafe.go
77 lines (67 loc) · 1.7 KB
/
methods_unsafe.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
// +build !appengine
package driver
import (
"reflect"
"unsafe"
)
type method func(uintptr) error
type Methods struct {
// The address for the Load method. 0 if there's no Load method
LoadPointer unsafe.Pointer
// Wheter Load returns an error
LoadReturns bool
// The address for the Save method. 0 if there's no Save method
SavePointer unsafe.Pointer
// Wheter Save returns an error
SaveReturns bool
}
func (m *Methods) Load(obj interface{}) error {
return m.method(m.LoadPointer, m.LoadReturns, obj)
}
func (m *Methods) Save(obj interface{}) error {
return m.method(m.SavePointer, m.SaveReturns, obj)
}
func (m *Methods) method(p unsafe.Pointer, ret bool, obj interface{}) error {
if p != nil {
val := reflect.ValueOf(obj)
for val.Kind() == reflect.Ptr && val.Elem().Kind() == reflect.Ptr {
val = val.Elem()
}
f := *(*method)(unsafe.Pointer(&p))
if ret {
return f(val.Pointer())
}
f(val.Pointer())
}
return nil
}
func MakeMethods(typ reflect.Type) (m *Methods, err error) {
m = &Methods{}
// Get pointer methods
if typ.Kind() != reflect.Ptr {
typ = reflect.PtrTo(typ)
}
// Check for Load and Save methods
if load, ok := typ.MethodByName("Load"); ok {
if err = checkMethod(typ, load); err != nil {
return
}
m.LoadPointer = pointer(typ, load.Index)
m.LoadReturns = returns(load)
}
if save, ok := typ.MethodByName("Save"); ok {
if err = checkMethod(typ, save); err != nil {
return
}
m.SavePointer = pointer(typ, save.Index)
m.SaveReturns = returns(save)
}
return
}
func pointer(typ reflect.Type, idx int) unsafe.Pointer {
ptr := typ.Method(idx).Func.Pointer()
return unsafe.Pointer(&ptr)
}
func returns(m reflect.Method) bool {
return m.Type.NumOut() > 0
}