1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
// Copyright (C) 2022-2023 Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later
package typedsync
import (
"sync"
)
// Map is a type-safe equivalent of the standard library's sync.Map.
//
// See the [sync.Map documentation] for full details.
//
// Go 1.20 added sync.Map.Swap method; this method is only available
// on typedsync.Map if built with Go 1.20 or later.
//
// Go 1.20 added sync.Map.CompareAndDelete and sync.Map.CompareAndSwap
// methods that are only usable if V is a comparable type; these
// methods are not available on typedsync.Map, but when typedsync is
// built with Go 1.20 or later they are available on a separate
// ComparableMap type.
//
// When typedsync is built versions of Go prior to Go 1.20,
// typedsync.Map is specified too loosely, as
//
// Map[K any, V any]
//
// while with Go 1.20 and later, typedsync.Map is specified as
//
// Map[K comparable, V any]
//
// This is because with Go versions prior to 1.20, 'comparable' was
// overly strict, disallowing many types that are valid map-keys (see
// https://github.com/golang/go/issues/56548). The type used as K in
// a Map with older versions of Go must be a valid map-key type, even
// though the type specification of Map does not enforce that.
//
// [sync.Map documentation]: https://pkg.go.dev/sync#Map
type Map[K mapkey, V any] struct {
inner sync.Map
}
func (m *Map[K, V]) Delete(key K) {
m.inner.Delete(key)
}
func (m *Map[K, V]) Load(key K) (value V, ok bool) {
_value, ok := m.inner.Load(key)
if ok {
//nolint:forcetypeassert // Typed wrapper around untyped lib.
value = _value.(V)
}
return value, ok
}
func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
_value, ok := m.inner.LoadAndDelete(key)
if ok {
//nolint:forcetypeassert // Typed wrapper around untyped lib.
value = _value.(V)
}
return value, ok
}
func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
_actual, loaded := m.inner.LoadOrStore(key, value)
//nolint:forcetypeassert // Typed wrapper around untyped lib.
actual = _actual.(V)
return actual, loaded
}
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
m.inner.Range(func(key, value any) bool {
//nolint:forcetypeassert // Typed wrapper around untyped lib.
return f(key.(K), value.(V))
})
}
func (m *Map[K, V]) Store(key K, value V) {
m.inner.Store(key, value)
}
|