add isExpired bool to OnEvicted callback signature

This commit is contained in:
Ashton Kinslow 2017-06-08 19:11:19 -05:00
parent 7ac151875f
commit 44fb2d5981
2 changed files with 29 additions and 6 deletions

View File

@ -41,7 +41,7 @@ type cache struct {
defaultExpiration time.Duration defaultExpiration time.Duration
items map[string]Item items map[string]Item
mu sync.RWMutex mu sync.RWMutex
onEvicted func(string, interface{}) onEvicted func(string, interface{}, bool)
janitor *janitor janitor *janitor
} }
@ -907,7 +907,7 @@ func (c *cache) Delete(k string) {
v, evicted := c.delete(k) v, evicted := c.delete(k)
c.mu.Unlock() c.mu.Unlock()
if evicted { if evicted {
c.onEvicted(k, v) c.onEvicted(k, v, false)
} }
} }
@ -943,14 +943,14 @@ func (c *cache) DeleteExpired() {
} }
c.mu.Unlock() c.mu.Unlock()
for _, v := range evictedItems { 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 // 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 // item is evicted from the cache. (Including when it is deleted manually, but
// not when it is overwritten.) Set to nil to disable. // 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.mu.Lock()
c.onEvicted = f c.onEvicted = f
c.mu.Unlock() c.mu.Unlock()

View File

@ -1231,8 +1231,8 @@ func TestOnEvicted(t *testing.T) {
t.Fatal("tc.onEvicted is not nil") t.Fatal("tc.onEvicted is not nil")
} }
works := false works := false
tc.OnEvicted(func(k string, v interface{}) { tc.OnEvicted(func(k string, v interface{}, expired bool) {
if k == "foo" && v.(int) == 3 { if k == "foo" && v.(int) == 3 && expired == false {
works = true works = true
} }
tc.Set("bar", 4, DefaultExpiration) 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) { func TestCacheSerialization(t *testing.T) {
tc := New(DefaultExpiration, 0) tc := New(DefaultExpiration, 0)
testFillAndSerialize(t, tc) testFillAndSerialize(t, tc)