-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_map.go
198 lines (158 loc) · 3.89 KB
/
sync_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
package syncmap
import (
"bytes"
"cmp"
"encoding/gob"
"errors"
"fmt"
"io"
"sort"
"sync"
)
// SortedKeys returns a sorted slice of the map's keys
func SortedKeys[K cmp.Ordered, V any](m map[K]V) []K {
keys := make([]K, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
return keys
}
// ComparableAndOrdered defines the type constraints for SynchronisedMap
type ComparableAndOrdered interface {
comparable
cmp.Ordered
}
// New returns an instance of SynchronisedMap, containing the
// contents of the init map
func New[T ComparableAndOrdered, U any](init map[T]U) *SynchronisedMap[T, U] {
m := &SynchronisedMap[T, U]{
m: map[T]U{},
}
for k, v := range init {
m.m[k] = v
}
return m
}
// ErrMissingKey is returned if the requested key is not in the map
var ErrMissingKey = errors.New("unknown key")
// ErrKeyExists is returned if Insert is called and key already exists
var ErrKeyExists = errors.New("key already exists")
// SynchronisedMap provides a concurrency safe map
type SynchronisedMap[T ComparableAndOrdered, U any] struct {
lck sync.RWMutex
m map[T]U
}
// Insert adds the value at the specified key.
// If errIfExists is true and the key exists, then an error is raised. Otherwise
// the value is inserted at the key, and any pre-existing value returned.
func (s *SynchronisedMap[T, U]) Insert(k T, v U, errIfExists bool) (U, error) {
s.lck.Lock()
defer s.lck.Unlock()
var r U
old, ok := s.m[k]
if !ok {
s.m[k] = v
return r, nil
}
if errIfExists {
return r, ErrKeyExists
}
s.m[k] = v
return old, nil
}
// GetKeys returns the keys, sorted, within the map
func (s *SynchronisedMap[T, U]) GetKeys() []T {
s.lck.RLock()
defer s.lck.RUnlock()
return SortedKeys(s.m)
}
// Contains returns true if the key is found
func (s *SynchronisedMap[T, U]) Contains(id T) bool {
s.lck.RLock()
defer s.lck.RUnlock()
_, ok := s.m[id]
return ok
}
// Get returns the value associated with the key,
// or a key missing error
func (s *SynchronisedMap[T, U]) Get(id T) (U, error) {
s.lck.RLock()
defer s.lck.RUnlock()
if t, ok := s.m[id]; ok {
return t, nil
}
var r U
return r, ErrMissingKey
}
// Remove deletes the key from the map
func (s *SynchronisedMap[T, U]) Remove(id T) {
s.lck.Lock()
defer s.lck.Unlock()
delete(s.m, id)
}
// Len returns the current length
func (s *SynchronisedMap[T, U]) Len() int {
s.lck.RLock()
defer s.lck.RUnlock()
return len(s.m)
}
func (s *SynchronisedMap[T, U]) snap() map[T]U {
s.lck.RLock()
defer s.lck.RUnlock()
m := map[T]U{}
for k, v := range s.m {
m[k] = v
}
return m
}
// String returns the contents of the map as a string,
// with entries ordered based on the key type T
func (s *SynchronisedMap[T, U]) String() string {
m := s.snap()
// Apply ordering so the output is deterministic
keys := SortedKeys[T, U](m)
buf := new(bytes.Buffer)
io.WriteString(buf, "map[")
for i, key := range keys {
io.WriteString(buf, fmt.Sprint(key))
io.WriteString(buf, ":")
io.WriteString(buf, fmt.Sprint(m[key]))
if i < len(keys)-1 {
io.WriteString(buf, " ")
}
}
io.WriteString(buf, "]")
return buf.String()
}
// Bytes serialises the current contents of the map
func (s *SynchronisedMap[T, U]) Bytes() ([]byte, error) {
b := new(bytes.Buffer)
enc := gob.NewEncoder(b)
if err := enc.Encode(s.snap()); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// Merge attempts to decode the slice, assuming it is of the
// same type as returned by Bytes(). If successful, then
// adds any missing key/value pairs into this instance of the map.
func (s *SynchronisedMap[T, U]) Merge(b []byte) error {
buf := new(bytes.Buffer)
buf.Write(b)
dec := gob.NewDecoder(buf)
m := map[T]U{}
if err := dec.Decode(&m); err != nil {
return err
}
s.lck.Lock()
defer s.lck.Unlock()
for k, v := range m {
if _, ok := s.m[k]; !ok {
s.m[k] = v
}
}
return nil
}