From 243f5c8219a70b5b0b19880260731083a6b273f0 Mon Sep 17 00:00:00 2001 From: Alexej Kubarev Date: Sun, 25 Nov 2018 15:31:09 -0800 Subject: [PATCH] Fixes #21. Callong OnDelete during gc() --- cache.go | 3 +++ cache_test.go | 10 +++++++++- secondarycache_test.go | 6 +++--- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/cache.go b/cache.go index 4d89a9f..d8d74ed 100644 --- a/cache.go +++ b/cache.go @@ -223,6 +223,9 @@ func (c *Cache) gc() { c.bucket(item.key).delete(item.key) c.size -= item.size c.list.Remove(element) + if c.onDelete != nil { + c.onDelete(item) + } item.promotions = -2 } element = prev diff --git a/cache_test.go b/cache_test.go index 8c56189..bcbefaa 100644 --- a/cache_test.go +++ b/cache_test.go @@ -98,7 +98,14 @@ func (_ CacheTests) TrackerDoesNotCleanupHeldInstance() { } func (_ CacheTests) RemovesOldestItemWhenFull() { - cache := New(Configure().MaxSize(5).ItemsToPrune(1)) + onDeleteFnCalled := false + onDeleteFn := func(item *Item) { + if item.key == "0" { + onDeleteFnCalled = true + } + } + + cache := New(Configure().MaxSize(5).ItemsToPrune(1).OnDelete(onDeleteFn)) for i := 0; i < 7; i++ { cache.Set(strconv.Itoa(i), i, time.Minute) } @@ -106,6 +113,7 @@ func (_ CacheTests) RemovesOldestItemWhenFull() { Expect(cache.Get("0")).To.Equal(nil) Expect(cache.Get("1")).To.Equal(nil) Expect(cache.Get("2").Value()).To.Equal(2) + Expect(onDeleteFnCalled).To.Equal(true) } func (_ CacheTests) RemovesOldestItemWhenFullBySizer() { diff --git a/secondarycache_test.go b/secondarycache_test.go index 7065c23..fa1f891 100644 --- a/secondarycache_test.go +++ b/secondarycache_test.go @@ -2,9 +2,9 @@ package ccache import ( . "github.com/karlseguin/expect" + "strconv" "testing" "time" - "strconv" ) type SecondaryCacheTests struct{} @@ -77,14 +77,14 @@ func (_ SecondaryCacheTests) FetchReturnsAnExistingValue() { cache := newLayered() cache.Set("spice", "flow", "value-a", time.Minute) sCache := cache.GetOrCreateSecondaryCache("spice") - val, _ := sCache.Fetch("flow", time.Minute, func() (interface{}, error) {return "a fetched value", nil}) + val, _ := sCache.Fetch("flow", time.Minute, func() (interface{}, error) { return "a fetched value", nil }) Expect(val.Value().(string)).To.Equal("value-a") } func (_ SecondaryCacheTests) FetchReturnsANewValue() { cache := newLayered() sCache := cache.GetOrCreateSecondaryCache("spice") - val, _ := sCache.Fetch("flow", time.Minute, func() (interface{}, error) {return "a fetched value", nil}) + val, _ := sCache.Fetch("flow", time.Minute, func() (interface{}, error) { return "a fetched value", nil }) Expect(val.Value().(string)).To.Equal("a fetched value") }