-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcache.go
81 lines (67 loc) · 1.43 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package zizou
import (
"errors"
"time"
)
var (
ERR_INVALID_CONFIG = errors.New("invalid configuration")
)
func isPowerOfTwo(num uint64) bool {
return (num != 0) && ((num & (num - 1)) == 0)
}
type Config struct {
SweepTime time.Duration
ShardSize uint64
}
func (c *Config) Validate() bool {
if c.SweepTime < 0 {
return false
}
if !isPowerOfTwo(c.ShardSize) {
return false
}
return true
}
func New(cnf *Config) (*Cache, error) {
isValid := cnf.Validate()
if !isValid {
return nil, ERR_INVALID_CONFIG
}
nc := &Cache{
shards: make([]*shard, cnf.ShardSize),
hash: newXXHash(),
shardMask: cnf.ShardSize - 1,
}
for i := uint64(0); i < cnf.ShardSize; i++ {
nc.shards[i] = newShardWithSweeper(cnf.SweepTime)
}
return nc, nil
}
type Cache struct {
shards []*shard
hash hasher
shardMask uint64
}
func (c *Cache) getShard(hashedKey uint64) (shard *shard) {
return c.shards[hashedKey&c.shardMask]
}
func (c *Cache) Get(k string) (interface{}, bool) {
hashedKey := c.hash.Sum64(k)
shard := c.getShard(hashedKey)
return shard.Get(k)
}
func (c *Cache) Set(k string, v interface{}, dur time.Duration) error {
hashedKey := c.hash.Sum64(k)
shard := c.getShard(hashedKey)
return shard.Set(k, v, dur)
}
func (c *Cache) Delete(k string) bool {
hashedKey := c.hash.Sum64(k)
shard := c.getShard(hashedKey)
return shard.Delete(k)
}
func (c *Cache) Flush() {
for _, shard := range c.shards {
shard.Flush()
}
}