From fec8b64975f952e2fa5fa8478b09dced87f0fa7b Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Fri, 6 Mar 2026 04:43:03 +0800 Subject: internal/lru: Split --- internal/lru/add.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 internal/lru/add.go (limited to 'internal/lru/add.go') diff --git a/internal/lru/add.go b/internal/lru/add.go new file mode 100644 index 00000000..6c055ab5 --- /dev/null +++ b/internal/lru/add.go @@ -0,0 +1,35 @@ +package lru + +// Add inserts or replaces key and marks it most-recently-used. +// +// Add returns false when the entry's weight exceeds MaxWeight even for an empty +// cache. In that case the cache is unchanged. +// +// Add panics if weightFn returns a negative weight. +func (cache *Cache[K, V]) Add(key K, value V) bool { + w := cache.weightFn(key, value) + if w < 0 { + panic("lru: negative entry weight") + } + + if w > cache.maxWeight { + return false + } + + if elem, ok := cache.items[key]; ok { + cache.removeElem(elem) + } + + ent := &entry[K, V]{ + key: key, + value: value, + weight: w, + } + elem := cache.lru.PushBack(ent) + cache.items[key] = elem + cache.weight += w + + cache.evictOverBudget() + + return true +} -- cgit v1.3.1-10-gc9f91