forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
space.go
82 lines (65 loc) · 1.5 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
package app
import (
"errors"
"github.com/v2ray/v2ray-core/common"
)
var (
ErrMissingApplication = errors.New("App: Failed to found one or more applications.")
)
type ID int
// Context of a function call from proxy to app.
type Context interface {
CallerTag() string
}
type Caller interface {
Tag() string
}
type Application interface {
common.Releasable
}
type ApplicationInitializer func() error
// 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 {
Initialize() error
InitializeApplication(ApplicationInitializer)
HasApp(ID) bool
GetApp(ID) Application
BindApp(ID, Application)
}
type spaceImpl struct {
cache map[ID]Application
appInit []ApplicationInitializer
}
func NewSpace() Space {
return &spaceImpl{
cache: make(map[ID]Application),
appInit: make([]ApplicationInitializer, 0, 32),
}
}
func (this *spaceImpl) InitializeApplication(f ApplicationInitializer) {
this.appInit = append(this.appInit, f)
}
func (this *spaceImpl) Initialize() error {
for _, f := range this.appInit {
err := f()
if err != nil {
return err
}
}
return nil
}
func (this *spaceImpl) HasApp(id ID) bool {
_, found := this.cache[id]
return found
}
func (this *spaceImpl) GetApp(id ID) Application {
obj, found := this.cache[id]
if !found {
return nil
}
return obj
}
func (this *spaceImpl) BindApp(id ID, application Application) {
this.cache[id] = application
}