diff --git a/cache.go b/cache.go index db88d2f..9fec4df 100644 --- a/cache.go +++ b/cache.go @@ -6,6 +6,7 @@ import ( "io" "os" "runtime" + "sort" "sync" "time" ) @@ -1052,6 +1053,20 @@ func (c *cache) Items() map[string]Item { 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 // expired, but have not yet been cleaned up. func (c *cache) ItemCount() int { diff --git a/cache_test.go b/cache_test.go index 47a3d53..4347519 100644 --- a/cache_test.go +++ b/cache_test.go @@ -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) { var found bool