Skip to content

Commit

Permalink
add sync map
Browse files Browse the repository at this point in the history
  • Loading branch information
mpkondrashin committed Apr 11, 2024
1 parent 1d8e9ab commit 6b040a1
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions pkg/task/map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
m := new(Map[string, string])
m.Store("hi", "ho")
*/

package task

import "sync"

type Map[K comparable, V any] struct {
m sync.Map
}

func (m *Map[K, V]) Delete(key K) {
m.m.Delete(key)
}

func (m *Map[K, V]) Load(key K) (value V, ok bool) {
v, ok := m.m.Load(key)
if !ok {
return value, ok
}
return v.(V), ok
}

func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
v, loaded := m.m.LoadAndDelete(key)
if !loaded {
return value, loaded
}
return v.(V), loaded
}

func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
a, loaded := m.m.LoadOrStore(key, value)
return a.(V), loaded
}

func (m *Map[K, V]) Range(f func(key K, value V) bool) {
m.m.Range(func(key, value any) bool {
return f(key.(K), value.(V))
})
}

func (m *Map[K, V]) Store(key K, value V) {
m.m.Store(key, value)
}

func (m *Map[K, V]) Length() int {
var i int
m.Range(func(k K, v V) bool {
i++
return true
})
return i
}

0 comments on commit 6b040a1

Please sign in to comment.