eviction callback

add-license-1 v0.0.5
Basit Ali 2022-04-06 15:19:15 +05:00
parent 9b5a155a44
commit 3e79112696
2 changed files with 8 additions and 2 deletions

View File

@ -8,10 +8,13 @@ func (cache *myCache) deleteExpired() {
now := time.Now().UnixNano()
for k, v := range cache.items {
if cache.decisionFunc != nil && !cache.decisionFunc(v) {
if cache.decisionFunc != nil && !cache.decisionFunc(v.data) {
continue
}
if v.expiration > 0 && now > v.expiration {
if cache.onEviction != nil {
cache.onEviction(k, v.data)
}
delete(cache.items, k)
}
}

View File

@ -11,6 +11,7 @@ type myCache struct {
items map[string]*value
expireAfter int64
decisionFunc func(v interface{}) bool
onEviction func(k string, v interface{})
}
func NewCache() Cache {
@ -19,11 +20,13 @@ func NewCache() Cache {
}
}
func NewCacheWithSweeper(interval, expireAfter time.Duration, decisionFunc func(v interface{}) bool) Cache {
func NewCacheWithSweeper(interval, expireAfter time.Duration,
decisionFunc func(v interface{}) bool, onEviction func(k string, v interface{})) Cache {
c := &myCache{
items: make(map[string]*value),
expireAfter: expireAfter.Nanoseconds(),
decisionFunc: decisionFunc,
onEviction: onEviction,
}
if interval > 0 && expireAfter > 0 {