-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsharded.go
More file actions
54 lines (45 loc) · 1.2 KB
/
sharded.go
File metadata and controls
54 lines (45 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package loadingcache
import (
"context"
"fmt"
"github.com/devzero-inc/loadingcache/stats"
"github.com/pkg/errors"
)
type shardedCache[Key comparable, Value any] struct {
cacheOptions[Key, Value]
shards []Cache[Key, Value]
}
func (s *shardedCache[K, V]) Get(ctx context.Context, key K) (V, error) {
val, err := s.shards[s.hashCodeFunc(key)%uint64(len(s.shards))].Get(ctx, key)
return val, errors.Wrap(err, "")
}
func (s *shardedCache[K, V]) Put(key K, value V) {
s.shards[s.hashCodeFunc(key)%uint64(len(s.shards))].Put(key, value)
}
func (s *shardedCache[K, V]) Invalidate(keys ...K) {
for _, k := range keys {
s.shards[s.hashCodeFunc(k)%uint64(len(s.shards))].Invalidate(k)
}
}
func (s *shardedCache[K, V]) InvalidateAll() {
for _, shard := range s.shards {
shard.InvalidateAll()
}
}
func (s *shardedCache[K, V]) Close() {
for _, shard := range s.shards {
shard.Close()
}
}
func (s *shardedCache[K, V]) Stats() Stats {
statsSum := &stats.InternalStats{}
for _, shard := range s.shards {
switch typedCache := shard.(type) {
case *genericCache[K, V]:
statsSum = statsSum.Add(typedCache.stats)
default:
panic(fmt.Sprintf("unsupported cache type %T", shard))
}
}
return statsSum
}