Skip to content

Commit 725ab58

Browse files
committed
cache: add Size method to LRU cache with test updates
1 parent eb500a6 commit 725ab58

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

cache/cache.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,8 @@ type Cache[K comparable, V Value] interface {
2626

2727
// Len returns number of elements in the cache.
2828
Len() int
29+
30+
// Size returns the total size of all elements in the cache. It uses
31+
// the same units produced by V.Size().
32+
Size() uint64
2933
}

cache/lru/lru.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,3 +282,12 @@ func (c *Cache[K, V]) RangeFIFO(visitor func(K, V) bool) {
282282
}
283283
}
284284
}
285+
286+
// Size returns the total size of all elements in the cache. It uses
287+
// the same units produced by V.Size().
288+
func (c *Cache[K, V]) Size() uint64 {
289+
c.mtx.RLock()
290+
defer c.mtx.RUnlock()
291+
292+
return c.size
293+
}

cache/lru/lru_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ func TestElementSizeCapacityEvictsEverything(t *testing.T) {
105105
c.Put(1, &sizeable{value: 1, size: 1})
106106
c.Put(2, &sizeable{value: 2, size: 2})
107107
c.Put(3, &sizeable{value: 3, size: 3})
108-
require.Equal(t, c.size, uint64(6))
108+
require.Equal(t, c.Size(), uint64(6))
109109

110110
// Insert element with size=capacity of cache.
111111
c.Put(4, &sizeable{value: 4, size: 6})
@@ -326,7 +326,7 @@ func TestLoadAndDelete(t *testing.T) {
326326

327327
// The length should be 0.
328328
require.Zero(t, c.Len())
329-
require.Zero(t, c.size)
329+
require.Zero(t, c.Size())
330330
}
331331

332332
// TestRangeIteration checks that the `Range` method works as expected.

0 commit comments

Comments
 (0)