Skip to content

Commit

Permalink
add Size method on cache
Browse files Browse the repository at this point in the history
  • Loading branch information
nlachfr committed Aug 19, 2024
1 parent 5a347aa commit 038e932
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ func (c *Cache[K, V]) Len() int {
return c.store.Len()
}

// Size returns the used size of the cache.
func (c *Cache[K, V]) Size() int {
return c.store.Size()
}

// Close closes all goroutines created by cache.
func (c *Cache[K, V]) Close() {
c.store.Close()
Expand Down Expand Up @@ -126,6 +131,11 @@ func (c *LoadingCache[K, V]) Len() int {
return c.store.Len()
}

// Size returns the used size of the cache.
func (c *LoadingCache[K, V]) Size() int {
return c.store.Size()
}

// SaveCache save cache data to writer.
func (c *LoadingCache[K, V]) SaveCache(version uint64, writer io.Writer) error {
return c.store.Persist(version, writer)
Expand Down
4 changes: 4 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ func TestCost(t *testing.T) {
}
time.Sleep(time.Second)
require.True(t, client.Len() == 25)
require.True(t, client.Size() == 500)

// test cost func
builder := theine.NewBuilder[string, string](500)
Expand All @@ -243,6 +244,7 @@ func TestCost(t *testing.T) {
}
time.Sleep(time.Second)
require.True(t, client.Len() == 25)
require.True(t, client.Size() == 500)
client.Close()
}

Expand All @@ -256,12 +258,14 @@ func TestCostUpdate(t *testing.T) {
}
time.Sleep(time.Second)
require.True(t, client.Len() == 25)
require.True(t, client.Size() == 500)
// update cost
success := client.Set("key:10", "", 200)
require.True(t, success)
time.Sleep(time.Second)
// 15 * 20 + 200
require.True(t, client.Len() == 16)
require.True(t, client.Size() == 15*20+200)
client.Close()
}

Expand Down
13 changes: 13 additions & 0 deletions internal/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,19 @@ func (s *Store[K, V]) Len() int {
return total
}

func (s *Store[K, V]) Size() int {
total := 0
for _, s := range s.shards {
tk := s.mu.RLock()
for _, entry := range s.hashmap {
total += int(entry.cost.Load())
}
s.mu.RUnlock(tk)
}
return total
}

// spread hash before get index
func (s *Store[K, V]) index(key K) (uint64, int) {
base := s.hasher.hash(key)
return base, int(base & uint64(s.shardCount-1))
Expand Down

0 comments on commit 038e932

Please sign in to comment.