Skip to content

Commit

Permalink
util: add typed sync.Map type
Browse files Browse the repository at this point in the history
  • Loading branch information
Wessie committed Feb 26, 2024
1 parent 2d880f5 commit eea50ee
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions util/map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package util

import "sync"

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

func (m *Map[K, V]) CompareAndDelete(key K, old V) (deleted bool) {
return m.m.CompareAndDelete(key, old)
}

func (m *Map[K, V]) CompareAndSwap(key K, old V, new V) bool {
return m.m.CompareAndSwap(key, old, new)
}

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 || v == nil {
return *new(V), false
}
return v.(V), true
}

func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
v, loaded := m.m.LoadAndDelete(key)
if v == nil {
return *new(V), 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)
if a == nil {
return *new(V), loaded
}
return a.(V), loaded
}

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

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

func (m *Map[K, V]) Swap(key K, value V) (previous V, loaded bool) {
p, loaded := m.m.Swap(key, value)
if p == nil {
return *new(V), loaded
}
return p.(V), loaded
}

0 comments on commit eea50ee

Please sign in to comment.