Skip to content

Commit 7edc6f1

Browse files
committed
Add a helper method to set eviction function after construction
Signed-off-by: Davanum Srinivas <[email protected]>
1 parent 49e7df5 commit 7edc6f1

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lru/lru.go

+10
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ limitations under the License.
1616
package lru
1717

1818
import (
19+
"fmt"
1920
"sync"
2021

2122
groupcache "k8s.io/utils/internal/third_party/forked/golang/golang-lru"
@@ -44,6 +45,15 @@ func NewWithEvictionFunc(size int, f EvictionFunc) *Cache {
4445
return c
4546
}
4647

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+
4757
// Add adds a value to the cache.
4858
func (c *Cache) Add(key Key, value interface{}) {
4959
c.lock.Lock()

lru/lru_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,31 @@ func TestEviction(t *testing.T) {
130130
t.Errorf("unexpected eviction data: key=%v val=%v", seenKey, seenVal)
131131
}
132132
}
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+
}

0 commit comments

Comments
 (0)