Flush calls onEvicted

This commit is contained in:
Pavel Bazika 2020-05-28 16:15:44 +02:00
parent 46f4078530
commit 8e3c28f0e9
2 changed files with 26 additions and 0 deletions

View File

@ -1063,9 +1063,18 @@ func (c *cache) ItemCount() int {
// Delete all items from the cache. // Delete all items from the cache.
func (c *cache) Flush() { func (c *cache) Flush() {
var oldCache map[string]Item
c.mu.Lock() c.mu.Lock()
if c.onEvicted != nil {
oldCache = c.items
}
c.items = map[string]Item{} c.items = map[string]Item{}
c.mu.Unlock() c.mu.Unlock()
for k, v := range oldCache {
c.onEvicted(k, v.Object)
}
} }
type janitor struct { type janitor struct {

View File

@ -1179,6 +1179,23 @@ func TestFlush(t *testing.T) {
if x != nil { if x != nil {
t.Error("x is not nil:", x) t.Error("x is not nil:", x)
} }
evictMask := 0
tc.OnEvicted(func(k string, v interface{}) {
if k == "foo" && v.(string) == "bar" {
evictMask |= 0x1
}
if k == "baz" && v.(string) == "yes" {
evictMask |= 0x2
}
})
tc.Set("foo", "bar", DefaultExpiration)
tc.Set("baz", "yes", DefaultExpiration)
tc.Flush()
if evictMask != 0x3 {
t.Error("on evicted on flush fails")
}
} }
func TestIncrementOverflowInt(t *testing.T) { func TestIncrementOverflowInt(t *testing.T) {