snow/aid/syncer.go

67 lines
1.0 KiB
Go
Raw Normal View History

2024-01-20 01:58:57 +00:00
package aid
import (
"sync"
)
type GenericSyncMap[T any] struct {
m sync.Map
}
2024-01-28 22:04:40 +00:00
func (s *GenericSyncMap[T]) Set(key string, value *T) {
2024-01-20 01:58:57 +00:00
s.m.Store(key, value)
}
func (s *GenericSyncMap[T]) Get(key string) (*T, bool) {
v, ok := s.m.Load(key)
if !ok {
return nil, false
}
return v.(*T), true
}
2024-01-29 23:46:22 +00:00
func (s *GenericSyncMap[T]) MustGet(key string) *T {
v, ok := s.m.Load(key)
if !ok {
return nil
}
return v.(*T)
}
2024-01-20 01:58:57 +00:00
func (s *GenericSyncMap[T]) Delete(key string) {
s.m.Delete(key)
}
func (s *GenericSyncMap[T]) Range(f func(key string, value *T) bool) {
s.m.Range(func(key, value interface{}) bool {
return f(key.(string), value.(*T))
})
2024-01-29 23:46:22 +00:00
}
func (s *GenericSyncMap[T]) Has(key string) bool {
_, ok := s.Get(key)
return ok
}
// change the key of a value in the map
func (s *GenericSyncMap[T]) ChangeKey(oldKey, newKey string) {
v, ok := s.Get(oldKey)
if !ok {
return
}
s.Set(newKey, v)
s.Delete(oldKey)
2024-02-10 01:55:56 +00:00
}
func (s *GenericSyncMap[T]) Len() int {
count := 0
s.m.Range(func(_, _ interface{}) bool {
count++
return true
})
return count
2024-01-20 01:58:57 +00:00
}