Add method for getting all cache keys
Implemented the (*cache) Keys() method returning a sorted slice of all keys in the cache.
This commit is contained in:
parent
a3647f8e31
commit
8ba0cd95c8
15
cache.go
15
cache.go
|
@ -6,6 +6,7 @@ import (
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"sort"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
@ -1052,6 +1053,20 @@ func (c *cache) Items() map[string]Item {
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Keys returns a sorted slice of all the keys in the cache.
|
||||||
|
func (c *cache) Keys() []string {
|
||||||
|
c.mu.RLock()
|
||||||
|
defer c.mu.RUnlock()
|
||||||
|
keys := make([]string, len(c.items))
|
||||||
|
var i int
|
||||||
|
for k := range c.items {
|
||||||
|
keys[i] = k
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
// Returns the number of items in the cache. This may include items that have
|
// Returns the number of items in the cache. This may include items that have
|
||||||
// expired, but have not yet been cleaned up.
|
// expired, but have not yet been cleaned up.
|
||||||
func (c *cache) ItemCount() int {
|
func (c *cache) ItemCount() int {
|
||||||
|
|
|
@ -68,6 +68,24 @@ func TestCache(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCacheKeys(t *testing.T) {
|
||||||
|
tc := New(DefaultExpiration, 0)
|
||||||
|
|
||||||
|
tc.Set("a", 1, DefaultExpiration)
|
||||||
|
tc.Set("b", 2, DefaultExpiration)
|
||||||
|
tc.Set("c", 3, DefaultExpiration)
|
||||||
|
|
||||||
|
keys := tc.Keys()
|
||||||
|
|
||||||
|
if len(keys) != 3 {
|
||||||
|
t.Error("invalid number of cache keys received")
|
||||||
|
}
|
||||||
|
|
||||||
|
if keys[0] != "a" || keys[1] != "b" || keys[2] != "c" {
|
||||||
|
t.Error("invalid cache keys received")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCacheTimes(t *testing.T) {
|
func TestCacheTimes(t *testing.T) {
|
||||||
var found bool
|
var found bool
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue