cache: Fix memory leak

Slices never shrink.
This commit is contained in:
Martin Polden 2020-09-07 22:40:06 +02:00
parent 971c0e11f4
commit bd8b1c7b97
1 changed files with 10 additions and 6 deletions

View File

@ -1,6 +1,7 @@
package http package http
import ( import (
"container/list"
"hash/fnv" "hash/fnv"
"net" "net"
"sync" "sync"
@ -10,17 +11,18 @@ type Cache struct {
capacity int capacity int
mu sync.RWMutex mu sync.RWMutex
entries map[uint64]Response entries map[uint64]Response
keys []uint64 keys *list.List
} }
func NewCache(capacity int) *Cache { func NewCache(capacity int) *Cache {
if capacity < 0 { if capacity < 0 {
capacity = 0 capacity = 0
} }
keys := list.New()
return &Cache{ return &Cache{
capacity: capacity, capacity: capacity,
entries: make(map[uint64]Response), entries: make(map[uint64]Response),
keys: make([]uint64, 0, capacity), keys: keys,
} }
} }
@ -37,12 +39,14 @@ func (c *Cache) Set(ip net.IP, resp Response) {
k := key(ip) k := key(ip)
c.mu.Lock() c.mu.Lock()
defer c.mu.Unlock() defer c.mu.Unlock()
if len(c.entries) == c.capacity && c.capacity > 0 { if len(c.entries) == c.capacity {
delete(c.entries, c.keys[0]) // At capacity. Remove the oldest entry
c.keys = c.keys[1:] oldest := c.keys.Front()
delete(c.entries, oldest.Value.(uint64))
c.keys.Remove(oldest)
} }
c.entries[k] = resp c.entries[k] = resp
c.keys = append(c.keys, k) c.keys.PushBack(k)
} }
func (c *Cache) Get(ip net.IP) (Response, bool) { func (c *Cache) Get(ip net.IP) (Response, bool) {