Skip to content

Commit

Permalink
Merge pull request #44 from norri/main
Browse files Browse the repository at this point in the history
Add Len() to common interface
  • Loading branch information
Code-Hex committed Apr 13, 2024
2 parents 9f98378 + 3621c33 commit 96a4323
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ type Interface[K comparable, V any] interface {
Keys() []K
// Delete deletes the item with provided key from the cache.
Delete(key K)
// Len returns the number of items in the cache.
Len() int
}

var (
Expand Down Expand Up @@ -253,6 +255,13 @@ func (c *Cache[K, V]) Delete(key K) {
c.cache.Delete(key)
}

// Len returns the number of items in the cache.
func (c *Cache[K, V]) Len() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.cache.Len()
}

// Contains reports whether key is within cache.
func (c *Cache[K, V]) Contains(key K) bool {
c.mu.Lock()
Expand Down
10 changes: 10 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ func ExampleCache_Keys() {
// [a b c]
}

func ExampleCache_Len() {
c := cache.New(cache.AsLFU[string, int]())
c.Set("a", 1)
c.Set("b", 1)
c.Set("c", 1)
fmt.Println(c.Len())
// Output:
// 3
}

func ExampleCache_Contains() {
c := cache.New(cache.AsLRU[string, int]())
c.Set("a", 1)
Expand Down
21 changes: 21 additions & 0 deletions policy/simple/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package simple_test

import (
"fmt"
"testing"

"github.com/Code-Hex/go-generics-cache/policy/simple"
)
Expand Down Expand Up @@ -47,3 +48,23 @@ func ExampleCache_Keys() {
// bar
// baz
}

func BenchmarkLenWithKeys(b *testing.B) {
c := simple.NewCache[string, int]()
c.Set("foo", 1)
c.Set("bar", 2)
c.Set("baz", 3)
for i := 0; i < b.N; i++ {
var _ = len(c.Keys())
}
}

func BenchmarkJustLen(b *testing.B) {
c := simple.NewCache[string, int]()
c.Set("foo", 1)
c.Set("bar", 2)
c.Set("baz", 3)
for i := 0; i < b.N; i++ {
var _ = c.Len()
}
}
5 changes: 5 additions & 0 deletions policy/simple/simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,8 @@ func (c *Cache[K, _]) Keys() []K {
func (c *Cache[K, V]) Delete(key K) {
delete(c.items, key)
}

// Len returns the number of items in the cache.
func (c *Cache[K, V]) Len() int {
return len(c.items)
}

0 comments on commit 96a4323

Please sign in to comment.