Skip to content

Commit 96a4323

Browse files
authored
Merge pull request #44 from norri/main
Add Len() to common interface
2 parents 9f98378 + 3621c33 commit 96a4323

File tree

4 files changed

+45
-0
lines changed

4 files changed

+45
-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/example_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package simple_test
22

33
import (
44
"fmt"
5+
"testing"
56

67
"github.com/Code-Hex/go-generics-cache/policy/simple"
78
)
@@ -47,3 +48,23 @@ func ExampleCache_Keys() {
4748
// bar
4849
// baz
4950
}
51+
52+
func BenchmarkLenWithKeys(b *testing.B) {
53+
c := simple.NewCache[string, int]()
54+
c.Set("foo", 1)
55+
c.Set("bar", 2)
56+
c.Set("baz", 3)
57+
for i := 0; i < b.N; i++ {
58+
var _ = len(c.Keys())
59+
}
60+
}
61+
62+
func BenchmarkJustLen(b *testing.B) {
63+
c := simple.NewCache[string, int]()
64+
c.Set("foo", 1)
65+
c.Set("bar", 2)
66+
c.Set("baz", 3)
67+
for i := 0; i < b.N; i++ {
68+
var _ = c.Len()
69+
}
70+
}

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)