-
Notifications
You must be signed in to change notification settings - Fork 2
/
value.go
73 lines (66 loc) · 1.8 KB
/
value.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
72
73
package goctx
import (
"context"
"sync/atomic"
"unsafe"
"github.com/zerosnake0/gounsafe"
)
// ValueFunc takes a context and a key, returns the value and the parent of the context (if exists)
type ValueFunc func(ctx context.Context, key interface{}) (value interface{}, parent context.Context)
var (
valueFuncMap = map[uintptr]ValueFunc{}
)
func loadMap() (unsafe.Pointer, map[uintptr]ValueFunc) {
ptr := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&valueFuncMap)))
m := *(*map[uintptr]ValueFunc)(unsafe.Pointer(&ptr))
return ptr, m
}
// RegisterValueFunc registers a value function
func RegisterValueFunc(ctx context.Context, f ValueFunc) {
for {
ptr, m := loadMap()
newM := map[uintptr]ValueFunc{}
for k, v := range m {
newM[k] = v
}
newM[(*gounsafe.Iface)(unsafe.Pointer(&ctx)).Itab.RType] = f
if atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&valueFuncMap)),
ptr, *(*unsafe.Pointer)(unsafe.Pointer(&newM))) {
return
}
}
}
// Value can replace the `context.Context.Value` call
func Value(ctx context.Context, key interface{}) (v interface{}) {
_, m := loadMap()
for {
if ctx == nil {
return
}
ifc := (*gounsafe.Iface)(unsafe.Pointer(&ctx))
switch ifc.Itab.RType {
// the rtype value will be zero if initialization failed
case cancelCtxRtype:
ctx = (*cancelCtx)((*gounsafe.Iface)(unsafe.Pointer(&ctx)).Data).Context
case emptyCtxRtype:
return nil
case timerCtxRtype:
ctx = (*timerCtx)((*gounsafe.Iface)(unsafe.Pointer(&ctx)).Data).Context
case valueCtxRtype:
ptr := (*valueCtx)((*gounsafe.Iface)(unsafe.Pointer(&ctx)).Data)
if key == ptr.key {
return ptr.value
}
ctx = ptr.Context
default:
f := m[ifc.Itab.RType]
if f == nil {
return ctx.Value(key)
}
v, ctx = f(ctx, key)
if v != nil {
return
}
}
}
}