Skip to content

Commit

Permalink
Delete expired items before setting
Browse files Browse the repository at this point in the history
Check if an item exists and it has expired before setting so that
onEvicted is actually called.

Fixes #48.

Add test and split func

Use nanoseconds instead
  • Loading branch information
jaimem88 committed Oct 13, 2020
1 parent 46f4078 commit 59cc448
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
15 changes: 15 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ func (c *cache) Set(k string, x interface{}, d time.Duration) {
if d > 0 {
e = time.Now().Add(d).UnixNano()
}

// delete before setting and call onEvicted
c.deleteIfExpired(k)

c.mu.Lock()
c.items[k] = Item{
Object: x,
Expand Down Expand Up @@ -922,6 +926,17 @@ func (c *cache) delete(k string) (interface{}, bool) {
return nil, false
}

func (c *cache) deleteIfExpired(k string) {
c.mu.Lock()
i, ok := c.items[k]
c.mu.Unlock()

if ok && i.Expired() {
// delete if expired so .onEvicted is called
c.Delete(k)
}
}

type keyAndValue struct {
key string
value interface{}
Expand Down
33 changes: 33 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1247,6 +1247,39 @@ func TestOnEvicted(t *testing.T) {
}
}

func TestOnEvictedCalledBeforeSet(t *testing.T) {
tc := New(DefaultExpiration, 0)
expiry := 1 * time.Nanosecond

works := false
tc.OnEvicted(func(k string, v interface{}) {
if k == "foo" && v.(int) == 3 {

works = true
}
tc.Set("bar", 4, DefaultExpiration)
})

tc.Set("foo", 3, expiry)
if tc.onEvicted == nil {
t.Fatal("tc.onEvicted is nil")
}

// ensure item expires
time.Sleep(expiry)

// calling Set again should evict expired item
tc.Set("foo", 3, DefaultExpiration)

x, _ := tc.Get("bar")
if !works {
t.Fatal("works bool not true")
}
if x.(int) != 4 {
t.Error("bar was not 4")
}
}

func TestCacheSerialization(t *testing.T) {
tc := New(DefaultExpiration, 0)
testFillAndSerialize(t, tc)
Expand Down

0 comments on commit 59cc448

Please sign in to comment.