From 7316f99bd9594707f19ba285574adb3038e93fda Mon Sep 17 00:00:00 2001 From: Karl Seguin Date: Thu, 13 Nov 2014 22:23:52 +0700 Subject: [PATCH] replace on layeredcache --- layeredbucket.go | 10 ++++++++++ layeredcache.go | 4 ++++ layeredcache_test.go | 16 ++++++++++++---- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/layeredbucket.go b/layeredbucket.go index 6a443bf..0934437 100644 --- a/layeredbucket.go +++ b/layeredbucket.go @@ -35,6 +35,16 @@ func (b *LayeredBucket) set(primary, secondary string, value interface{}, durati return item, new } +func (b *LayeredBucket) replace(primary, secondary string, value interface{}) bool { + b.Lock() + bucket, exists := b.buckets[primary] + b.Unlock() + if exists == false { + return false + } + return bucket.replace(secondary, value) +} + func (b *LayeredBucket) delete(primary, secondary string) *Item { b.RLock() bucket, exists := b.buckets[primary] diff --git a/layeredcache.go b/layeredcache.go index 0b04062..b04be74 100644 --- a/layeredcache.go +++ b/layeredcache.go @@ -65,6 +65,10 @@ func (c *LayeredCache) Set(primary, secondary string, value interface{}, duratio } } +func (c *LayeredCache) Replace(primary, secondary string, value interface{}) bool { + return c.bucket(primary).replace(primary, secondary, value) +} + func (c *LayeredCache) Fetch(primary, secondary string, duration time.Duration, fetch func() (interface{}, error)) (interface{}, error) { item := c.Get(primary, secondary) if item != nil { diff --git a/layeredcache_test.go b/layeredcache_test.go index a576d10..32162fb 100644 --- a/layeredcache_test.go +++ b/layeredcache_test.go @@ -39,6 +39,18 @@ func (l *LayeredCacheTests) SetsMultipleValueWithinTheSameLayer() { Expect(cache.Get("baron", "friend")).To.Equal(nil) } +func (l *LayeredCacheTests) ReplaceDoesNothingIfKeyDoesNotExist() { + cache := newLayered() + Expect(cache.Replace("spice", "flow", "value-a")).To.Equal(false) +} + +func (l *LayeredCacheTests) ReplaceUpdatesTheValue() { + cache := newLayered() + cache.Set("spice", "flow", "value-a", time.Minute) + Expect(cache.Replace("spice", "flow", "value-b")).To.Equal(true) + Expect(cache.Get("spice", "flow").Value().(string)).To.Equal("value-b") +} + func (l *LayeredCacheTests) DeletesAValue() { cache := newLayered() cache.Set("spice", "flow", "value-a", time.Minute) @@ -125,10 +137,6 @@ func (c *LayeredCacheTests) RemovesOldestItemWhenFull() { Expect(cache.Get("xx", "b").Value()).To.Equal(9001) } -// func (c *LayeredCacheTests) GetsAnExpiredIten() { - -// } - func newLayered() *LayeredCache { return Layered(Configure()) }