Skip to content

Commit

Permalink
Add a helper method to set eviction function after construction
Browse files Browse the repository at this point in the history
Signed-off-by: Davanum Srinivas <davanum@gmail.com>
  • Loading branch information
dims committed Nov 3, 2024
1 parent 49e7df5 commit 7edc6f1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lru/lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.
package lru

import (
"fmt"
"sync"

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

// SetEvictionFunc updates the eviction func
func (c *Cache) SetEvictionFunc(f EvictionFunc) error {
if c.cache.OnEvicted != nil {
return fmt.Errorf("lru cache eviction function is already set")
}
c.cache.OnEvicted = f
return nil
}

// Add adds a value to the cache.
func (c *Cache) Add(key Key, value interface{}) {
c.lock.Lock()
Expand Down
28 changes: 28 additions & 0 deletions lru/lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,31 @@ func TestEviction(t *testing.T) {
t.Errorf("unexpected eviction data: key=%v val=%v", seenKey, seenVal)
}
}

func TestSetEviction(t *testing.T) {
var seenKey Key
var seenVal interface{}

lru := New(1)

err := lru.SetEvictionFunc(func(key Key, value interface{}) {
seenKey = key
seenVal = value
})

if err != nil {
t.Errorf("unexpected error setting eviction function: %v", err)
}

lru.Add(1, 2)
lru.Add(3, 4)

if seenKey != 1 || seenVal != 2 {
t.Errorf("unexpected eviction data: key=%v val=%v", seenKey, seenVal)
}

err = lru.SetEvictionFunc(func(key Key, value interface{}) {})
if err == nil {
t.Errorf("expected error but got none")
}
}

0 comments on commit 7edc6f1

Please sign in to comment.