File tree 2 files changed +38
-0
lines changed
2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,7 @@ limitations under the License.
16
16
package lru
17
17
18
18
import (
19
+ "fmt"
19
20
"sync"
20
21
21
22
groupcache "k8s.io/utils/internal/third_party/forked/golang/golang-lru"
@@ -44,6 +45,15 @@ func NewWithEvictionFunc(size int, f EvictionFunc) *Cache {
44
45
return c
45
46
}
46
47
48
+ // SetEvictionFunc updates the eviction func
49
+ func (c * Cache ) SetEvictionFunc (f EvictionFunc ) error {
50
+ if c .cache .OnEvicted != nil {
51
+ return fmt .Errorf ("lru cache eviction function is already set" )
52
+ }
53
+ c .cache .OnEvicted = f
54
+ return nil
55
+ }
56
+
47
57
// Add adds a value to the cache.
48
58
func (c * Cache ) Add (key Key , value interface {}) {
49
59
c .lock .Lock ()
Original file line number Diff line number Diff line change @@ -130,3 +130,31 @@ func TestEviction(t *testing.T) {
130
130
t .Errorf ("unexpected eviction data: key=%v val=%v" , seenKey , seenVal )
131
131
}
132
132
}
133
+
134
+ func TestSetEviction (t * testing.T ) {
135
+ var seenKey Key
136
+ var seenVal interface {}
137
+
138
+ lru := New (1 )
139
+
140
+ err := lru .SetEvictionFunc (func (key Key , value interface {}) {
141
+ seenKey = key
142
+ seenVal = value
143
+ })
144
+
145
+ if err != nil {
146
+ t .Errorf ("unexpected error setting eviction function: %v" , err )
147
+ }
148
+
149
+ lru .Add (1 , 2 )
150
+ lru .Add (3 , 4 )
151
+
152
+ if seenKey != 1 || seenVal != 2 {
153
+ t .Errorf ("unexpected eviction data: key=%v val=%v" , seenKey , seenVal )
154
+ }
155
+
156
+ err = lru .SetEvictionFunc (func (key Key , value interface {}) {})
157
+ if err == nil {
158
+ t .Errorf ("expected error but got none" )
159
+ }
160
+ }
You can’t perform that action at this time.
0 commit comments