Skip to content

Commit

Permalink
fix compact for arm64
Browse files Browse the repository at this point in the history
  • Loading branch information
phuslu committed Feb 20, 2024
1 parent f10746e commit 40e7434
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
29 changes: 19 additions & 10 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ type Cache[K comparable, V any] struct {
group singleflight_Group[K, V]
}

var compactCache = runtime.GOARCH == "amd64"

// New creates lru cache with size capacity.
func New[K comparable, V any](size int, options ...Option[K, V]) *Cache[K, V] {
clocking()
Expand All @@ -45,17 +47,24 @@ func New[K comparable, V any](size int, options ...Option[K, V]) *Cache[K, V] {
c.hasher = maphash_NewHasher[K]().Hash
}

// pre-alloc lists and tables for compactness
shardsize := (uint32(size) + c.mask) / (c.mask + 1)
shardlists := make([]node[K, V], (shardsize+1)*(c.mask+1))
tablesize := newTableSize(uint32(shardsize))
tablebuckets := make([]struct{ hdib, index uint32 }, tablesize*(c.mask+1))

for i := uint32(0); i <= c.mask; i++ {
c.shards[i].list = shardlists[i*(shardsize+1) : (i+1)*(shardsize+1)]
c.shards[i].table.buckets = tablebuckets[i*tablesize : (i+1)*tablesize]
c.shards[i].Init(shardsize)
if compactCache {
// pre-alloc lists and tables for compactness
shardsize := (uint32(size) + c.mask) / (c.mask + 1)
shardlists := make([]node[K, V], (shardsize+1)*(c.mask+1))
tablesize := newTableSize(uint32(shardsize))
tablebuckets := make([]struct{ hdib, index uint32 }, tablesize*(c.mask+1))
for i := uint32(0); i <= c.mask; i++ {
c.shards[i].list = shardlists[i*(shardsize+1) : (i+1)*(shardsize+1)]
c.shards[i].table.buckets = tablebuckets[i*tablesize : (i+1)*tablesize]
c.shards[i].Init(shardsize)
}
} else {
shardsize := (uint32(size) + c.mask) / (c.mask + 1)
for i := uint32(0); i <= c.mask; i++ {
c.shards[i].Init(shardsize)
}
}

return c
}

Expand Down
15 changes: 15 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ import (
"time"
)

func TestCacheCompactCache(t *testing.T) {
compact := compactCache
defer func() {
compactCache = compact
}()

for _, b := range []bool{true, false} {
compactCache = b
cache := New[string, []byte](32 * 1024)
if length := cache.Len(); length != 0 {
t.Fatalf("bad cache length: %v", length)
}
}
}

func TestCacheDefaultkey(t *testing.T) {
cache := New[string, int](1)
var k string
Expand Down

0 comments on commit 40e7434

Please sign in to comment.