2018-01-10 06:22:37 -05:00
|
|
|
package core
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
|
|
|
|
2020-06-27 00:28:53 -04:00
|
|
|
// V2rayKey is the key type of Instance in Context, exported for test.
|
2021-05-04 09:19:23 -04:00
|
|
|
type v2rayKeyType int
|
2018-01-10 06:22:37 -05:00
|
|
|
|
2021-05-04 09:19:23 -04:00
|
|
|
const v2rayKey v2rayKeyType = 1
|
2018-01-10 06:22:37 -05:00
|
|
|
|
2018-02-21 11:05:29 -05:00
|
|
|
// FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
|
2018-01-10 06:22:37 -05:00
|
|
|
func FromContext(ctx context.Context) *Instance {
|
2021-04-02 07:12:27 -04:00
|
|
|
if s, ok := ctx.Value(v2rayKey).(*Instance); ok {
|
2018-01-10 06:22:37 -05:00
|
|
|
return s
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2018-02-21 11:05:29 -05:00
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
2021-04-04 07:28:00 -04:00
|
|
|
|
2022-06-28 08:26:01 -04:00
|
|
|
/*
|
|
|
|
toContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
|
2021-04-05 13:13:24 -04:00
|
|
|
|
|
|
|
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 {
|
2021-04-04 07:28:00 -04:00
|
|
|
if FromContext(ctx) != v {
|
|
|
|
ctx = context.WithValue(ctx, v2rayKey, v)
|
|
|
|
}
|
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
|
2022-06-28 08:26:01 -04:00
|
|
|
/*
|
|
|
|
ToBackgroundDetachedContext create a detached context from another context
|
2021-05-04 16:06:23 -04:00
|
|
|
Internal API
|
2021-04-28 11:29:19 -04:00
|
|
|
*/
|
|
|
|
func ToBackgroundDetachedContext(ctx context.Context) context.Context {
|
2021-06-22 07:42:20 -04:00
|
|
|
return &temporaryValueDelegationFix{context.Background(), ctx}
|
|
|
|
}
|
|
|
|
|
|
|
|
type temporaryValueDelegationFix struct {
|
|
|
|
context.Context
|
|
|
|
value context.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *temporaryValueDelegationFix) Value(key interface{}) interface{} {
|
|
|
|
return t.value.Value(key)
|
2021-04-28 11:29:19 -04:00
|
|
|
}
|