-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache-control.go
124 lines (94 loc) · 2.33 KB
/
cache-control.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package memoize
import (
"reflect"
)
type CacheControl interface {
Clear()
Remove(args ...interface{})
}
type cacheControl struct {
cacheRoot map[interface{}]interface{}
}
func (cc *cacheControl) Clear() {
cc.cacheRoot = map[interface{}]interface{}{}
}
func (cc *cacheControl) Remove(args ...interface{}) {
var m, next interface{}
var prev map[interface{}]interface{}
var ok bool
m = cc.cacheRoot
for _, arg := range args {
value := normalize(arg)
switch mm := m.(type) {
case map[interface{}]interface{}:
next, ok = mm[value]
if !ok {
// haven't cached this set of args yet
return
}
case []reflect.Value:
// more args were provided than the memoized function has
return
}
prev = m.(map[interface{}]interface{})
m = next
}
normalLastArg := normalize(args[len(args)-1])
leaf := prev[normalLastArg]
switch l := leaf.(type) {
case map[interface{}]interface{}:
for key := range l {
delete(l, key)
}
case []reflect.Value:
prev[normalLastArg] = nil
}
}
func (cc *cacheControl) fillAndCheck(args []reflect.Value) (results []reflect.Value) {
var m, next interface{}
var ok bool
m = cc.cacheRoot
for _, arg := range args {
value := normalize(arg.Interface())
next, ok = m.(map[interface{}]interface{})[value]
if !ok {
next = map[interface{}]interface{}{}
m.(map[interface{}]interface{})[value] = next
}
m = next
}
results, ok = m.([]reflect.Value)
if !ok || results == nil {
return nil
}
return results
}
func (cc *cacheControl) fillAndSet(args []reflect.Value, results []reflect.Value) {
var m interface{}
var prev map[interface{}]interface{}
m = cc.cacheRoot
for _, arg := range args {
prev = m.(map[interface{}]interface{})
value := normalize(arg.Interface())
m = prev[value]
}
value := normalize(args[len(args)-1].Interface())
prev[value] = results
}
func normalize(arg interface{}) (root interface{}) {
argT := reflect.TypeOf(arg)
if argT.Kind() == reflect.Slice {
return normalizeSlice(arg)
}
return arg
}
func normalizeSlice(arg interface{}) (norm interface{}) {
argV := reflect.ValueOf(arg)
length := argV.Len()
arr := reflect.New(reflect.ArrayOf(length, argV.Type().Elem())).Elem()
for i := 0; i < length; i++ {
arr.Index(i).Set(reflect.ValueOf(normalize(argV.Index(i).Interface())))
}
reflect.Copy(arr, argV)
return arr.Interface()
}