Put adds a key to the cache. Eviction occurs when memory is over filled or greater than the specified size in the cache. Keys are evicted randomly from the cache.
(key string)
| 125 | // over filled or greater than the specified size in the cache. |
| 126 | // Keys are evicted randomly from the cache. |
| 127 | func (c *RandReplKeyCache) Put(key string) { |
| 128 | c.lock.Lock() |
| 129 | if _, ok := c.cache[key]; ok { |
| 130 | c.lock.Unlock() |
| 131 | return |
| 132 | } |
| 133 | if len(c.cache) >= c.size { |
| 134 | index := rand.Intn(len(c.keys)) |
| 135 | delete(c.cache, c.keys[index]) |
| 136 | c.keys[index] = key |
| 137 | } else { |
| 138 | c.keys = append(c.keys, key) |
| 139 | } |
| 140 | c.cache[key] = struct{}{} |
| 141 | c.lock.Unlock() |
| 142 | } |
| 143 | |
| 144 | // Len returns the number of keys in the cache. |
| 145 | func (c *RandReplKeyCache) Len() int { |