-
Notifications
You must be signed in to change notification settings - Fork 2
/
runtime.go
61 lines (54 loc) · 1.39 KB
/
runtime.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
package funcache
import (
"reflect"
"runtime"
)
const cacheBustingFn = "github.com/aviddiviner/go-funcache.(*Cache).Bust"
var cacheBustingFnPc uintptr
// Return the program counters of function invocations all the way up the stack.
func getAllCallers(skip int) (pcs []uintptr) {
// Arbitrarily do this in batches of 64
var batch = make([]uintptr, 64)
var n int
for {
n = runtime.Callers(skip, batch)
pcs = append(pcs, batch[:n]...)
if n < len(batch) {
break
}
skip += n
}
return
}
// Check if any of the callers were our cache busting function.
func wasCalledByCacheBustingFn() bool {
// Skip the first 3 callers:
// 1. runtime.Callers
// 2. github.com/aviddiviner/funcache.getAllCallers
// 3. github.com/aviddiviner/funcache.wasCalledByCacheBustingFn
//
// From there on it should be:
// 4. github.com/aviddiviner/funcache.(*Cache).Cache
// ...
pcs := getAllCallers(3)
for _, pc := range pcs {
if pc == cacheBustingFnPc {
return true
}
}
return false
}
func getFnName(fn func() interface{}) string {
ptr := reflect.ValueOf(fn).Pointer()
return runtime.FuncForPC(ptr).Name()
}
func init() {
nilCache().Bust(func() {
cacheBustingFnPc, _, _, _ = runtime.Caller(1)
})
// Sanity check that we have the right cache busting function
fn := runtime.FuncForPC(cacheBustingFnPc)
if fn.Name() != cacheBustingFn {
panic("funcache: init: unable to identify cache busting func")
}
}