Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lru: add support for setting eviction func #275

Merged
merged 1 commit into from
Feb 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lru/lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -22,6 +22,7 @@ import (
)

type Key = groupcache.Key
type EvictionFunc = func(key Key, value interface{})

// Cache is a thread-safe fixed size LRU cache.
type Cache struct {
Expand All @@ -36,6 +37,13 @@ func New(size int) *Cache {
}
}

// NewWithEvictionFunc creates an LRU of the given size with the given eviction func.
func NewWithEvictionFunc(size int, f EvictionFunc) *Cache {
c := New(size)
c.cache.OnEvicted = f
return c
}

// Add adds a value to the cache.
func (c *Cache) Add(key Key, value interface{}) {
c.lock.Lock()
Expand Down
17 changes: 17 additions & 0 deletions lru/lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,20 @@ func TestGetRace(t *testing.T) {
// let them run
time.Sleep(5 * time.Second)
}

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

lru := NewWithEvictionFunc(1, func(key Key, value interface{}) {
seenKey = key
seenVal = value
})

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

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