mirror of
https://github.com/SagerNet/sing.git
synced 2025-04-02 03:17:37 +03:00
freelru: purge all expired items
This commit is contained in:
parent
39040e06dc
commit
3f30aaf25e
2 changed files with 16 additions and 16 deletions
|
@ -688,14 +688,19 @@ func (lru *LRU[K, V]) Purge() {
|
|||
// The evict function is called for each expired item.
|
||||
func (lru *LRU[K, V]) PurgeExpired() {
|
||||
l := lru.len
|
||||
if l == 0 {
|
||||
return
|
||||
}
|
||||
n := now()
|
||||
pos := lru.head
|
||||
for i := uint32(0); i < l; i++ {
|
||||
pos := lru.elements[lru.head].next
|
||||
next := lru.elements[pos].next
|
||||
if lru.elements[pos].expire != 0 {
|
||||
if lru.elements[pos].expire > now() {
|
||||
return // no more expired items
|
||||
if lru.elements[pos].expire <= n {
|
||||
lru.removeAt(pos)
|
||||
}
|
||||
lru.removeAt(pos)
|
||||
}
|
||||
pos = next
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -14,10 +14,9 @@ func TestUpdateLifetimeOnGet(t *testing.T) {
|
|||
t.Parallel()
|
||||
lru, err := freelru.New[string, string](1024, maphash.NewHasher[string]().Hash32)
|
||||
require.NoError(t, err)
|
||||
lru.SetUpdateLifetimeOnGet(true)
|
||||
lru.AddWithLifetime("hello", "world", 2*time.Second)
|
||||
time.Sleep(time.Second)
|
||||
_, ok := lru.Get("hello")
|
||||
_, ok := lru.GetAndRefresh("hello")
|
||||
require.True(t, ok)
|
||||
time.Sleep(time.Second + time.Millisecond*100)
|
||||
_, ok = lru.Get("hello")
|
||||
|
@ -28,7 +27,6 @@ func TestUpdateLifetimeOnGet1(t *testing.T) {
|
|||
t.Parallel()
|
||||
lru, err := freelru.New[string, string](1024, maphash.NewHasher[string]().Hash32)
|
||||
require.NoError(t, err)
|
||||
lru.SetUpdateLifetimeOnGet(true)
|
||||
lru.AddWithLifetime("hello", "world", 2*time.Second)
|
||||
time.Sleep(time.Second)
|
||||
lru.Peek("hello")
|
||||
|
@ -82,14 +80,11 @@ func TestPeekWithLifetime(t *testing.T) {
|
|||
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.AddWithLifetime("hello", "world", 10*time.Second)
|
||||
lru.Add("hello1", "")
|
||||
lru.Add("hello2", "")
|
||||
lru.Add("hello3", "")
|
||||
time.Sleep(2 * time.Second)
|
||||
lru.PurgeExpired()
|
||||
require.Equal(t, 0, lru.Len())
|
||||
require.Equal(t, 1, lru.Len())
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue