pkg/rw/map.go

61 lines
897 B
Go
Raw Permalink Normal View History

2023-09-18 15:51:20 +08:00
package rw
import (
"sync"
)
type Map[Item any] struct {
m map[string]Item
sync.RWMutex
}
func NewMap[Item any]() *Map[Item] {
return &Map[Item]{m: make(map[string]Item, 8)}
}
func (m *Map[Item]) ReadAll() (copyM map[string]Item) {
m.RLock()
defer m.RUnlock()
copyM = make(map[string]Item, len(m.m))
for k, v := range m.m {
copyM[k] = v
}
return copyM
}
func (m *Map[Item]) Has(key string) (ok bool) {
m.RLock()
_, ok = m.m[key]
m.RUnlock()
return
}
func (m *Map[Item]) Get(key string) Item {
m.RLock()
defer m.RUnlock()
return m.m[key]
}
func (m *Map[Item]) Set(key string, v Item) {
m.Lock()
defer m.Unlock()
m.m[key] = v
}
func (m *Map[Item]) SetAll(in map[string]Item) {
m.Lock()
defer m.Unlock()
for key, v := range in {
m.m[key] = v
}
}
func (m *Map[Item]) Del(key string) Item {
m.Lock()
defer m.Unlock()
v := m.m[key]
delete(m.m, key)
return v
}