Skip to content

Commit f75dfb0

Browse files
committed
change cache impl from pool to sync.Map
1 parent b9dc14f commit f75dfb0

File tree

1 file changed

+26
-28
lines changed

1 file changed

+26
-28
lines changed

cache.go

+26-28
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,57 @@
11
package helpisu
22

3-
import (
4-
"sync"
5-
)
3+
import "sync"
64

75
/*
86
Cache ジェネリックで、スレッドセーフなマップキャッシュ
9-
リセットしても初期キャパシティを記憶しています
7+
sync.Mapのジェネリックなラッパーです
108
*/
119
type Cache[K comparable, V any] struct {
12-
m *sync.Pool
13-
c int
10+
m *sync.Map
1411
}
1512

1613
// NewCache 新たなCacheを作成
17-
func NewCache[K comparable, V any](capacity int) *Cache[K, V] {
14+
func NewCache[K comparable, V any]() *Cache[K, V] {
1815
return &Cache[K, V]{
19-
m: &sync.Pool{
20-
New: func() interface{} {
21-
return make(map[K]V, capacity)
22-
},
23-
},
24-
c: capacity,
16+
m: &sync.Map{},
2517
}
2618
}
2719

2820
// Get 指定したKeyのキャッシュを取得
2921
func (c *Cache[K, V]) Get(key K) (value V, ok bool) {
30-
cache, _ := c.m.Get().(map[K]V)
31-
defer c.m.Put(cache)
32-
value, ok = cache[key]
22+
cache, ok := c.m.Load(key)
23+
if !ok {
24+
return
25+
}
26+
27+
value, ok = cache.(V)
28+
29+
return
30+
}
31+
32+
// GetAndDelete 指定したKeyのキャッシュを取得して削除
33+
func (c *Cache[K, V]) GetAndDelete(key K) (value V, ok bool) {
34+
cache, ok := c.m.LoadAndDelete(key)
35+
if !ok {
36+
return
37+
}
38+
39+
value, ok = cache.(V)
3340

3441
return
3542
}
3643

3744
// Set 指定したKey-Valueのセットをキャッシュに入れる
3845
func (c *Cache[K, V]) Set(key K, value V) {
39-
cache, _ := c.m.Get().(map[K]V)
40-
cache[key] = value
41-
c.m.Put(cache)
46+
c.m.Store(key, value)
4247
}
4348

4449
// Delete 指定したKeyのキャッシュを削除
4550
func (c *Cache[K, V]) Delete(key K) {
46-
cache, _ := c.m.Get().(map[K]V)
47-
delete(cache, key)
48-
c.m.Put(cache)
51+
c.m.Delete(key)
4952
}
5053

5154
// Reset 全てのキャッシュを削除
5255
func (c *Cache[K, V]) Reset() {
53-
cache, _ := c.m.Get().(map[K]V)
54-
for key := range cache {
55-
delete(cache, key)
56-
}
57-
58-
c.m.Put(cache)
56+
c.m = &sync.Map{}
5957
}

0 commit comments

Comments
 (0)