From 8e3c28f0e918e9c64a1985b7d4441d25d2447c03 Mon Sep 17 00:00:00 2001 From: Pavel Bazika Date: Thu, 28 May 2020 16:15:44 +0200 Subject: [PATCH] Flush calls onEvicted --- cache.go | 9 +++++++++ cache_test.go | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/cache.go b/cache.go index db88d2f..84b9877 100644 --- a/cache.go +++ b/cache.go @@ -1063,9 +1063,18 @@ func (c *cache) ItemCount() int { // Delete all items from the cache. func (c *cache) Flush() { + var oldCache map[string]Item + c.mu.Lock() + if c.onEvicted != nil { + oldCache = c.items + } c.items = map[string]Item{} c.mu.Unlock() + + for k, v := range oldCache { + c.onEvicted(k, v.Object) + } } type janitor struct { diff --git a/cache_test.go b/cache_test.go index de3e9d6..322da59 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1179,6 +1179,23 @@ func TestFlush(t *testing.T) { if x != nil { 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) {