From 267e895bd89e429586b9a3b26c2c25f7eef4c159 Mon Sep 17 00:00:00 2001 From: MrMelon54 Date: Thu, 6 Feb 2025 20:16:53 +0000 Subject: [PATCH] Change Set to accept time.Duration and move the original function to SetAbs b --- cache.go | 11 +++++++++-- cache_test.go | 27 ++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/cache.go b/cache.go index e0b4929..5201590 100644 --- a/cache.go +++ b/cache.go @@ -193,10 +193,17 @@ func (c *Cache[K, V]) SetPermanent(key K, value V) { c.items.Store(key, i) } -// Set adds an item to the cache with an expiry date. +// Set adds an item to the cache with an expiry duration. // // If an item is added with the same key then this item with be overwritten. -func (c *Cache[K, V]) Set(key K, value V, expires time.Time) { +func (c *Cache[K, V]) Set(key K, value V, expires time.Duration) { + c.SetAbs(key, value, timeNow().Add(expires)) +} + +// SetAbs adds an item to the cache with an expiry date. +// +// If an item is added with the same key then this item with be overwritten. +func (c *Cache[K, V]) SetAbs(key K, value V, expires time.Time) { // if the cache is closed then just return select { case <-c.close: diff --git a/cache_test.go b/cache_test.go index 7c94f0e..f420b8e 100644 --- a/cache_test.go +++ b/cache_test.go @@ -71,8 +71,26 @@ func TestCache_SetPermanent(t *testing.T) { } func TestCache_Set(t *testing.T) { + timeNow = func() time.Time { return time.Date(nextYear, time.January, 1, 0, 0, 0, 0, time.UTC) } + c := New[string, string]() - c.Set("a", "b", time.Date(nextYear, time.January, 1, 0, 0, 0, 0, time.UTC)) + c.Set("a", "b", 5*time.Minute) + + value, ok := c.items.Load("a") + v := value.(*item[string]) + assert.Equal(t, item[string]{ + data: "b", + expires: timeNow().Add(5 * time.Minute), + }, *v) + assert.True(t, ok) + + value, ok = c.items.Load("b") + assert.False(t, ok) +} + +func TestCache_SetAbs(t *testing.T) { + c := New[string, string]() + c.SetAbs("a", "b", time.Date(nextYear, time.January, 1, 0, 0, 0, 0, time.UTC)) value, ok := c.items.Load("a") v := value.(*item[string]) @@ -112,9 +130,8 @@ func TestCache_Range(t *testing.T) { func TestCache_Cleaner(t *testing.T) { timeNow = time.Now - n := time.Now().Add(2 * time.Second) c := New[string, string]() - c.Set("a", "b", n) + c.Set("a", "b", 2*time.Second) // check before expiry time.Sleep(time.Second) @@ -137,14 +154,14 @@ func TestCache_UpdateExpiry(t *testing.T) { timeNow = time.Now c := New[string, string]() - c.Set("a", "b", time.Now().Add(2*time.Second)) + c.Set("a", "b", 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)) + c.Set("a", "b", 5*time.Second) // after expiry of the first set call time.Sleep(2 * time.Second)