From 725ab584637a6bedbb22f8a69ad8ebdbe483811f Mon Sep 17 00:00:00 2001 From: ffranr Date: Fri, 7 Nov 2025 13:24:43 +0000 Subject: [PATCH] cache: add `Size` method to LRU cache with test updates --- cache/cache.go | 4 ++++ cache/lru/lru.go | 9 +++++++++ cache/lru/lru_test.go | 4 ++-- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/cache/cache.go b/cache/cache.go index 95d009d74..5702d4fc1 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -26,4 +26,8 @@ type Cache[K comparable, V Value] interface { // Len returns number of elements in the cache. Len() int + + // Size returns the total size of all elements in the cache. It uses + // the same units produced by V.Size(). + Size() uint64 } diff --git a/cache/lru/lru.go b/cache/lru/lru.go index ca35a6741..02b74747e 100644 --- a/cache/lru/lru.go +++ b/cache/lru/lru.go @@ -282,3 +282,12 @@ func (c *Cache[K, V]) RangeFIFO(visitor func(K, V) bool) { } } } + +// Size returns the total size of all elements in the cache. It uses +// the same units produced by V.Size(). +func (c *Cache[K, V]) Size() uint64 { + c.mtx.RLock() + defer c.mtx.RUnlock() + + return c.size +} diff --git a/cache/lru/lru_test.go b/cache/lru/lru_test.go index 775838936..553dffc74 100644 --- a/cache/lru/lru_test.go +++ b/cache/lru/lru_test.go @@ -105,7 +105,7 @@ func TestElementSizeCapacityEvictsEverything(t *testing.T) { c.Put(1, &sizeable{value: 1, size: 1}) c.Put(2, &sizeable{value: 2, size: 2}) c.Put(3, &sizeable{value: 3, size: 3}) - require.Equal(t, c.size, uint64(6)) + require.Equal(t, c.Size(), uint64(6)) // Insert element with size=capacity of cache. c.Put(4, &sizeable{value: 4, size: 6}) @@ -326,7 +326,7 @@ func TestLoadAndDelete(t *testing.T) { // The length should be 0. require.Zero(t, c.Len()) - require.Zero(t, c.size) + require.Zero(t, c.Size()) } // TestRangeIteration checks that the `Range` method works as expected.