Skip to content

Commit 6ad9dfb

Browse files
authored
Merge pull request #35 from Code-Hex/fix/33
fixed #33
2 parents ccf9cd9 + c1bd684 commit 6ad9dfb

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

policy/lfu/lfu.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package lfu
22

33
import (
44
"container/heap"
5+
"log"
56
)
67

78
// Cache is used a LFU (Least-frequently used) cache replacement policy.
@@ -69,6 +70,8 @@ func (c *Cache[K, V]) Set(key K, val V) {
6970

7071
if len(c.items) == c.cap {
7172
evictedEntry := heap.Pop(c.queue).(*entry[K, V])
73+
// e := evictedEntry
74+
// log.Println(c.items, e.index, e.key)
7275
delete(c.items, evictedEntry.key)
7376
}
7477

@@ -89,6 +92,7 @@ func (c *Cache[K, V]) Keys() []K {
8992
// Delete deletes the item with provided key from the cache.
9093
func (c *Cache[K, V]) Delete(key K) {
9194
if e, ok := c.items[key]; ok {
95+
log.Println(c.items, e.index, e.key)
9296
heap.Remove(c.queue, e.index)
9397
delete(c.items, key)
9498
}

policy/lfu/lfu_test.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func TestSet(t *testing.T) {
4444
}
4545

4646
func TestDelete(t *testing.T) {
47-
cache := lfu.NewCache[string, int](lfu.WithCapacity(1))
47+
cache := lfu.NewCache[string, int](lfu.WithCapacity(2))
4848
cache.Set("foo", 1)
4949
if got := cache.Len(); got != 1 {
5050
t.Fatalf("invalid length: %d", got)
@@ -63,3 +63,15 @@ func TestDelete(t *testing.T) {
6363
t.Fatalf("invalid get after deleted %v", ok)
6464
}
6565
}
66+
67+
// check don't panic
68+
func TestIssue33(t *testing.T) {
69+
cache := lfu.NewCache[string, int](lfu.WithCapacity(2))
70+
cache.Set("foo", 1)
71+
cache.Set("foo2", 2)
72+
cache.Set("foo3", 3)
73+
74+
cache.Delete("foo")
75+
cache.Delete("foo2")
76+
cache.Delete("foo3")
77+
}

policy/lfu/priotiry_queue.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,11 @@ func (l *priorityQueue[K, V]) Pop() interface{} {
6565
entry := old[n-1]
6666
old[n-1] = nil // avoid memory leak
6767
entry.index = -1 // for safety
68-
*l = old[0 : n-1]
68+
new := old[0 : n-1]
69+
for i := 0; i < len(new); i++ {
70+
new[i].index = i
71+
}
72+
*l = new
6973
return entry
7074
}
7175

0 commit comments

Comments
 (0)