-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
change cache impl from pool to sync.Map
- Loading branch information
1 parent
b9dc14f
commit f75dfb0
Showing
1 changed file
with
26 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,59 +1,57 @@ | ||
package helpisu | ||
|
||
import ( | ||
"sync" | ||
) | ||
import "sync" | ||
|
||
/* | ||
Cache ジェネリックで、スレッドセーフなマップキャッシュ | ||
リセットしても初期キャパシティを記憶しています | ||
sync.Mapのジェネリックなラッパーです | ||
*/ | ||
type Cache[K comparable, V any] struct { | ||
m *sync.Pool | ||
c int | ||
m *sync.Map | ||
} | ||
|
||
// NewCache 新たなCacheを作成 | ||
func NewCache[K comparable, V any](capacity int) *Cache[K, V] { | ||
func NewCache[K comparable, V any]() *Cache[K, V] { | ||
return &Cache[K, V]{ | ||
m: &sync.Pool{ | ||
New: func() interface{} { | ||
return make(map[K]V, capacity) | ||
}, | ||
}, | ||
c: capacity, | ||
m: &sync.Map{}, | ||
} | ||
} | ||
|
||
// Get 指定したKeyのキャッシュを取得 | ||
func (c *Cache[K, V]) Get(key K) (value V, ok bool) { | ||
cache, _ := c.m.Get().(map[K]V) | ||
defer c.m.Put(cache) | ||
value, ok = cache[key] | ||
cache, ok := c.m.Load(key) | ||
if !ok { | ||
return | ||
} | ||
|
||
value, ok = cache.(V) | ||
|
||
return | ||
} | ||
|
||
// GetAndDelete 指定したKeyのキャッシュを取得して削除 | ||
func (c *Cache[K, V]) GetAndDelete(key K) (value V, ok bool) { | ||
cache, ok := c.m.LoadAndDelete(key) | ||
if !ok { | ||
return | ||
} | ||
|
||
value, ok = cache.(V) | ||
|
||
return | ||
} | ||
|
||
// Set 指定したKey-Valueのセットをキャッシュに入れる | ||
func (c *Cache[K, V]) Set(key K, value V) { | ||
cache, _ := c.m.Get().(map[K]V) | ||
cache[key] = value | ||
c.m.Put(cache) | ||
c.m.Store(key, value) | ||
} | ||
|
||
// Delete 指定したKeyのキャッシュを削除 | ||
func (c *Cache[K, V]) Delete(key K) { | ||
cache, _ := c.m.Get().(map[K]V) | ||
delete(cache, key) | ||
c.m.Put(cache) | ||
c.m.Delete(key) | ||
} | ||
|
||
// Reset 全てのキャッシュを削除 | ||
func (c *Cache[K, V]) Reset() { | ||
cache, _ := c.m.Get().(map[K]V) | ||
for key := range cache { | ||
delete(cache, key) | ||
} | ||
|
||
c.m.Put(cache) | ||
c.m = &sync.Map{} | ||
} |