Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert syncmap #133

Merged
merged 18 commits into from
Dec 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 21 additions & 20 deletions safemap/safemap.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,45 @@ package safemap
import "sync"

type SafeMap[K comparable, V any] struct {
data sync.Map
mu sync.RWMutex
data map[K]V
}

func New[K comparable, V any]() *SafeMap[K, V] {
return &SafeMap[K, V]{
data: sync.Map{},
data: make(map[K]V),
}
}

func (s *SafeMap[K, V]) Set(k K, v V) {
s.data.Store(k, v)
s.mu.Lock()
defer s.mu.Unlock()
s.data[k] = v
}

func (s *SafeMap[K, V]) Get(k K) (V, bool) {
val, ok := s.data.Load(k)
var zero V
if !ok {
return zero, false
}
return val.(V), ok
s.mu.RLock()
defer s.mu.RUnlock()
val, ok := s.data[k]
return val, ok
}

func (s *SafeMap[K, V]) Delete(k K) {
s.data.Delete(k)
s.mu.Lock()
defer s.mu.Unlock()
delete(s.data, k)
}

func (s *SafeMap[K, V]) Len() int {
count := 0
s.data.Range(func(_, _ interface{}) bool {
count++
return true
})
return count
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.data)
}

func (s *SafeMap[K, V]) ForEach(f func(K, V)) {
s.data.Range(func(key, value interface{}) bool {
f(key.(K), value.(V))
return true
})
s.mu.RLock()
defer s.mu.RUnlock()
for k, v := range s.data {
f(k, v)
}
}