github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/context.go (about)

     1  package core
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  // V2rayKey is the key type of Instance in Context, exported for test.
     8  type v2rayKeyType int
     9  
    10  const v2rayKey v2rayKeyType = 1
    11  
    12  // FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
    13  func FromContext(ctx context.Context) *Instance {
    14  	if s, ok := ctx.Value(v2rayKey).(*Instance); ok {
    15  		return s
    16  	}
    17  	return nil
    18  }
    19  
    20  // MustFromContext returns an Instance from the given context, or panics if not present.
    21  func MustFromContext(ctx context.Context) *Instance {
    22  	v := FromContext(ctx)
    23  	if v == nil {
    24  		panic("V is not in context.")
    25  	}
    26  	return v
    27  }
    28  
    29  /*
    30  	toContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
    31  
    32  It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
    33  in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
    34  use this function in your third party code.
    35  
    36  For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
    37  and may break at any time.
    38  */
    39  func toContext(ctx context.Context, v *Instance) context.Context {
    40  	if FromContext(ctx) != v {
    41  		ctx = context.WithValue(ctx, v2rayKey, v)
    42  	}
    43  	return ctx
    44  }
    45  
    46  /*
    47  ToBackgroundDetachedContext create a detached context from another context
    48  Internal API
    49  */
    50  func ToBackgroundDetachedContext(ctx context.Context) context.Context {
    51  	return &temporaryValueDelegationFix{context.Background(), ctx}
    52  }
    53  
    54  type temporaryValueDelegationFix struct {
    55  	context.Context
    56  	value context.Context
    57  }
    58  
    59  func (t *temporaryValueDelegationFix) Value(key interface{}) interface{} {
    60  	return t.value.Value(key)
    61  }