Skip to content

Commit

Permalink
Merge pull request #14 from segmentio/pelletier/resize
Browse files Browse the repository at this point in the history
Resize method
  • Loading branch information
Larry Marburger authored Feb 7, 2022
2 parents 6857a73 + c39efbc commit f3993b5
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
22 changes: 22 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,28 @@ func (cache *Cache) Stats() Stats {
}
}

// Resize the cache to hold at most n entries. If n is smaller than the current
// size, entries are evicted to fit the new size. It errors if n <= 0.
func (cache *Cache) Resize(n int) error {
if n <= 0 {
return errors.New("must supply a positive capacity to Resize")
}

cache.mutex.Lock()
defer cache.mutex.Unlock()
c := cache.capacity
cache.capacity = n

for i := 0; i < c-n; i++ {
successful := cache.evictOldest()
if !successful {
break
}
}

return nil
}

func (cache *Cache) deleteExpired() {
keys := cache.Keys()

Expand Down
31 changes: 31 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,37 @@ func TestActiveExpiration(t *testing.T) {
assert.True(t, duration < time.Millisecond*2)
}

func TestResize(t *testing.T) {
cache := New(Config{
Capacity: 2,
})
cache.Set("a", 1)
cache.Set("b", 1)

cache.Resize(2) // no-op

assert.True(t, cache.Has("a"))
assert.True(t, cache.Has("b"))

cache.Set("c", 1)
assert.False(t, cache.Has("a"))
assert.True(t, cache.Has("b"))
assert.True(t, cache.Has("c"))

cache.Resize(1)
assert.False(t, cache.Has("a"))
assert.False(t, cache.Has("b"))
assert.True(t, cache.Has("c"))

cache.Resize(2)
cache.Set("d", 1)

assert.False(t, cache.Has("a"))
assert.False(t, cache.Has("b"))
assert.True(t, cache.Has("c"))
assert.True(t, cache.Has("d"))
}

func TestStats(t *testing.T) {
t.Run("reports capacity", func(t *testing.T) {
cache := New(Config{Capacity: 100})
Expand Down

0 comments on commit f3993b5

Please sign in to comment.