diff --git a/cache.go b/cache.go index db88d2f..58d768e 100644 --- a/cache.go +++ b/cache.go @@ -911,6 +911,23 @@ func (c *cache) Delete(k string) { } } +// Remove an item from the cache. Does nothing if the key is not in the cache. +// There is delete cache data, return cache data and presence status +func (c *cache) Remove(k string) (interface{}, bool) { + c.mu.Lock() + v, found := c.items[k] + if found { + delete(c.items, k) + c.mu.Unlock() + if c.onEvicted != nil { + c.onEvicted(k, v) + } + return v.Object, true + } + c.mu.Unlock() + return nil, false +} + func (c *cache) delete(k string) (interface{}, bool) { if c.onEvicted != nil { if v, found := c.items[k]; found { diff --git a/cache_test.go b/cache_test.go index 47a3d53..d52cbec 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1149,7 +1149,25 @@ func TestDelete(t *testing.T) { t.Error("x is not nil:", x) } } +func TestREmove(t *testing.T) { + tc := New(DefaultExpiration, 0) + tc.Set("foo", "bar", DefaultExpiration) + data, ok := tc.Remove("foo") + if !ok { + t.Error("foo was not found, It should be discovered") + } + if data != "bar" { + t.Error("foo should be bar ") + } + x, found := tc.Get("foo") + if found { + t.Error("foo was found, but it should have been deleted") + } + if x != nil { + t.Error("x is not nil:", x) + } +} func TestItemCount(t *testing.T) { tc := New(DefaultExpiration, 0) tc.Set("foo", "1", DefaultExpiration)