Skip to content

Commit

Permalink
fix Keys method with tests
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Jan 4, 2024
1 parent 172402c commit ffba292
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
9 changes: 6 additions & 3 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,12 @@ func (c *Cache[K, V]) Keys() (all []K) {
now := atomic.LoadUint32(&clock)
for i := range c.shards {
c.shards[i].mu.Lock()
for j := range c.shards[i].list.nodes {
node := &c.shards[i].list.nodes[j]
if expires := node.expires; expires == 0 || expires <= now {
for _, b := range c.shards[i].table.buckets {
if b.index == 0 {
continue
}
node := &c.shards[i].list.nodes[b.index]
if expires := node.expires; expires == 0 || now <= expires {
all = append(all, node.key)
}
}
Expand Down
29 changes: 24 additions & 5 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ func TestCacheEviction(t *testing.T) {
if got, want := l.Len(), 128; got != want {
t.Fatalf("curent cache length %v should be %v", got, want)
}

if got, want := len(l.Keys()), 128; got != want {
t.Fatalf("curent cache keys length %v should be %v", got, want)
}
}

func TestCachePeek(t *testing.T) {
Expand Down Expand Up @@ -123,17 +127,32 @@ func TestCachePeek(t *testing.T) {
func TestCacheTouchGet(t *testing.T) {
l := newWithShards[string, int](1, 256)

l.SetWithTTL("foobar", 42, 3*time.Second)
l.Set("a", 1)
l.SetWithTTL("b", 2, 3*time.Second)
l.SetWithTTL("c", 3, 3*time.Second)

if got, want := l.Keys(), 3; len(got) != want {
t.Fatalf("curent cache keys %v length should be %v", got, want)
}

time.Sleep(2 * time.Second)
if v, ok := l.TouchGet("foobar"); !ok || v != 42 {
t.Errorf("foobar should be set to 42: %v,", v)
if v, ok := l.TouchGet("c"); !ok || v != 3 {
t.Errorf("c should be set to 3: %v,", v)
}

if got, want := l.Keys(), 3; len(got) != want {
t.Fatalf("curent cache keys %v length should be %v", got, want)
}

time.Sleep(2 * time.Second)
if v, ok := l.Get("foobar"); !ok || v != 42 {
t.Errorf("foobar should be still set to 42: %v,", v)
if v, ok := l.Get("c"); !ok || v != 3 {
t.Errorf("c should be still set to 3: %v,", v)
}

if got, want := l.Keys(), 2; len(got) != want {
t.Fatalf("curent cache keys %v length should be %v", got, want)
}

}

func BenchmarkCacheRand(b *testing.B) {
Expand Down

0 comments on commit ffba292

Please sign in to comment.