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

add isExpired bool to OnEvicted callback signature #58

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 4 additions & 4 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ type cache struct {
defaultExpiration time.Duration
items map[string]Item
mu sync.RWMutex
onEvicted func(string, interface{})
onEvicted func(string, interface{}, bool)
janitor *janitor
}

Expand Down Expand Up @@ -907,7 +907,7 @@ func (c *cache) Delete(k string) {
v, evicted := c.delete(k)
c.mu.Unlock()
if evicted {
c.onEvicted(k, v)
c.onEvicted(k, v, false)
}
}

Expand Down Expand Up @@ -943,14 +943,14 @@ func (c *cache) DeleteExpired() {
}
c.mu.Unlock()
for _, v := range evictedItems {
c.onEvicted(v.key, v.value)
c.onEvicted(v.key, v.value, true)
}
}

// Sets an (optional) function that is called with the key and value when an
// item is evicted from the cache. (Including when it is deleted manually, but
// not when it is overwritten.) Set to nil to disable.
func (c *cache) OnEvicted(f func(string, interface{})) {
func (c *cache) OnEvicted(f func(string, interface{}, bool)) {
c.mu.Lock()
c.onEvicted = f
c.mu.Unlock()
Expand Down
27 changes: 25 additions & 2 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1231,8 +1231,8 @@ func TestOnEvicted(t *testing.T) {
t.Fatal("tc.onEvicted is not nil")
}
works := false
tc.OnEvicted(func(k string, v interface{}) {
if k == "foo" && v.(int) == 3 {
tc.OnEvicted(func(k string, v interface{}, expired bool) {
if k == "foo" && v.(int) == 3 && expired == false {
works = true
}
tc.Set("bar", 4, DefaultExpiration)
Expand All @@ -1247,6 +1247,29 @@ func TestOnEvicted(t *testing.T) {
}
}

func TestOnEvictedWithExpired(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("foo", 3, 1)
if tc.onEvicted != nil {
t.Fatal("tc.onEvicted is not nil")
}
works := false
tc.OnEvicted(func(k string, v interface{}, expired bool) {
if k == "foo" && v.(int) == 3 && expired == true {
works = true
}
tc.Set("bar", 4, DefaultExpiration)
})
tc.DeleteExpired()

x, _ := tc.Get("bar")
if !works {
t.Error("works bool not true")
}
if x.(int) != 4 {
t.Error("bar was not 4")
}
}
func TestCacheSerialization(t *testing.T) {
tc := New(DefaultExpiration, 0)
testFillAndSerialize(t, tc)
Expand Down