-
Notifications
You must be signed in to change notification settings - Fork 48
/
registry_impl.go
94 lines (83 loc) · 2.15 KB
/
registry_impl.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 manager
import (
"fmt"
"sync"
"github.com/xuperchain/xupercore/kernel/contract"
)
type shortcut struct {
OldMethod string
Contract string
Method string
}
type registryImpl struct {
mutex sync.Mutex
methods map[string]map[string]contract.KernMethod
shortcuts map[string]shortcut
}
func (r *registryImpl) RegisterKernMethod(ctract, method string, handler contract.KernMethod) {
r.mutex.Lock()
defer r.mutex.Unlock()
if r.methods == nil {
r.methods = make(map[string]map[string]contract.KernMethod)
}
contractMap, ok := r.methods[ctract]
if !ok {
contractMap = make(map[string]contract.KernMethod)
r.methods[ctract] = contractMap
}
_, ok = contractMap[method]
if ok {
panic(fmt.Sprintf("kernel method `%s' for `%s' exists", method, ctract))
}
contractMap[method] = handler
}
func (r *registryImpl) UnregisterKernMethod(ctract, method string) {
r.mutex.Lock()
defer r.mutex.Unlock()
if contractMap, ok := r.methods[ctract]; ok {
delete(contractMap, method)
}
}
func (r *registryImpl) RegisterShortcut(oldmethod, contract, method string) {
r.mutex.Lock()
defer r.mutex.Unlock()
if r.shortcuts == nil {
r.shortcuts = make(map[string]shortcut)
}
_, ok := r.shortcuts[oldmethod]
if ok {
panic(fmt.Sprintf("kernel method shortcut for '%s' exists", oldmethod))
}
r.shortcuts[oldmethod] = shortcut{
OldMethod: oldmethod,
Contract: contract,
Method: method,
}
}
func (r *registryImpl) getShortcut(method string) (shortcut, error) {
sc, ok := r.shortcuts[method]
if !ok {
return shortcut{}, fmt.Errorf("kernel method for `%s' not found", method)
}
return sc, nil
}
func (r *registryImpl) GetKernMethod(ctract, method string) (contract.KernMethod, error) {
r.mutex.Lock()
defer r.mutex.Unlock()
if ctract == "" {
sc, err := r.getShortcut(method)
if err != nil {
return nil, err
}
ctract, method = sc.Contract, sc.Method
}
contractMap, ok := r.methods[ctract]
if !ok {
return nil, fmt.Errorf("kernel contract '%s' not found", ctract)
}
contractMethod, ok := contractMap[method]
if !ok {
return nil, fmt.Errorf("kernel method '%s' for '%s' not exists", method, ctract)
}
return contractMethod, nil
}