Add method for delete by regex rule

This commit is contained in:
vitams 2019-04-10 23:50:35 +05:00
parent 5633e08626
commit 63ea70e00b
2 changed files with 24 additions and 0 deletions

View File

@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"regexp"
"runtime"
"sync"
"time"
@ -911,6 +912,16 @@ func (c *cache) Delete(k string) {
}
}
// Delete an item from the cache by regex rule
func (c *cache) DeleteRegex(rule string) {
re, _ := regexp.Compile(rule)
for k := range c.items {
if re.MatchString(k) {
c.Delete(k)
}
}
}
func (c *cache) delete(k string) (interface{}, bool) {
if c.onEvicted != nil {
if v, found := c.items[k]; found {

View File

@ -1150,6 +1150,19 @@ func TestDelete(t *testing.T) {
}
}
func TestDeleteRegex(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("foo1", "bar", DefaultExpiration)
tc.DeleteRegex(`^foo`)
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)