freelru: Fix purge

This commit is contained in:
世界 2024-11-27 13:51:08 +08:00
parent a8f5bf4eb0
commit c44912a861
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 21 additions and 2 deletions

View file

@ -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() {

View file

@ -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())
}