-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
53 lines (45 loc) · 988 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
47
48
49
50
51
52
53
package perp
import (
"errors"
"sync"
)
type Cache[K comparable, V any] struct {
maxSizePerP int
pool *sync.Pool
}
type cacheStripe[K comparable, V any] struct {
cache map[K]V
}
func NewCache[K comparable, V any](maxSizePerP int) (*Cache[K, V], error) {
if maxSizePerP <= 0 {
return nil, errors.New("maxSizePerP must be greater than zero")
}
c := &Cache[K, V]{
maxSizePerP: maxSizePerP,
pool: &sync.Pool{
New: func() interface{} {
return &cacheStripe[K, V]{
cache: make(map[K]V),
}
},
},
}
return c, nil
}
func (c *Cache[K, V]) Load(key K) (V, bool) {
stripe := c.pool.Get().(*cacheStripe[K, V])
defer c.pool.Put(stripe)
value, ok := stripe.cache[key]
return value, ok
}
func (c *Cache[K, V]) Store(key K, value V) {
stripe := c.pool.Get().(*cacheStripe[K, V])
defer c.pool.Put(stripe)
stripe.cache[key] = value
if len(stripe.cache) > c.maxSizePerP {
for k := range stripe.cache {
delete(stripe.cache, k)
break
}
}
}