2019-02-01 14:08:21 -05:00
|
|
|
// +build !confonly
|
|
|
|
|
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
|
|
|
|
2021-04-05 13:13:24 -04:00
|
|
|
/* 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 {
|
2021-04-04 07:28:00 -04:00
|
|
|
if FromContext(ctx) != v {
|
|
|
|
ctx = context.WithValue(ctx, v2rayKey, v)
|
|
|
|
}
|
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
|
2021-05-04 16:06:23 -04:00
|
|
|
/*ToBackgroundDetachedContext create a detached context from another context
|
|
|
|
Internal API
|
2021-04-28 11:29:19 -04:00
|
|
|
*/
|
|
|
|
func ToBackgroundDetachedContext(ctx context.Context) context.Context {
|
|
|
|
instance := MustFromContext(ctx)
|
|
|
|
return toContext(context.Background(), instance)
|
|
|
|
}
|