Skip to content

Commit

Permalink
change cache impl from pool to sync.Map
Browse files Browse the repository at this point in the history
  • Loading branch information
logica0419 committed Jul 22, 2022
1 parent b9dc14f commit f75dfb0
Showing 1 changed file with 26 additions and 28 deletions.
54 changes: 26 additions & 28 deletions cache.go
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{}
}

0 comments on commit f75dfb0

Please sign in to comment.