add Rename() support

This commit is contained in:
BugLesser 2022-12-29 13:08:49 +08:00 committed by GitHub
parent 46f4078530
commit 4a10e24f29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 0 deletions

View File

@ -115,6 +115,18 @@ func (c *cache) Replace(k string, x interface{}, d time.Duration) error {
return nil
}
func (c *cache) Rename(oldk, newk string) error {
c.mu.Lock()
defer c.mu.Unlock()
item, found := c.get(oldk)
if !found {
return fmt.Errorf("Item %s doesn't exist", oldk)
}
delete(c.items, oldk)
c.items[newk] = item
return nil
}
// Get an item from the cache. Returns the item or nil, and a bool indicating
// whether the key was found.
func (c *cache) Get(k string) (interface{}, bool) {

View File

@ -1137,6 +1137,19 @@ func TestReplace(t *testing.T) {
}
}
func TestRename(t *testing.T) {
tc := New(DefaultExpiration, 0)
err := tc.Rename("foo", "bar")
if err != nil {
t.Error(err)
}
tc.Set("foo", 123, DefaultExpiration)
err = tc.Rename("foo", "bar")
if err != nil {
t.Error(err)
}
}
func TestDelete(t *testing.T) {
tc := New(DefaultExpiration, 0)
tc.Set("foo", "bar", DefaultExpiration)