diff options
| author | 2026-03-06 04:43:03 +0800 | |
|---|---|---|
| committer | 2026-03-06 04:43:03 +0800 | |
| commit | fec8b64975f952e2fa5fa8478b09dced87f0fa7b (patch) | |
| tree | 358cea12d4f20d6821202f040aeb9be58eb878a7 /internal/lru/add.go | |
| parent | format/commitgraph/bloom: Add commit-graph bloom filters (diff) | |
| signature | No signature | |
internal/lru: Split
Diffstat (limited to 'internal/lru/add.go')
| -rw-r--r-- | internal/lru/add.go | 35 |
1 files changed, 35 insertions, 0 deletions
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 +} |
