Add function which increse int64 or set in cache if not exists yet

This commit is contained in:
oskarwojciski 2017-07-12 08:55:53 +02:00
parent 7ac151875f
commit 37630f2f9a
No known key found for this signature in database
GPG Key ID: D8CA6798EEF6DCA8
2 changed files with 59 additions and 0 deletions

View File

@ -589,6 +589,39 @@ func (c *cache) Decrement(k string, n int64) error {
return nil 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 // 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 // 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 // possible to decrement it by n. Pass a negative number to decrement the

View File

@ -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) { func TestOnEvicted(t *testing.T) {
tc := New(DefaultExpiration, 0) tc := New(DefaultExpiration, 0)
tc.Set("foo", 3, DefaultExpiration) tc.Set("foo", 3, DefaultExpiration)