-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
46 lines (38 loc) · 979 Bytes
/
cache.go
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
package flache
import (
"time"
"github.com/cespare/xxhash"
)
type Cache struct {
shards []*shard
shardMask uint64
}
func NewCache() *Cache {
// TODO: use conf
c := &Cache{
shards: make([]*shard, defaultShardSize),
shardMask: defaultShardSize - 1,
}
for i := range c.shards {
c.shards[i] = newShard(defaultCacheSize / defaultShardSize)
}
return c
}
func (c *Cache) Get(key string) ([]byte, error) {
hashedKey := xxhash.Sum64String(key)
shard := c.getShard(hashedKey)
return shard.get(key, hashedKey)
}
func (c *Cache) Set(key string, value []byte, expiration time.Duration) error {
hashedKey := xxhash.Sum64String(key)
shard := c.getShard(hashedKey)
return shard.set(key, hashedKey, value, expiration)
}
func (c *Cache) Del(key string) error {
hashedKey := xxhash.Sum64String(key)
shard := c.getShard(hashedKey)
return shard.del(key, hashedKey)
}
func (c *Cache) getShard(hashedKey uint64) *shard {
return c.shards[hashedKey&c.shardMask]
}