Fix LRU to correct evict cache items when replaced (#52)

This commit is contained in:
Matt Harrison 2022-12-20 10:31:47 -05:00 committed by GitHub
parent 2bec0534cf
commit a139af4144
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 46 additions and 1 deletions

View File

@ -535,3 +535,18 @@ func TestContextDeadlineOnPeer(t *testing.T) {
}
}
}
func TestCacheRemovesBytesOfReplacedValues(t *testing.T) {
c := cache{}
const key = "test"
keyLen := len(key)
for _, bytes := range []int{100, 1000, 2000} {
c.add(key, ByteView{b: make([]byte, bytes)})
expected := int64(bytes + keyLen)
if c.nbytes != expected {
t.Fatalf("%s: expected %d was %d", t.Name(), expected, c.nbytes)
}
}
}

View File

@ -63,8 +63,12 @@ func (c *Cache) Add(key Key, value interface{}, expire time.Time) {
c.ll = list.New()
}
if ee, ok := c.cache[key]; ok {
eee := ee.Value.(*entry)
if c.OnEvicted != nil {
c.OnEvicted(key, eee.value)
}
c.ll.MoveToFront(ee)
ee.Value.(*entry).value = value
eee.value = value
return
}
ele := c.ll.PushFront(&entry{key, value, expire})

View File

@ -46,6 +46,32 @@ var getTests = []struct {
complexStruct{1, simpleStruct{2, "three"}}, true},
}
func TestAdd_evictsOldAndReplaces(t *testing.T) {
var evictedKey Key
var evictedValue interface{}
lru := New(0)
lru.OnEvicted = func(key Key, value interface{}) {
evictedKey = key
evictedValue = value
}
lru.Add("myKey", 1234, time.Time{})
lru.Add("myKey", 1235, time.Time{})
newVal, ok := lru.Get("myKey")
if !ok {
t.Fatalf("%s: cache hit = %v; want %v", t.Name(), ok, !ok)
}
if newVal != 1235 {
t.Fatalf("%s: cache hit = %v; want %v", t.Name(), newVal, 1235)
}
if evictedKey != "myKey" {
t.Fatalf("%s: evictedKey = %v; want %v", t.Name(), evictedKey, "myKey")
}
if evictedValue != 1234 {
t.Fatalf("%s: evictedValue = %v; want %v", t.Name(), evictedValue, 1234)
}
}
func TestGet(t *testing.T) {
for _, tt := range getTests {
lru := New(0)