1
0

Added Add and Replace commands

This commit is contained in:
Patrick Mylund Nielsen 2012-01-02 14:04:47 +01:00
parent 2a304e4c5c
commit a78bca69e4
2 changed files with 51 additions and 2 deletions

View File

@ -108,8 +108,8 @@ type janitor struct {
stop chan bool
}
// Adds an item to the cache. If the duration is 0, the cache's default expiration time
// is used. If it is -1, the item never expires.
// Adds an item to the cache, replacing any existing item. If the duration is 0, the
// cache's default expiration time is used. If it is -1, the item never expires.
func (c *cache) Set(k string, x interface{}, d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
@ -132,6 +132,30 @@ func (c *cache) Set(k string, x interface{}, d time.Duration) {
}
}
// TODO: Add and Replace aren't completely atomic
// Adds an item to the cache only if an item doesn't already exist for the given key,
// or if the existing item has expired. Returns an error if not.
func (c *cache) Add(k string, x interface{}, d time.Duration) error {
_, found := c.Get(k)
if found {
return fmt.Errorf("Item %s already exists", k)
}
c.Set(k, x, d)
return nil
}
// Sets a new value for the cache item only if it already exists. Returns an error if
// it does not.
func (c *cache) Replace(k string, x interface{}, d time.Duration) error {
_, found := c.Get(k)
if !found {
return fmt.Errorf("Item %s doesn't exist", k)
}
c.Set(k, x, d)
return nil
}
// Gets an item from the cache.
func (c *cache) Get(k string) (interface{}, bool) {
c.mu.Lock()

View File

@ -349,3 +349,28 @@ func TestDecrementInt64(t *testing.T) {
t.Error("int64 is not 3:", x)
}
}
func TestAdd(t *testing.T) {
tc := New(0, 0)
err := tc.Add("foo", "bar", 0)
if err != nil {
t.Error("Couldn't add foo even though it shouldn't exist")
}
err = tc.Add("foo", "baz", 0)
if err == nil {
t.Error("Successfully added another foo when it should have returned an error")
}
}
func TestReplace(t *testing.T) {
tc := New(0, 0)
err := tc.Replace("foo", "bar", 0)
if err == nil {
t.Error("Replaced foo when it shouldn't exist")
}
tc.Set("foo", "bar", 0)
err = tc.Replace("foo", "bar", 0)
if err != nil {
t.Error("Couldn't replace existing key foo")
}
}