-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
212 lines (176 loc) · 5.09 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package ordered
import (
"slices"
"sync/atomic"
)
// An op is a read-only or read-write operation, used to annotate invariant
// checks.
//
//enumcheck:exhaustive
type op int
// Possible op types.
const (
_ op = iota
ro
rw
)
// A Map is like a map[K]V, but offers deterministic iteration order by applying
// a comparison function against all keys. A Map must be constructed using
// NewMap or its methods will panic.
//
// Maps are not safe for concurrent use.
type Map[K comparable, V any] struct {
// Atomic: whether or not a MapIterator is live for this Map.
iter int32
// A sorted list of keys stored in the map and the function to compare those
// keys.
keys []K
cmp func(a, b K) int
// The actual underlying map storage.
m map[K]V
}
// NewMap creates a *Map[K, V] which uses the a comparison function to order the
// keys in the map. cmp must not be nil or NewMap will panic. For types which
// meet the [cmp.Ordered] constraint, [cmp.Compare] can be used as a comparison
// function.
func NewMap[K comparable, V any](cmp func(a, b K) int) *Map[K, V] {
if cmp == nil {
panic("ordered: NewMap must use a non-nil cmp function")
}
return &Map[K, V]{
m: make(map[K]V),
cmp: cmp,
}
}
// Get gets the value V for a given key K, returning the zero value of V if K is
// not found.
func (m *Map[K, V]) Get(k K) V {
m.check(ro)
return m.m[k]
}
// TryGet tries to get the value V for a given key K, returning false if K is
// not found.
func (m *Map[K, V]) TryGet(k K) (V, bool) {
m.check(ro)
v, ok := m.m[k]
return v, ok
}
// Len returns the number of elements in the Map.
func (m *Map[K, V]) Len() int {
m.check(ro)
return len(m.keys)
}
// Set inserts or updates the value V for a given key K.
func (m *Map[K, V]) Set(k K, v V) {
m.check(rw)
if _, ok := m.m[k]; !ok {
// Always sort when a new key is inserted.
m.keys = append(m.keys, k)
slices.SortFunc(m.keys, m.cmp)
}
m.m[k] = v
}
// Delete deletes the value for a given key K.
func (m *Map[K, V]) Delete(k K) {
m.check(rw)
i := slices.Index(m.keys, k)
if i != -1 {
// Found this key, remove it from the order index.
m.keys = slices.Delete(m.keys, i, i+1)
}
delete(m.m, k)
}
// Reset clears the underlying storage for a Map by removing all elements,
// enabling the allocated capacity to be reused.
func (m *Map[K, V]) Reset() {
m.check(rw)
m.keys = m.keys[:0]
clear(m.m)
}
// check checks the Map's invariants for a given operation type.
func (m *Map[K, V]) check(op op) {
if m == nil || m.cmp == nil {
panic("ordered: a Map must be constructed using NewMap")
}
if op == rw && atomic.LoadInt32(&m.iter) != 0 {
panic("ordered: write to Map while MapIterator is not closed")
}
}
// A KeyValue is a key/value pair produced by a MapIterator or Map.Range call.
type KeyValue[K comparable, V any] struct {
Key K
Value V
}
// Range produces a slice of all KeyValue pairs from Map for use in a for range
// loop. See Map.Iter for more fine-grained iteration control.
func (m *Map[K, V]) Range() []KeyValue[K, V] {
m.check(ro)
kvs := make([]KeyValue[K, V], 0, len(m.keys))
for _, k := range m.keys {
kvs = append(kvs, KeyValue[K, V]{
Key: k,
Value: m.m[k],
})
}
return kvs
}
// A MapIterator is an iteration cursor over a Map. A MapIterator must be
// constructed using Map.Iter or its methods will panic.
//
// When a MapIterator is created, any methods which write to a Map (Delete,
// Reset, Set) will panic. Reads during iteration are permitted. To complete
// iteration and permit further writes, call MapIterator.Close. Multiple
// MapIterators can be used at once over the same Map, but write methods will
// panic until all MapIterators are closed. After a call to Close, the
// MapIterator can no longer be used.
//
// For more basic iteration use cases, see Map.Range.
type MapIterator[K comparable, V any] struct {
m *Map[K, V]
i int
}
// Iter produces a MapIterator which allows fine-grained iteration over a Map.
func (m *Map[K, V]) Iter() *MapIterator[K, V] {
m.check(ro)
// Add another iterator to the stack.
atomic.AddInt32(&m.iter, 1)
return &MapIterator[K, V]{m: m}
}
// Close releases a MapIterator's resources, enabling further writes to a Map.
func (mi *MapIterator[K, V]) Close() {
mi.check()
// Remove an iterator from the stack. If this number goes below zero, panic
// due to misuse.
if atomic.AddInt32(&mi.m.iter, -1) < 0 {
panic("ordered: call to MapIterator.Close while MapIterator is not open")
}
mi = nil
}
// Next returns the next KeyValue pair from a Map. If Next returns nil, no more
// KeyValue pairs are present. Next is intended to be used in a for loop, in the
// format:
//
// mi := m.Iter()
// defer mi.Close()
// for kv := mi.Next(); kv != nil; kv = mi.Next() {
// // use kv
// }
func (mi *MapIterator[K, V]) Next() *KeyValue[K, V] {
mi.check()
if mi.i >= len(mi.m.keys) {
// No more keys.
return nil
}
k := mi.m.keys[mi.i]
mi.i++
return &KeyValue[K, V]{
Key: k,
Value: mi.m.m[k],
}
}
// check checks the MapIterator's invariants.
func (mi *MapIterator[K, V]) check() {
if mi == nil || mi.m == nil {
panic("ordered: a MapIterator must be constructed using Map.Iter")
}
}