Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util/kvcache: enhance kvcache (#24242) #25299

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion util/kvcache/simple_lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ type SimpleLRUCache struct {
quota uint64
guard float64
elements map[string]*list.Element
cache *list.List

// onEvict function will be called if any eviction happened
onEvict func(Key, Value)
cache *list.List
}

// NewSimpleLRUCache creates a SimpleLRUCache object, whose capacity is "capacity".
Expand All @@ -72,10 +75,16 @@ func NewSimpleLRUCache(capacity uint, guard float64, quota uint64) *SimpleLRUCac
quota: quota,
guard: guard,
elements: make(map[string]*list.Element),
onEvict: nil,
cache: list.New(),
}
}

// SetOnEvict set the function called on each eviction.
func (l *SimpleLRUCache) SetOnEvict(onEvict func(Key, Value)) {
l.onEvict = onEvict
}

// Get tries to find the corresponding value according to the given key.
func (l *SimpleLRUCache) Get(key Key) (value Value, ok bool) {
element, exists := l.elements[string(key.Hash())]
Expand Down Expand Up @@ -125,6 +134,11 @@ func (l *SimpleLRUCache) Put(key Key, value Value) {
if lru == nil {
break
}

if l.onEvict != nil {
l.onEvict(lru.Value.(*cacheEntry).key, lru.Value.(*cacheEntry).value)
}

l.cache.Remove(lru)
delete(l.elements, string(lru.Value.(*cacheEntry).key.Hash()))
l.size--
Expand Down
7 changes: 7 additions & 0 deletions util/kvcache/simple_lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ func (s *testLRUCacheSuite) TestPut(c *C) {

keys := make([]*mockCacheKey, 5)
vals := make([]int64, 5)
droppedKv := make(map[Key]Value)

lru.SetOnEvict(func(key Key, value Value) {
droppedKv[key] = value
})
for i := 0; i < 5; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
Expand All @@ -73,10 +77,12 @@ func (s *testLRUCacheSuite) TestPut(c *C) {
c.Assert(lru.size, Equals, uint(3))

// test for non-existent elements
c.Assert(len(droppedKv), Equals, 2)
for i := 0; i < 2; i++ {
element, exists := lru.elements[string(keys[i].Hash())]
c.Assert(exists, IsFalse)
c.Assert(element, IsNil)
c.Assert(droppedKv[keys[i]], Equals, vals[i])
}

// test for existent elements
Expand Down Expand Up @@ -104,6 +110,7 @@ func (s *testLRUCacheSuite) TestPut(c *C) {

root = root.Next()
}

// test for end of double-linked list
c.Assert(root, IsNil)
}
Expand Down