| 40 | } |
| 41 | |
| 42 | func (c *Cache) Set(ip net.IP, resp Response) { |
| 43 | if c.capacity == 0 { |
| 44 | return |
| 45 | } |
| 46 | k := key(ip) |
| 47 | c.mu.Lock() |
| 48 | defer c.mu.Unlock() |
| 49 | minEvictions := len(c.entries) - c.capacity + 1 |
| 50 | if minEvictions > 0 { // At or above capacity. Shrink the cache |
| 51 | evicted := 0 |
| 52 | for el := c.values.Front(); el != nil && evicted < minEvictions; { |
| 53 | value := el.Value.(Response) |
| 54 | delete(c.entries, key(value.IP)) |
| 55 | next := el.Next() |
| 56 | c.values.Remove(el) |
| 57 | el = next |
| 58 | evicted++ |
| 59 | } |
| 60 | c.evictions += uint64(evicted) |
| 61 | } |
| 62 | current, ok := c.entries[k] |
| 63 | if ok { |
| 64 | c.values.Remove(current) |
| 65 | } |
| 66 | c.entries[k] = c.values.PushBack(resp) |
| 67 | } |
| 68 | |
| 69 | func (c *Cache) Get(ip net.IP) (Response, bool) { |
| 70 | k := key(ip) |