Skip to content

Commit e6e2171

Browse files
author
Eero Norri
committed
Add Len() to common interface
- implement Len for simple cache
1 parent 9f98378 commit e6e2171

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

cache.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ type Interface[K comparable, V any] interface {
2323
Keys() []K
2424
// Delete deletes the item with provided key from the cache.
2525
Delete(key K)
26+
// Len returns the number of items in the cache.
27+
Len() int
2628
}
2729

2830
var (
@@ -253,6 +255,13 @@ func (c *Cache[K, V]) Delete(key K) {
253255
c.cache.Delete(key)
254256
}
255257

258+
// Len returns the number of items in the cache.
259+
func (c *Cache[K, V]) Len() int {
260+
c.mu.Lock()
261+
defer c.mu.Unlock()
262+
return c.cache.Len()
263+
}
264+
256265
// Contains reports whether key is within cache.
257266
func (c *Cache[K, V]) Contains(key K) bool {
258267
c.mu.Lock()

example_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,16 @@ func ExampleCache_Keys() {
123123
// [a b c]
124124
}
125125

126+
func ExampleCache_Len() {
127+
c := cache.New(cache.AsLFU[string, int]())
128+
c.Set("a", 1)
129+
c.Set("b", 1)
130+
c.Set("c", 1)
131+
fmt.Println(c.Len())
132+
// Output:
133+
// 3
134+
}
135+
126136
func ExampleCache_Contains() {
127137
c := cache.New(cache.AsLRU[string, int]())
128138
c.Set("a", 1)

policy/simple/simple.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,8 @@ func (c *Cache[K, _]) Keys() []K {
5959
func (c *Cache[K, V]) Delete(key K) {
6060
delete(c.items, key)
6161
}
62+
63+
// Len returns the number of items in the cache.
64+
func (c *Cache[K, V]) Len() int {
65+
return len(c.items)
66+
}

0 commit comments

Comments
 (0)