From eea50ee013d073e45c3c979da694bda523ff6b64 Mon Sep 17 00:00:00 2001 From: Wessie Date: Mon, 26 Feb 2024 23:15:51 +0000 Subject: [PATCH] util: add typed sync.Map type --- util/map.go | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 util/map.go diff --git a/util/map.go b/util/map.go new file mode 100644 index 00000000..1f25d45c --- /dev/null +++ b/util/map.go @@ -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 +}