Don't delete changed items on original expiry

Use compare and delete to ensure item has not changed before deleting it

Fixes #1
This commit is contained in:
Melon 2024-10-20 22:20:45 +01:00
parent 7e244a930f
commit 112b816e53
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
2 changed files with 21 additions and 1 deletions

View File

@ -116,7 +116,7 @@ func (c *Cache[K, V]) cleaner() {
// remove all expired entries // remove all expired entries
for c.chain != nil && c.chain.HasExpired() { for c.chain != nil && c.chain.HasExpired() {
c.items.Delete(c.chain.data) c.items.CompareAndDelete(c.chain.data, c.chain.item)
c.chain = c.chain.next c.chain = c.chain.next
} }
} }

View File

@ -132,3 +132,23 @@ func TestCache_Cleaner(t *testing.T) {
c.sched.Wait() c.sched.Wait()
assert.Nil(t, c.chain) assert.Nil(t, c.chain)
} }
func TestCache_UpdateExpiry(t *testing.T) {
timeNow = func() time.Time { return time.Now() }
c := New[string, string]()
c.Set("a", "b", time.Now().Add(2*time.Second))
time.Sleep(time.Second)
get, b := c.Get("a")
assert.True(t, b)
assert.Equal(t, "b", get)
c.Set("a", "b", time.Now().Add(5*time.Second))
// after expiry of the first set call
time.Sleep(2 * time.Second)
get, b = c.Get("a")
assert.True(t, b)
assert.Equal(t, "b", get)
}