-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncmap.go
402 lines (340 loc) · 8.61 KB
/
syncmap.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package chadango
import (
"bytes"
"encoding/gob"
"sync"
)
// SyncMap is a synchronized map that can be accessed concurrently.
//
// It provides thread-safe methods for setting, getting, deleting, and iterating over key-value pairs.
// The map also supports Gob encoding and decoding for persistence.
type SyncMap[K comparable, V any] struct {
sync.RWMutex
M map[K]V
}
// Set adds or updates a key-value pair in the SyncMap.
//
// Args:
// - key: The key to add or update.
// - val: The value to associate with the key.
func (sm *SyncMap[K, V]) Set(key K, val V) {
sm.Lock()
defer sm.Unlock()
sm.M[key] = val
}
// Get retrieves the value associated with the specified key from the SyncMap.
//
// Args:
// - key: The key to retrieve the value for.
//
// Returns:
// - V: The value associated with the key.
// - bool: True if the key exists in the map, false otherwise.
func (sm *SyncMap[K, V]) Get(key K) (val V, ok bool) {
sm.RLock()
defer sm.RUnlock()
val, ok = sm.M[key]
return
}
// Del removes the key-value pair with the specified key from the SyncMap.
//
// Args:
// - key: The key to remove.
func (sm *SyncMap[K, V]) Del(key K) {
sm.Lock()
defer sm.Unlock()
delete(sm.M, key)
}
// Len returns the number of key-value pairs in the SyncMap.
//
// Returns:
// - int: The number of key-value pairs in the map.
func (sm *SyncMap[K, V]) Len() int {
sm.RLock()
defer sm.RUnlock()
return len(sm.M)
}
// Range iterates over each key-value pair in the SyncMap and calls the specified function.
//
// Args:
// - fun: The function to call for each key-value pair.
//
// The function takes two arguments:
// - key: The key of the current key-value pair.
// - value: The value of the current key-value pair.
//
// If the function returns false, the iteration stops.
func (sm *SyncMap[K, V]) Range(fun func(K, V) bool) {
sm.RLock()
defer sm.RUnlock()
for k, v := range sm.M {
if !fun(k, v) {
return
}
}
}
// Clear removes all key-value pairs from the SyncMap.
func (sm *SyncMap[K, V]) Clear() {
sm.Lock()
defer sm.Unlock()
sm.M = make(map[K]V)
}
// Keys returns a slice of keys in the SyncMap.
//
// Returns:
// - []K: A slice containing all the keys in the map.
func (sm *SyncMap[K, V]) Keys() (keys []K) {
sm.RLock()
defer sm.RUnlock()
for k := range sm.M {
keys = append(keys, k)
}
return
}
// GobEncode encodes the SyncMap using Gob encoding.
//
// Returns:
// - []byte: The encoded byte slice.
// - error: An error if encoding fails.
func (sm *SyncMap[K, V]) GobEncode() ([]byte, error) {
sm.RLock()
defer sm.RUnlock()
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(sm.M)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// GobDecode decodes the SyncMap using Gob decoding.
//
// Args:
// - data: The encoded byte slice to decode.
//
// Returns:
// - error: An error if decoding fails.
func (sm *SyncMap[K, V]) GobDecode(data []byte) error {
sm.Lock()
defer sm.Unlock()
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
err := dec.Decode(&sm.M)
if err != nil {
return err
}
return nil
}
// NewSyncMap creates a new instance of SyncMap.
//
// Returns:
// - SyncMap[K, V]: A new instance of SyncMap.
func NewSyncMap[K comparable, V any]() SyncMap[K, V] {
return SyncMap[K, V]{M: map[K]V{}}
}
// OrderedSyncMap is a synchronized map that maintains the order of keys.
//
// It provides thread-safe methods for setting, getting, deleting, and iterating over key-value pairs in the order they were added.
// The map also supports Gob encoding and decoding for persistence.
type OrderedSyncMap[K comparable, V any] struct {
sync.RWMutex
K []K
M map[K]V
}
// Set adds or updates a key-value pair in the OrderedSyncMap.
//
// Args:
// - key: The key to add or update.
// - val: The value to associate with the key.
func (sm *OrderedSyncMap[K, V]) Set(key K, val V) {
sm.Lock()
defer sm.Unlock()
sm.del(key)
sm.K = append(sm.K, key)
sm.M[key] = val
}
// Get retrieves the value associated with the specified key from the OrderedSyncMap.
//
// Args:
// - key: The key to retrieve the value for.
//
// Returns:
// - V: The value associated with the key.
// - bool: True if the key exists in the map, false otherwise.
func (sm *OrderedSyncMap[K, V]) Get(key K) (val V, ok bool) {
sm.RLock()
defer sm.RUnlock()
val, ok = sm.M[key]
return
}
// Del removes the key-value pair with the specified key from the OrderedSyncMap.
//
// Args:
// - key: The key to remove.
func (sm *OrderedSyncMap[K, V]) Del(key K) {
sm.Lock()
defer sm.Unlock()
sm.del(key)
}
// del removes the key from the OrderedSyncMap's key slice and deletes the corresponding value.
// This is not protected by Mutex, so keep it for internal use.
func (sm *OrderedSyncMap[K, V]) del(key K) {
index := -1
for i, k := range sm.K {
if k == key {
index = i
break
}
}
if index < 0 {
return
}
sm.K = append(sm.K[:index], sm.K[index+1:]...)
delete(sm.M, key)
}
// Len returns the number of key-value pairs in the OrderedSyncMap.
//
// Returns:
// - int: The number of key-value pairs in the map.
func (sm *OrderedSyncMap[K, V]) Len() int {
sm.RLock()
defer sm.RUnlock()
return len(sm.M)
}
// Range iterates over each key-value pair in the OrderedSyncMap and calls the specified function.
//
// Args:
// - fun: The function to call for each key-value pair.
//
// The function takes two arguments:
// - key: The key of the current key-value pair.
// - value: The value of the current key-value pair.
//
// If the function returns false, the iteration stops.
func (sm *OrderedSyncMap[K, V]) Range(fun func(K, V) bool) {
sm.RLock()
defer sm.RUnlock()
for _, k := range sm.K {
if !fun(k, sm.M[k]) {
return
}
}
}
// RangeReversed iterates over each key-value pair in the OrderedSyncMap in reverse order and calls the specified function.
//
// Args:
// - fun: The function to call for each key-value pair.
//
// The function takes two arguments:
// - key: The key of the current key-value pair.
// - value: The value of the current key-value pair.
//
// If the function returns false, the iteration stops.
func (sm *OrderedSyncMap[K, V]) RangeReversed(fun func(K, V) bool) {
sm.RLock()
defer sm.RUnlock()
for i := len(sm.K) - 1; i >= 0; i-- {
if !fun(sm.K[i], sm.M[sm.K[i]]) {
return
}
}
}
// Clear removes all key-value pairs from the OrderedSyncMap.
func (sm *OrderedSyncMap[K, V]) Clear() {
sm.Lock()
defer sm.Unlock()
sm.K = make([]K, 0)
sm.M = make(map[K]V)
}
// Keys returns a slice of keys in the OrderedSyncMap.
//
// Returns:
// - []K: A slice containing all the keys in the map.
func (sm *OrderedSyncMap[K, V]) Keys() []K {
sm.RLock()
defer sm.RUnlock()
return sm.K
}
// SetFront adds or updates a key-value pair at the front of the OrderedSyncMap.
//
// Args:
// - key: The key to add or update.
// - val: The value to associate with the key.
func (sm *OrderedSyncMap[K, V]) SetFront(key K, val V) {
sm.Lock()
defer sm.Unlock()
sm.del(key)
temp := make([]K, len(sm.K)+1)
copy(temp[1:], sm.K)
temp[0] = key
sm.K = temp
sm.M[key] = val
}
// TrimFront trims the front part of the OrderedSyncMap to the specified length.
//
// Args:
// - length: The desired length of the map after trimming.
//
// It modifies the OrderedSyncMap in place,
// removing elements from the beginning of the map until the desired length is reached.
func (sm *OrderedSyncMap[K, V]) TrimFront(length int) {
l := sm.Len()
if l <= length {
return
}
sm.Lock()
defer sm.Unlock()
trim := sm.K[:l-length]
for _, k := range trim {
sm.del(k)
}
}
// GobEncode encodes the OrderedSyncMap using Gob.
//
// Returns:
// - []byte: The encoded byte slice.
// - error: An error if encoding fails.
func (sm *OrderedSyncMap[K, V]) GobEncode() ([]byte, error) {
sm.RLock()
defer sm.RUnlock()
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(sm.K)
if err != nil {
return nil, err
}
err = enc.Encode(sm.M)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// GobDecode decodes the OrderedSyncMap using Gob.
//
// Args:
// - data: The encoded byte slice to decode.
//
// Returns:
// - error: An error if decoding fails.
func (sm *OrderedSyncMap[K, V]) GobDecode(data []byte) error {
sm.Lock()
defer sm.Unlock()
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
err := dec.Decode(&sm.K)
if err != nil {
return err
}
err = dec.Decode(&sm.M)
if err != nil {
return err
}
return nil
}
// NewOrderedSyncMap creates a new instance of OrderedSyncMap.
//
// Returns:
// - OrderedSyncMap[K, V]: A new instance of OrderedSyncMap.
func NewOrderedSyncMap[K comparable, V any]() OrderedSyncMap[K, V] {
return OrderedSyncMap[K, V]{K: []K{}, M: map[K]V{}}
}