Skip to content

Commit

Permalink
Merge pull request #6 from alanshaw/feat/add-simplelru-resize
Browse files Browse the repository at this point in the history
feat: add simplelru resize
  • Loading branch information
sysulq committed Apr 22, 2020
2 parents 966dd6f + 22ff8c8 commit 82ba7ba
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/hnlq715/golang-lru

go 1.12
13 changes: 13 additions & 0 deletions simplelru/lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,19 @@ func (c *LRU) Len() int {
return c.evictList.Len()
}

// Resize changes the cache size.
func (c *LRU) Resize(size int) (evicted int) {
diff := c.Len() - size
if diff < 0 {
diff = 0
}
for i := 0; i < diff; i++ {
c.removeOldest()
}
c.size = size
return diff
}

// removeOldest removes the oldest item from the cache.
func (c *LRU) removeOldest() {
ent := c.evictList.Back()
Expand Down
39 changes: 39 additions & 0 deletions simplelru/lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,42 @@ func TestLRU_Expire(t *testing.T) {
t.Errorf("1 should not be contained")
}
}

// Test that Resize can upsize and downsize
func TestLRU_Resize(t *testing.T) {
onEvictCounter := 0
onEvicted := func(k interface{}, v interface{}) {
onEvictCounter++
}
l, err := NewLRU(2, onEvicted)
if err != nil {
t.Fatalf("err: %v", err)
}

// Downsize
l.Add(1, 1)
l.Add(2, 2)
evicted := l.Resize(1)
if evicted != 1 {
t.Errorf("1 element should have been evicted: %v", evicted)
}
if onEvictCounter != 1 {
t.Errorf("onEvicted should have been called 1 time: %v", onEvictCounter)
}

l.Add(3, 3)
if l.Contains(1) {
t.Errorf("Element 1 should have been evicted")
}

// Upsize
evicted = l.Resize(2)
if evicted != 0 {
t.Errorf("0 elements should have been evicted: %v", evicted)
}

l.Add(4, 4)
if !l.Contains(3) || !l.Contains(4) {
t.Errorf("Cache should have contained 2 elements")
}
}

0 comments on commit 82ba7ba

Please sign in to comment.