diff --git a/cache.go b/cache.go index 7dcc14e..4a63866 100644 --- a/cache.go +++ b/cache.go @@ -1098,11 +1098,26 @@ func (c *cache) ItemCount() int { return n } -// Delete all items from the cache. -func (c *cache) Flush() { +// Flush all items from the cache and return them. +func (c *cache) Flush() map[string]*Item { c.mu.Lock() + defer c.mu.Unlock() + + m := make(map[string]*Item, len(c.items)) + for k, v := range c.items { + // "Inlining" of Expired + if v.Expired() { + continue + } + m[k] = &Item{ + Object: v.Object, + Expiration: v.Expiration, + } + } + c.items = map[string]*Item{} - c.mu.Unlock() + + return m } type janitor struct { diff --git a/cache_test.go b/cache_test.go index 655b865..7b89c61 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1164,7 +1164,7 @@ func TestFlush(t *testing.T) { tc := New(DefaultExpiration, 0) tc.Set("foo", "bar", DefaultExpiration) tc.Set("baz", "yes", DefaultExpiration) - tc.Flush() + items := tc.Flush() x, found := tc.Get("foo") if found { t.Error("foo was found, but it should have been deleted") @@ -1179,6 +1179,16 @@ func TestFlush(t *testing.T) { if x != nil { t.Error("x is not nil:", x) } + + x, found = items["foo"] + if !found { + t.Error("foo was not found, it should be returned on flush") + } + + x, found = items["baz"] + if !found { + t.Error("baz was not found, it should be returned on flush") + } } func TestIncrementOverflowInt(t *testing.T) {