File tree Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
55you may not use this file except in compliance with the License.
66You 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
1010Unless required by applicable law or agreed to in writing, software
1111distributed under the License is distributed on an "AS IS" BASIS,
@@ -22,6 +22,7 @@ import (
2222)
2323
2424type Key = groupcache.Key
25+ type EvictionFunc = func (key Key , value interface {})
2526
2627// Cache is a thread-safe fixed size LRU cache.
2728type 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.
4048func (c * Cache ) Add (key Key , value interface {}) {
4149 c .lock .Lock ()
Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments