-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
map.go
58 lines (46 loc) · 982 Bytes
/
map.go
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
package compatible
import "sync"
// Map is a generics sync.Map
type Map[K comparable, V any] struct {
m sync.Map
}
func (m *Map[K, V]) Len() int {
var count int
m.m.Range(func(key, value any) bool {
count++
return true
})
return count
}
func (m *Map[K, V]) Load(key K) (V, bool) {
v, ok := m.m.Load(key)
if !ok {
return *new(V), false
}
return v.(V), ok
}
func (m *Map[K, V]) Store(key K, value V) {
m.m.Store(key, value)
}
func (m *Map[K, V]) Delete(key K) {
m.m.Delete(key)
}
func (m *Map[K, V]) Range(f func(key K, value V) bool) {
m.m.Range(func(key, value any) bool {
return f(key.(K), value.(V))
})
}
func (m *Map[K, V]) LoadOrStore(key K, value V) (V, bool) {
v, ok := m.m.LoadOrStore(key, value)
return v.(V), ok
}
func (m *Map[K, V]) LoadAndDelete(key K) (V, bool) {
v, ok := m.m.LoadAndDelete(key)
if !ok {
return *new(V), false
}
return v.(V), ok
}
func New[K comparable, V any]() *Map[K, V] {
return &Map[K, V]{m: sync.Map{}}
}