Skip to content

Commit 3135a7d

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

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

cache/cache.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,7 @@ 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 size of all the elements currently in the cache.
31+
Size() uint64
2932
}

cache/lru/lru.go

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

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)