From 5a1a904b4264c6ee323c9bd433f9ee4da93c984d Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Sun, 5 Feb 2023 13:02:57 -0700 Subject: typedsync: Bring up to being a mostly-drop-in replacement for Go 1.20 sync --- typedsync/map_go120.go | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) (limited to 'typedsync/map_go120.go') diff --git a/typedsync/map_go120.go b/typedsync/map_go120.go index 0d4ff5b..6885e2a 100644 --- a/typedsync/map_go120.go +++ b/typedsync/map_go120.go @@ -7,3 +7,54 @@ package typedsync type mapkey = comparable + +func (m *Map[K, V]) Swap(key K, value V) (previous V, loaded bool) { + _previous, loaded := m.inner.Swap(key, value) + if loaded { + //nolint:forcetypeassert // Typed wrapper around untyped lib. + previous = _previous.(V) + } + return previous, loaded +} + +// ComparableMap is a variant of Map with a comparable type for V; +// affording additional CompareAndDelete and CompareAndSwap methods. +// +// See the [sync.Map documentation] for full details. +// +// [sync.Map documentation]: https://pkg.go.dev/sync#Map +type ComparableMap[K comparable, V comparable] struct { + inner Map[K, V] +} + +func (m *ComparableMap[K, V]) Delete(key K) { + m.inner.Delete(key) +} + +func (m *ComparableMap[K, V]) Load(key K) (value V, ok bool) { + return m.inner.Load(key) +} + +func (m *ComparableMap[K, V]) LoadAndDelete(key K) (value V, loaded bool) { + return m.inner.LoadAndDelete(key) +} + +func (m *ComparableMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) { + return m.inner.LoadOrStore(key, value) +} + +func (m *ComparableMap[K, V]) Range(f func(key K, value V) bool) { + m.inner.Range(f) +} + +func (m *ComparableMap[K, V]) Store(key K, value V) { + m.inner.Store(key, value) +} + +func (m *ComparableMap[K, V]) CompareAndDelete(key K, old V) (deleted bool) { + return m.inner.inner.CompareAndDelete(key, old) +} + +func (m *ComparableMap[K, V]) CompareAndSwap(key K, oldV, newV V) bool { + return m.inner.inner.CompareAndSwap(key, oldV, newV) +} -- cgit v1.2.3-2-g168b