From baf80827aa9ec87e5149363f517cf495ccfaa1a0 Mon Sep 17 00:00:00 2001 From: ybq Date: Wed, 21 Mar 2018 16:27:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Eremove=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E7=94=A8=E6=9D=A5=EF=BC=8C=E5=88=A0=E9=99=A4=E5=B9=B6=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E5=88=A0=E9=99=A4=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cache.go | 17 +++++++++++++++++ cache_test.go | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+) 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)