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

GetOrSet method to handle case for atomic get and set if not exists #117

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
15 changes: 15 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,21 @@ func (c *cache) Get(k string) (interface{}, bool) {
return item.Object, true
}

// GetOrSet an item from the cache or sets default if not found. Returns the
// existing item or v if none was found, and a bool indicating
// whether the key was found.
func (c *cache) GetOrSet(k string, v interface{}, d time.Duration) (interface{}, bool) {
c.mu.Lock()
item, found := c.get(k)
if !found {
c.set(k, v, d)
c.mu.Unlock()
return v, false
}
c.mu.Unlock()
return item, true
}

// GetWithExpiration returns an item and its expiration time from the cache.
// 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
Expand Down
14 changes: 14 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,20 @@ func TestCache(t *testing.T) {
}
}

func TestGetOrSet(t *testing.T) {
tc := New(DefaultExpiration, 0)

a, found := tc.GetOrSet("a", "v", DefaultExpiration)
if found || a.(string) != "v" {
t.Error("Getting a not found value not equal to default", a)
}

a, found = tc.GetOrSet("a", "v2", DefaultExpiration)
if !found || a.(string) != "v" {
t.Error("Getting a found value not equal to original", a)
}
}

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

Expand Down