Skip to content

Commit a36077c

Browse files
authored
Merge pull request #275 from enj/enj/f/lru_eviction
lru: add support for setting eviction func
2 parents 3401372 + 22082ee commit a36077c

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

lru/lru.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
55
you may not use this file except in compliance with the License.
66
You may obtain a copy of the License at
77
8-
http://www.apache.org/licenses/LICENSE-2.0
8+
http://www.apache.org/licenses/LICENSE-2.0
99
1010
Unless required by applicable law or agreed to in writing, software
1111
distributed under the License is distributed on an "AS IS" BASIS,
@@ -22,6 +22,7 @@ import (
2222
)
2323

2424
type Key = groupcache.Key
25+
type EvictionFunc = func(key Key, value interface{})
2526

2627
// Cache is a thread-safe fixed size LRU cache.
2728
type Cache struct {
@@ -36,6 +37,13 @@ func New(size int) *Cache {
3637
}
3738
}
3839

40+
// NewWithEvictionFunc creates an LRU of the given size with the given eviction func.
41+
func NewWithEvictionFunc(size int, f EvictionFunc) *Cache {
42+
c := New(size)
43+
c.cache.OnEvicted = f
44+
return c
45+
}
46+
3947
// Add adds a value to the cache.
4048
func (c *Cache) Add(key Key, value interface{}) {
4149
c.lock.Lock()

lru/lru_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,20 @@ func TestGetRace(t *testing.T) {
113113
// let them run
114114
time.Sleep(5 * time.Second)
115115
}
116+
117+
func TestEviction(t *testing.T) {
118+
var seenKey Key
119+
var seenVal interface{}
120+
121+
lru := NewWithEvictionFunc(1, func(key Key, value interface{}) {
122+
seenKey = key
123+
seenVal = value
124+
})
125+
126+
lru.Add(1, 2)
127+
lru.Add(3, 4)
128+
129+
if seenKey != 1 || seenVal != 2 {
130+
t.Errorf("unexpected eviction data: key=%v val=%v", seenKey, seenVal)
131+
}
132+
}

0 commit comments

Comments
 (0)