forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
71 lines (56 loc) · 2.17 KB
/
context.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
// +build !confonly
package core
import (
"context"
)
// V2rayKey is the key type of Instance in Context, exported for test.
type V2rayKey int
const v2rayKey V2rayKey = 1
// FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
func FromContext(ctx context.Context) *Instance {
if s, ok := ctx.Value(v2rayKey).(*Instance); ok {
return s
}
return nil
}
// MustFromContext returns an Instance from the given context, or panics if not present.
func MustFromContext(ctx context.Context) *Instance {
v := FromContext(ctx)
if v == nil {
panic("V is not in context.")
}
return v
}
/* toContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
use this function in your third party code.
For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
and may break at any time.
*/
func toContext(ctx context.Context, v *Instance) context.Context {
if FromContext(ctx) != v {
ctx = context.WithValue(ctx, v2rayKey, v)
}
return ctx
}
/* mustToContext returns ctx from the given context, or panics if not found that.
It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
use this function in your third party code.
For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
and may break at any time.
*/
func mustToContext(ctx context.Context, v *Instance) context.Context {
if c := toContext(ctx, v); c != ctx {
panic("V is not in context.")
}
return ctx
}
/* ToBackgroundDetachedContext create a detached context from another context
Internal API
*/
func ToBackgroundDetachedContext(ctx context.Context) context.Context {
instance := MustFromContext(ctx)
return toContext(context.Background(), instance)
}