forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
space.go
89 lines (73 loc) · 1.78 KB
/
space.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
package app
type ID int
// Context of a function call from proxy to app.
type Context interface {
CallerTag() string
}
// A Space contains all apps that may be available in a V2Ray runtime.
// Caller must check the availability of an app by calling HasXXX before getting its instance.
type Space interface {
HasApp(ID) bool
GetApp(ID) interface{}
}
type ForContextCreator func(Context, interface{}) interface{}
var (
metadataCache = make(map[ID]ForContextCreator)
)
func RegisterApp(id ID, creator ForContextCreator) {
// TODO: check id
metadataCache[id] = creator
}
type contextImpl struct {
callerTag string
}
func (this *contextImpl) CallerTag() string {
return this.callerTag
}
type spaceImpl struct {
cache map[ID]interface{}
tag string
}
func newSpaceImpl(tag string, cache map[ID]interface{}) *spaceImpl {
space := &spaceImpl{
tag: tag,
cache: make(map[ID]interface{}),
}
context := &contextImpl{
callerTag: tag,
}
for id, object := range cache {
creator, found := metadataCache[id]
if found {
space.cache[id] = creator(context, object)
}
}
return space
}
func (this *spaceImpl) HasApp(id ID) bool {
_, found := this.cache[id]
return found
}
func (this *spaceImpl) GetApp(id ID) interface{} {
obj, found := this.cache[id]
if !found {
return nil
}
return obj
}
// A SpaceController is supposed to be used by a shell to create Spaces. It should not be used
// directly by proxies.
type SpaceController struct {
objectCache map[ID]interface{}
}
func NewController() *SpaceController {
return &SpaceController{
objectCache: make(map[ID]interface{}),
}
}
func (this *SpaceController) Bind(id ID, object interface{}) {
this.objectCache[id] = object
}
func (this *SpaceController) ForContext(tag string) Space {
return newSpaceImpl(tag, this.objectCache)
}