From 89211faa4977810a415afbb18bf9fce44bc363bb Mon Sep 17 00:00:00 2001 From: technicianted Date: Tue, 11 Feb 2020 14:18:06 -0800 Subject: [PATCH] initial --- cache.go | 15 +++++++++++++++ cache_test.go | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/cache.go b/cache.go index db88d2f..ec9d059 100644 --- a/cache.go +++ b/cache.go @@ -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 diff --git a/cache_test.go b/cache_test.go index de3e9d6..87492cb 100644 --- a/cache_test.go +++ b/cache_test.go @@ -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