Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add GetWithExpirationUpdate #96

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,38 @@ func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) {
return item.Object, time.Time{}, true
}

// GetWithExpirationUpdate returns item and updates its cache expiration time
// It returns the item or nil, the expiration time if one is set (if the item
// never expires a zero value for time.Time is returned), and a bool indicating
// whether the key was found.
func (c *cache) GetWithExpirationUpdate(k string, d time.Duration) (interface{}, bool) {
c.mu.RLock()
item, found := c.items[k]
if !found {
c.mu.RUnlock()
return nil, false
}
if item.Expiration > 0 {
if time.Now().UnixNano() > item.Expiration {
c.mu.RUnlock()
return nil, false
}
}
c.mu.RUnlock()

c.mu.Lock()
if d == DefaultExpiration {
d = c.defaultExpiration
}
if d > 0 {
item.Expiration = time.Now().Add(d).UnixNano()
}
c.items[k] = item
c.mu.Unlock()

return item.Object, true
}

func (c *cache) get(k string) (interface{}, bool) {
item, found := c.items[k]
if !found {
Expand Down
25 changes: 25 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1769,3 +1769,28 @@ func TestGetWithExpiration(t *testing.T) {
t.Error("expiration for e is in the past")
}
}

func TestGetWithExpirationUpdate(t *testing.T) {
var found bool

tc := New(50*time.Millisecond, 1*time.Millisecond)
tc.Set("a", 1, DefaultExpiration)

<-time.After(25 * time.Millisecond)
_, found = tc.GetWithExpirationUpdate("a", DefaultExpiration)
if !found {
t.Error("item `a` not expired yet")
}

<-time.After(25 * time.Millisecond)
_, found = tc.Get("a")
if !found {
t.Error("item `a` not expired yet")
}

<-time.After(30 * time.Millisecond)
_, found = tc.Get("a")
if found {
t.Error("Found `a` when it should have been automatically deleted")
}
}