Skip to content

Commit

Permalink
add delete by key
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed Jan 25, 2019
1 parent 1b27a31 commit 858abb3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,28 @@ func TestCache_Invalidate(t *testing.T) {
}
}

func TestCache_Delete(t *testing.T) {

caches := cachesTestList(t)
for _, c := range caches {
t.Run(strings.Replace(fmt.Sprintf("%T", c), "*lcw.", "", 1), func(t *testing.T) {
// fill cache
for i := 0; i < 1000; i++ {
_, err := c.Get(fmt.Sprintf("key-%d", i), func() (Value, error) {
return sizedString(fmt.Sprintf("result-%d", i)), nil
})
require.Nil(t, err)
}
assert.Equal(t, 1000, c.Stat().Keys)
assert.Equal(t, int64(9890), c.Stat().Size)

c.Delete("key-2")
assert.Equal(t, 999, c.Stat().Keys)
assert.Equal(t, int64(9890-8), c.Stat().Size)
})
}
}

func TestCache_Stats(t *testing.T) {
caches := cachesTestList(t)
for _, c := range caches {
Expand Down
5 changes: 5 additions & 0 deletions expirable_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ func (c *ExpirableCache) Purge() {
atomic.StoreInt64(&c.currentSize, 0)
}

// Delete cache item by key
func (c *ExpirableCache) Delete(key string) {
c.backend.Delete(key)
}

// Stat returns cache statistics
func (c *ExpirableCache) Stat() CacheStat {
return CacheStat{
Expand Down
4 changes: 4 additions & 0 deletions interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type LoadingCache interface {
Get(key string, fn func() (Value, error)) (val Value, err error) // load or get from cache
Peek(key string) (Value, bool) // get from cache by key
Invalidate(fn func(key string) bool) // invalidate items for func(key) == true
Delete(key string) // delete by key
Purge() // clear cache
Stat() CacheStat // cache stats
}
Expand Down Expand Up @@ -55,6 +56,9 @@ func (n *Nop) Invalidate(fn func(key string) bool) {}
// Purge does nothing for nop cache
func (n *Nop) Purge() {}

// Delete does nothing for nop cache
func (n *Nop) Delete(key string) {}

// Stat always 0s for nop cache
func (n *Nop) Stat() CacheStat {
return CacheStat{}
Expand Down
5 changes: 5 additions & 0 deletions lru_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ func (c *LruCache) Invalidate(fn func(key string) bool) {
}
}

// Delete cache item by key
func (c *LruCache) Delete(key string) {
c.backend.Remove(key)
}

// Stat returns cache statistics
func (c *LruCache) Stat() CacheStat {
return CacheStat{
Expand Down

0 comments on commit 858abb3

Please sign in to comment.