Skip to content

Commit

Permalink
Fix LRU.Purge (#53)
Browse files Browse the repository at this point in the history
* fix LRU.Purge, add test

* revise test

---------

Co-authored-by: Tim Rühsen <tim.ruehsen@gmx.de>
  • Loading branch information
timwu20 and rockdaboot authored Oct 24, 2024
1 parent ecfc550 commit b272cf4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,8 @@ func (lru *LRU[K, V]) Keys() []K {
// The evict function is called for each expired item.
// The LRU metrics are reset.
func (lru *LRU[K, V]) Purge() {
for i := uint32(0); i < lru.len; i++ {
l := lru.len
for i := uint32(0); i < l; i++ {
_, _, _ = lru.RemoveOldest()
}

Expand All @@ -536,7 +537,8 @@ func (lru *LRU[K, V]) Purge() {
// PurgeExpired purges all expired items from the LRU.
// The evict function is called for each expired item.
func (lru *LRU[K, V]) PurgeExpired() {
for i := uint32(0); i < lru.len; i++ {
l := lru.len
for i := uint32(0); i < l; i++ {
pos := lru.elements[lru.head].next
if lru.elements[pos].expire != 0 {
if lru.elements[pos].expire > now() {
Expand Down
13 changes: 13 additions & 0 deletions lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,19 @@ func TestSyncedLRU_Add(t *testing.T) {
FatalIf(t, cache.Add(3, 4) == false || evictCounter != 1, "Missing eviction")
}

func TestLRU_Purge(t *testing.T) {
evictCounter := uint64(0)
cache := makeCache(t, 3, &evictCounter)

FatalIf(t, cache.Add(1, 2) == true || evictCounter != 0, "Unexpected eviction")
FatalIf(t, cache.Add(3, 4) == true || evictCounter != 0, "Unexpected eviction")
FatalIf(t, cache.Add(4, 5) == true || evictCounter != 0, "Unexpected eviction")
FatalIf(t, cache.Len() != 3, "Unexpected length")

cache.Purge()
FatalIf(t, cache.Len() != 0, "Unexpected length")
}

func TestLRU_Remove(t *testing.T) {
evictCounter := uint64(0)
cache := makeCache(t, 2, &evictCounter)
Expand Down

0 comments on commit b272cf4

Please sign in to comment.