Skip to content

Commit e6b4805

Browse files
committed
Add items retrieve
1 parent a55269f commit e6b4805

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

cache_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,23 @@ func TestMaxLifetime(t *testing.T) {
7676
t.Errorf("Expected empty cache to return no data")
7777
}
7878
}
79+
80+
func TestItems(t *testing.T) {
81+
dur := time.Millisecond * 100
82+
83+
cache := ttlmap.New()
84+
cache.Set("item1", "one", nil)
85+
cache.Set("item2", "two", nil)
86+
cache.Set("item3", "three", &dur)
87+
cache.Set("item4", "four", nil)
88+
89+
if len(cache.Items()) != 4 {
90+
t.Errorf("Expected cache to return 4 items")
91+
}
92+
93+
time.Sleep(dur)
94+
95+
if len(cache.Items()) != 3 {
96+
t.Errorf("Expected cache to return 3 items after cache expiry")
97+
}
98+
}

items.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package ttlmap
2+
3+
// Returns all items as map[string]interface{}
4+
func (m CacheMap) Items() map[string]interface{} {
5+
tmp := make(map[string]interface{})
6+
7+
for i := 0; i < m.options.shardCount; i++ {
8+
shard := m.items[i]
9+
shard.RLock()
10+
for key, itm := range shard.items {
11+
if !itm.Expired() {
12+
tmp[key] = itm.GetValue()
13+
}
14+
}
15+
shard.RUnlock()
16+
}
17+
return tmp
18+
}

0 commit comments

Comments
 (0)