added replace method

This commit is contained in:
Karl Seguin 2014-11-13 22:20:12 +07:00
parent 7e08960075
commit cc0395a391
4 changed files with 36 additions and 0 deletions

View file

@ -30,6 +30,17 @@ func (b *Bucket) set(key string, value interface{}, duration time.Duration) (*It
return item, true
}
func (b *Bucket) replace(key string, value interface{}) bool {
b.Lock()
defer b.Unlock()
existing, exists := b.lookup[key]
if exists == false {
return false
}
existing.value = value
return true
}
func (b *Bucket) delete(key string) *Item {
b.Lock()
defer b.Unlock()

View file

@ -48,6 +48,18 @@ func (b *BucketTests) SetsAnExistingItem() {
Expect(new).To.Equal(false)
}
func (b *BucketTests) ReplaceDoesNothingIfKeyDoesNotExist() {
bucket := testBucket()
item, _ := bucket.set("power", TestValue("9002"), time.Minute)
Expect(bucket.replace("power", TestValue("9004"))).To.Equal(true)
Expect(item.Value().(string)).To.Equal("9004")
}
func (b *BucketTests) ReplaceReplacesThevalue() {
bucket := testBucket()
Expect(bucket.replace("power", TestValue("9002"))).To.Equal(false)
}
func testBucket() *Bucket {
b := &Bucket{lookup: make(map[string]*Item)}
b.lookup["power"] = &Item{

View file

@ -65,6 +65,10 @@ func (c *Cache) Set(key string, value interface{}, duration time.Duration) {
}
}
func (c *Cache) Replace(key string, value interface{}) bool {
return c.bucket(key).replace(key, value)
}
func (c *Cache) Fetch(key string, duration time.Duration, fetch func() (interface{}, error)) (interface{}, error) {
item := c.Get(key)
if item != nil {

View file

@ -92,6 +92,15 @@ cache.Delete("user:4")
### Extend
The life of an item can be changed via the `Extend` method. This will change the expiry of the item by the specified duration relative to the current time.
### Replace
The value of an item can be updated to a new value without renewing the item's TTL or it's position in the LRU:
```go
cache.Replace("user:4", user)
```
`Replace` returns true if the item existed (and thus was replaced). In the case where the key was not in the cache, the value *is not* inserted and false is returned.
## Tracking
CCache supports a special tracking mode which is meant to be used in conjunction with other pieces of your code that maintains a long-lived reference to data.