diff --git a/layeredbucket.go b/layeredbucket.go index 57676ab..552c877 100644 --- a/layeredbucket.go +++ b/layeredbucket.go @@ -61,6 +61,16 @@ func (b *layeredBucket) delete(primary, secondary string) *Item { return bucket.delete(secondary) } +func (b *layeredBucket) deletePrefix(primary, prefix string, deletables chan *Item) int { + b.RLock() + bucket, exists := b.buckets[primary] + b.RUnlock() + if exists == false { + return 0 + } + return bucket.deletePrefix(prefix, deletables) +} + func (b *layeredBucket) deleteAll(primary string, deletables chan *Item) bool { b.RLock() bucket, exists := b.buckets[primary] diff --git a/layeredcache.go b/layeredcache.go index 65174f5..850af25 100644 --- a/layeredcache.go +++ b/layeredcache.go @@ -149,6 +149,11 @@ func (c *LayeredCache) DeleteAll(primary string) bool { return c.bucket(primary).deleteAll(primary, c.deletables) } +// Deletes all items that share the same primary key and prefix. +func (c *LayeredCache) DeletePrefix(primary, prefix string) int { + return c.bucket(primary).deletePrefix(primary, prefix, c.deletables) +} + //this isn't thread safe. It's meant to be called from non-concurrent tests func (c *LayeredCache) Clear() { for _, bucket := range c.buckets { diff --git a/layeredcache_test.go b/layeredcache_test.go index 2493edb..11e3562 100644 --- a/layeredcache_test.go +++ b/layeredcache_test.go @@ -71,6 +71,30 @@ func (_ *LayeredCacheTests) DeletesAValue() { Expect(cache.ItemCount()).To.Equal(2) } +func (_ *LayeredCacheTests) DeletesAPrefix() { + cache := newLayered() + Expect(cache.ItemCount()).To.Equal(0) + + cache.Set("spice", "aaa", "1", time.Minute) + cache.Set("spice", "aab", "2", time.Minute) + cache.Set("spice", "aac", "3", time.Minute) + cache.Set("leto", "aac", "3", time.Minute) + cache.Set("spice", "ac", "4", time.Minute) + cache.Set("spice", "z5", "7", time.Minute) + Expect(cache.ItemCount()).To.Equal(6) + + Expect(cache.DeletePrefix("spice", "9a")).To.Equal(0) + Expect(cache.ItemCount()).To.Equal(6) + + Expect(cache.DeletePrefix("spice", "aa")).To.Equal(3) + Expect(cache.Get("spice", "aaa")).To.Equal(nil) + Expect(cache.Get("spice", "aab")).To.Equal(nil) + Expect(cache.Get("spice", "aac")).To.Equal(nil) + Expect(cache.Get("spice", "ac").Value()).To.Equal("4") + Expect(cache.Get("spice", "z5").Value()).To.Equal("7") + Expect(cache.ItemCount()).To.Equal(3) +} + func (_ *LayeredCacheTests) OnDeleteCallbackCalled() { onDeleteFnCalled := false