Skip to content

Commit

Permalink
新增remove方法用来,删除并返回删除元素
Browse files Browse the repository at this point in the history
  • Loading branch information
ybq committed Mar 21, 2018
1 parent a3647f8 commit baf8082
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
17 changes: 17 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
18 changes: 18 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit baf8082

Please sign in to comment.