Add adds a value to the cache. Returns true if an eviction occurred. Returns false if there was no eviction: the item was already in the cache, or the size was not exceeded.
(key K, value V)
| 116 | // Returns false if there was no eviction: the item was already in the cache, |
| 117 | // or the size was not exceeded. |
| 118 | func (c *LRU[K, V]) Add(key K, value V) (evicted bool) { |
| 119 | c.mu.Lock() |
| 120 | defer c.mu.Unlock() |
| 121 | now := time.Now() |
| 122 | |
| 123 | // Check for existing item |
| 124 | if ent, ok := c.items[key]; ok { |
| 125 | c.evictList.MoveToFront(ent) |
| 126 | c.removeFromBucket(ent) // remove the entry from its current bucket as expiresAt is renewed |
| 127 | ent.Value = value |
| 128 | ent.ExpiresAt = now.Add(c.ttl) |
| 129 | c.addToBucket(ent) |
| 130 | return false |
| 131 | } |
| 132 | |
| 133 | // Add new item |
| 134 | ent := c.evictList.PushFrontExpirable(key, value, now.Add(c.ttl)) |
| 135 | c.items[key] = ent |
| 136 | c.addToBucket(ent) // adds the entry to the appropriate bucket and sets entry.expireBucket |
| 137 | |
| 138 | evict := c.size > 0 && c.evictList.Length() > c.size |
| 139 | // Verify size not exceeded |
| 140 | if evict { |
| 141 | c.removeOldest() |
| 142 | } |
| 143 | return evict |
| 144 | } |
| 145 | |
| 146 | // Get looks up a key's value from the cache. |
| 147 | func (c *LRU[K, V]) Get(key K) (value V, ok bool) { |