From 44fb2d598126417d35909d79d53190e9820f1567 Mon Sep 17 00:00:00 2001 From: Ashton Kinslow Date: Thu, 8 Jun 2017 19:11:19 -0500 Subject: [PATCH] add isExpired bool to OnEvicted callback signature --- cache.go | 8 ++++---- cache_test.go | 27 +++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/cache.go b/cache.go index 30b1ea2..7ff77a1 100644 --- a/cache.go +++ b/cache.go @@ -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 } @@ -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) } } @@ -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() diff --git a/cache_test.go b/cache_test.go index 47a3d53..fbfb530 100644 --- a/cache_test.go +++ b/cache_test.go @@ -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) @@ -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)