A cache's capacity is not always fixed for life. Today you let the LRU cache change capacity on the fly, evicting the least-recently-used entries when it shrinks below its current size and simply raising the ceiling when it grows.
Change the cache's capacity, evicting down to the new size when shrinking.
Capacity is not sacred - a running system may want to give a hot cache more room or
claw memory back under pressure. Resizing down is the interesting direction:
if the cache currently holds more entries than the new capacity allows, it must
evict the excess, and it does so the same way every other eviction works - from the
least-recently-used end, calling removeTail until it fits. Shrinking a cache of
three to a capacity of two drops exactly one entry, the coldest.
Resizing up is trivial: nothing needs evicting, so you just raise the ceiling and
let future Puts fill the new space. The one detail to get right is order - evict
first, then set the new cap - and to reuse removeTail rather than inventing a
second eviction path, so the recency rule stays in one place. With resize in hand,
the cache adapts to a changing memory budget without ever violating its own
invariant that Len never exceeds Cap.
func (c *LRU) Resize(newCap int) {for len(c.data) > newCap { c.removeTail() } // shed the LRU end firstc.cap = newCap}