Compare commits

...

2 Commits
v0.0.6 ... main

2 changed files with 34 additions and 10 deletions

View File

@ -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:

View File

@ -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])
@ -110,11 +128,10 @@ func TestCache_Range(t *testing.T) {
}
func TestCache_Cleaner(t *testing.T) {
timeNow = func() time.Time { return time.Now() }
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)
@ -134,17 +151,17 @@ func TestCache_Cleaner(t *testing.T) {
}
func TestCache_UpdateExpiry(t *testing.T) {
timeNow = func() time.Time { return time.Now() }
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)
@ -154,7 +171,7 @@ func TestCache_UpdateExpiry(t *testing.T) {
}
func TestCache_ClearerDeath(t *testing.T) {
timeNow = func() time.Time { return time.Now() }
timeNow = time.Now
c := New[string, string]()