From c44912a8610463cc8e4a0be8148e6e11a62456d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Wed, 27 Nov 2024 13:51:08 +0800 Subject: [PATCH] freelru: Fix purge --- contrab/freelru/lru.go | 6 ++++-- contrab/freelru/lru_test.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/contrab/freelru/lru.go b/contrab/freelru/lru.go index b3e6e29..8096015 100644 --- a/contrab/freelru/lru.go +++ b/contrab/freelru/lru.go @@ -592,7 +592,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++ { + lruLen := lru.len + for i := uint32(0); i < lruLen; i++ { _, _, _ = lru.RemoveOldest() } @@ -602,7 +603,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++ { + lruLen := lru.len + for i := uint32(0); i < lruLen; i++ { pos := lru.elements[lru.head].next if lru.elements[pos].expire != 0 { if lru.elements[pos].expire > now() { diff --git a/contrab/freelru/lru_test.go b/contrab/freelru/lru_test.go index 36e9a05..2650802 100644 --- a/contrab/freelru/lru_test.go +++ b/contrab/freelru/lru_test.go @@ -76,3 +76,20 @@ func TestUpdateLifetime2(t *testing.T) { _, ok = lru.Get("hello") require.False(t, ok) } + +func TestPeekWithLifetime(t *testing.T) { + t.Parallel() + lru, err := freelru.New[string, string](1024, maphash.NewHasher[string]().Hash32) + require.NoError(t, err) + lru.SetLifetime(time.Second) + lru.Add("1", "") + time.Sleep(300 * time.Millisecond) + lru.Add("2", "") + time.Sleep(300 * time.Millisecond) + lru.Add("3", "") + time.Sleep(300 * time.Millisecond) + lru.Add("4", "") + time.Sleep(time.Second) + lru.PurgeExpired() + require.Equal(t, 0, lru.Len()) +}