From 37630f2f9a2e9fe1bd004708e45ca500e5de215d Mon Sep 17 00:00:00 2001 From: oskarwojciski Date: Wed, 12 Jul 2017 08:55:53 +0200 Subject: [PATCH] Add function which increse int64 or set in cache if not exists yet --- cache.go | 33 +++++++++++++++++++++++++++++++++ cache_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/cache.go b/cache.go index 30b1ea2..16ed991 100644 --- a/cache.go +++ b/cache.go @@ -589,6 +589,39 @@ func (c *cache) Decrement(k string, n int64) error { return nil } +// Increment an item of type int64 by n. +// If item exists the value incremented is returned +// If the item not exists, then it is created with cache defaultExpiration and initial value = n +// Returns an error if the item's value is not an int64, + +func (c *cache) SetOrIncrement64(k string, n int64) (int64, error) { + c.mu.Lock() + v, found := c.items[k] + if !found || v.Expired() { + var e int64 + d := c.defaultExpiration + if d > 0 { + e = time.Now().Add(d).UnixNano() + } + + c.items[k] = Item{ + Object: int64(0), + Expiration: e, + } + v = c.items[k] + } + rv, ok := v.Object.(int64) + if !ok { + c.mu.Unlock() + return 0, fmt.Errorf("The value for %s is not an int64", k) + } + nv := rv + n + v.Object = nv + c.items[k] = v + c.mu.Unlock() + return nv, nil +} + // Decrement an item of type float32 or float64 by n. Returns an error if the // item's value is not floating point, if it was not found, or if it is not // possible to decrement it by n. Pass a negative number to decrement the diff --git a/cache_test.go b/cache_test.go index 47a3d53..184f92a 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1224,6 +1224,32 @@ func TestDecrementUnderflowUint(t *testing.T) { } } +func TestSetOrIncrement64(t *testing.T) { + tc := New(DefaultExpiration, 0) + tc.SetOrIncrement64("int64", 4) + + x, found := tc.Get("int64") + if !found { + t.Error("int64 not found") + } + + if x.(int64) != 4 { + t.Error("int64 is not 4:", x) + } + + tc.SetOrIncrement64("int64", 4) + + x, found = tc.Get("int64") + if !found { + t.Error("int64 not found") + } + + if x.(int64) != 8 { + t.Error("int64 is not 8:", x) + } + +} + func TestOnEvicted(t *testing.T) { tc := New(DefaultExpiration, 0) tc.Set("foo", 3, DefaultExpiration)