1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-03 20:45:23 +00:00
v2fly/app/space.go

90 lines
1.8 KiB
Go
Raw Normal View History

2015-12-05 21:55:45 +00:00
package app
2016-01-31 16:01:28 +00:00
type ID int
// Context of a function call from proxy to app.
2015-12-10 22:55:39 +00:00
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 {
2016-01-31 16:01:28 +00:00
HasApp(ID) bool
GetApp(ID) interface{}
}
type ForContextCreator func(Context, interface{}) interface{}
var (
metadataCache = make(map[ID]ForContextCreator)
)
2016-05-11 19:05:58 +00:00
func Register(id ID, creator ForContextCreator) {
2016-01-31 16:01:28 +00:00
// TODO: check id
metadataCache[id] = creator
}
type contextImpl struct {
callerTag string
}
2015-12-06 10:00:10 +00:00
2016-01-31 16:01:28 +00:00
func (this *contextImpl) CallerTag() string {
return this.callerTag
}
type spaceImpl struct {
cache map[ID]interface{}
tag string
}
2015-12-11 14:56:10 +00:00
2016-01-31 16:01:28 +00:00
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
}
2016-01-31 16:01:28 +00:00
func (this *SpaceController) ForContext(tag string) Space {
return newSpaceImpl(tag, this.objectCache)
2015-12-05 21:55:45 +00:00
}