-
Notifications
You must be signed in to change notification settings - Fork 2
/
value_valuectx.go
53 lines (46 loc) · 1.09 KB
/
value_valuectx.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
package goctx
import (
"context"
"reflect"
"unsafe"
"github.com/zerosnake0/gounsafe"
)
var (
valueCtxRtype gounsafe.RType
)
type valueCtx struct {
context.Context
key interface{}
value interface{}
}
func valueCtxFunc(ctx context.Context, key interface{}) (value interface{}, parent context.Context) {
ptr := (*valueCtx)((*gounsafe.Iface)(unsafe.Pointer(&ctx)).Data)
if key == ptr.key {
return ptr.value, ptr.Context
}
return nil, ptr.Context
}
func checkValueCtx(o interface{}) bool {
if o == nil {
return false
}
typ := reflect.TypeOf(o)
if typ.Kind() != reflect.Ptr {
return false
}
typ = typ.Elem()
if typ.String() != "context.valueCtx" {
return false
}
ourType := reflect.TypeOf(valueCtx{})
return checkInterfaceField(typ, "key", ourType.Field(1).Offset) &&
checkInterfaceField(typ, "val", ourType.Field(2).Offset) &&
checkContextField(typ, "Context", 0)
}
func init() {
ctx := context.WithValue(context.TODO(), valueCtx{}, "")
if checkValueCtx(ctx) {
RegisterValueFunc(ctx, valueCtxFunc)
valueCtxRtype = (*gounsafe.Iface)(unsafe.Pointer(&ctx)).Itab.RType
}
}