| 1 |
// Copyright 2024 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package syncx |
| 15 |
|
| 16 |
import "sync" |
| 17 |
|
| 18 |
// Map is a type-safe wrapper around sync.Map. |
| 19 |
// It is safe for concurrent use. |
| 20 |
// The zero value of Map is an empty map ready to use. |
| 21 |
type Map[K comparable, V any] struct { |
| 22 |
m sync.Map |
| 23 |
} |
| 24 |
|
| 25 |
func (m *Map[K, V]) Load(key K) (V, bool) { |
| 26 |
v, ok := m.m.Load(key) |
| 27 |
if !ok { |
| 28 |
var empty V |
| 29 |
return empty, false |
| 30 |
} |
| 31 |
return v.(V), true |
| 32 |
} |
| 33 |
|
| 34 |
func (m *Map[K, V]) Store(key K, value V) { |
| 35 |
m.m.Store(key, value) |
| 36 |
} |
| 37 |
|
| 38 |
func (m *Map[K, V]) Delete(key K) { |
| 39 |
m.m.Delete(key) |
| 40 |
} |
| 41 |
|
| 42 |
func (m *Map[K, V]) Range(f func(key K, value V) bool) { |
| 43 |
m.m.Range(func(key, value any) bool { |
| 44 |
return f(key.(K), value.(V)) |
| 45 |
}) |
| 46 |
} |
| 47 |
|
| 48 |
func (m *Map[K, V]) LoadOrStore(key K, value V) (V, bool) { |
| 49 |
v, loaded := m.m.LoadOrStore(key, value) |
| 50 |
return v.(V), loaded |
| 51 |
} |
| 52 |
|
| 53 |
func (m *Map[K, V]) LoadAndDelete(key K) (V, bool) { |
| 54 |
v, ok := m.m.LoadAndDelete(key) |
| 55 |
if !ok { |
| 56 |
var empty V |
| 57 |
return empty, false |
| 58 |
} |
| 59 |
return v.(V), true |
| 60 |
} |
| 61 |
|
| 62 |
func (m *Map[K, V]) CompareAndSwap(key K, old, new V) bool { |
| 63 |
return m.m.CompareAndSwap(key, old, new) |
| 64 |
} |
| 65 |
|
| 66 |
func (m *Map[K, V]) CompareAndDelete(key K, value V) bool { |
| 67 |
return m.m.CompareAndDelete(key, value) |
| 68 |
} |
| 69 |
|
| 70 |
func (m *Map[K, V]) Swap(key K, value V) (V, bool) { |
| 71 |
previous, loaded := m.m.Swap(key, value) |
| 72 |
return previous.(V), loaded |
| 73 |
} |