-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcmap.go
343 lines (306 loc) · 7.58 KB
/
cmap.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
package cmap
import (
"sync"
"sync/atomic"
"unsafe"
)
const (
mInitialSize = 1 << 4
mOverflowThreshold = 1 << 6
mOverflowGrowThreshold = 1 << 7
)
// Cmap is a "thread" safe map of type AnyComparableType:Any.
// To avoid lock bottlenecks this map is dived to several map shards.
// We can store different type key and value into the same map.
type Cmap struct {
lock sync.Mutex
inode unsafe.Pointer // *inode
count int64
}
type inode struct {
mask uintptr
overflow int64
growThreshold int64
shrinkThreshold int64
resizeInProgress int64
pred unsafe.Pointer // *inode
buckets []bucket
}
type entry struct {
key, value interface{}
}
type bucket struct {
lock sync.RWMutex
init int64
m map[interface{}]interface{}
frozen bool
}
// Store sets the value for a key.
func (m *Cmap) Store(key, value interface{}) {
hash := ehash(key)
for {
inode, b := m.getInodeAndBucket(hash)
if b.tryStore(m, inode, false, key, value) {
return
}
}
}
// Load returns the value stored in the map for a key, or nil if no
// value is present.
// The ok result indicates whether value was found in the map.
func (m *Cmap) Load(key interface{}) (value interface{}, ok bool) {
hash := ehash(key)
_, b := m.getInodeAndBucket(hash)
return b.tryLoad(key)
}
// LoadOrStore returns the existing value for the key if present.
// Otherwise, it stores and returns the given value.
// The loaded result is true if the value was loaded, false if stored.
func (m *Cmap) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) {
hash := ehash(key)
for {
inode, b := m.getInodeAndBucket(hash)
actual, loaded = b.tryLoad(key)
if loaded {
return
}
if b.tryStore(m, inode, true, key, value) {
return value, false
}
}
}
// Delete deletes the value for a key.
func (m *Cmap) Delete(key interface{}) {
hash := ehash(key)
for {
inode, b := m.getInodeAndBucket(hash)
if b.tryDelete(m, inode, key) {
return
}
}
}
// Range calls f sequentially for each key and value present in the map.
// If f returns false, range stops the iteration.
//
// Range does not necessarily correspond to any consistent snapshot of the Map's
// contents: no key will be visited more than once, but if the value for any key
// is stored or deleted concurrently, Range may reflect any mapping for that key
// from any point during the Range call.
//
// Range may be O(N) with the number of elements in the map even if f returns
// false after a constant number of calls.
func (m *Cmap) Range(f func(key, value interface{}) bool) {
n := m.getInode()
for i := 0; i < len(n.buckets); i++ {
b := &(n.buckets[i])
if !b.inited() {
n.initBucket(uintptr(i))
}
for _, e := range b.clone() {
if !f(e.key, e.value) {
return
}
}
}
}
// Count returns the number of elements within the map.
func (m *Cmap) Count() int {
return int(atomic.LoadInt64(&m.count))
}
// IsEmpty checks if map is empty.
func (m *Cmap) IsEmpty() bool {
return m.Count() == 0
}
func (m *Cmap) getInode() *inode {
n := (*inode)(atomic.LoadPointer(&m.inode))
if n == nil {
m.lock.Lock()
n = (*inode)(atomic.LoadPointer(&m.inode))
if n == nil {
n = &inode{
mask: uintptr(mInitialSize - 1),
growThreshold: int64(mInitialSize * mOverflowThreshold),
shrinkThreshold: 0,
buckets: make([]bucket, mInitialSize),
}
atomic.StorePointer(&m.inode, unsafe.Pointer(n))
}
m.lock.Unlock()
}
return n
}
func (m *Cmap) getInodeAndBucket(hash uintptr) (*inode, *bucket) {
n := m.getInode()
i := hash & n.mask
b := &(n.buckets[i])
if !b.inited() {
n.initBucket(i)
}
return n, b
}
func (n *inode) initBuckets() {
for i := range n.buckets {
n.initBucket(uintptr(i))
}
atomic.StorePointer(&n.pred, nil)
}
func (n *inode) initBucket(i uintptr) {
b := &(n.buckets[i])
b.lock.Lock()
if b.inited() {
b.lock.Unlock()
return
}
b.m = make(map[interface{}]interface{})
p := (*inode)(atomic.LoadPointer(&n.pred)) // predecessor
if p != nil {
if n.mask > p.mask {
// Grow
pb := &(p.buckets[i&p.mask])
if !pb.inited() {
p.initBucket(i & p.mask)
}
for k, v := range pb.freeze() {
hash := ehash(k)
if hash&n.mask == i {
b.m[k] = v
}
}
} else {
// Shrink
pb0 := &(p.buckets[i])
if !pb0.inited() {
p.initBucket(i)
}
pb1 := &(p.buckets[i+uintptr(len(n.buckets))])
if !pb1.inited() {
p.initBucket(i + uintptr(len(n.buckets)))
}
for k, v := range pb0.freeze() {
b.m[k] = v
}
for k, v := range pb1.freeze() {
b.m[k] = v
}
}
if len(b.m) > mOverflowThreshold {
atomic.AddInt64(&n.overflow, int64(len(b.m)-mOverflowThreshold))
}
}
atomic.StoreInt64(&b.init, 1)
b.lock.Unlock()
}
func (b *bucket) inited() bool {
return atomic.LoadInt64(&b.init) == 1
}
func (b *bucket) freeze() map[interface{}]interface{} {
b.lock.Lock()
b.frozen = true
m := b.m
b.lock.Unlock()
return m
}
func (b *bucket) clone() []entry {
b.lock.RLock()
entries := make([]entry, 0, len(b.m))
for k, v := range b.m {
entries = append(entries, entry{key: k, value: v})
}
b.lock.RUnlock()
return entries
}
func (b *bucket) tryLoad(key interface{}) (value interface{}, ok bool) {
b.lock.RLock()
value, ok = b.m[key]
b.lock.RUnlock()
return
}
func (b *bucket) tryStore(m *Cmap, n *inode, check bool, key, value interface{}) (done bool) {
b.lock.Lock()
if b.frozen {
b.lock.Unlock()
return
}
if check {
if _, ok := b.m[key]; ok {
b.lock.Unlock()
return
}
}
l0 := len(b.m) // Using length check existence is faster than accessing.
b.m[key] = value
length := len(b.m)
b.lock.Unlock()
if l0 == length {
return true
}
// Update counter
grow := atomic.AddInt64(&m.count, 1) >= n.growThreshold
if length > mOverflowThreshold {
grow = grow || atomic.AddInt64(&n.overflow, 1) >= mOverflowGrowThreshold
}
// Grow
if grow && atomic.CompareAndSwapInt64(&n.resizeInProgress, 0, 1) {
nlen := len(n.buckets) << 1
node := &inode{
mask: uintptr(nlen) - 1,
pred: unsafe.Pointer(n),
growThreshold: int64(nlen) * mOverflowThreshold,
shrinkThreshold: int64(nlen) >> 1,
buckets: make([]bucket, nlen),
}
ok := atomic.CompareAndSwapPointer(&m.inode, unsafe.Pointer(n), unsafe.Pointer(node))
if !ok {
panic("BUG: failed swapping head")
}
go node.initBuckets()
}
return true
}
func (b *bucket) tryDelete(m *Cmap, n *inode, key interface{}) (done bool) {
b.lock.Lock()
if b.frozen {
b.lock.Unlock()
return
}
l0 := len(b.m)
delete(b.m, key)
length := len(b.m)
b.lock.Unlock()
if l0 == length {
return true
}
// Update counter
shrink := atomic.AddInt64(&m.count, -1) < n.shrinkThreshold
if length >= mOverflowThreshold {
atomic.AddInt64(&n.overflow, -1)
}
// Shrink
if shrink && len(n.buckets) > mInitialSize && atomic.CompareAndSwapInt64(&n.resizeInProgress, 0, 1) {
nlen := len(n.buckets) >> 1
node := &inode{
mask: uintptr(nlen) - 1,
pred: unsafe.Pointer(n),
growThreshold: int64(nlen) * mOverflowThreshold,
shrinkThreshold: int64(nlen) >> 1,
buckets: make([]bucket, nlen),
}
ok := atomic.CompareAndSwapPointer(&m.inode, unsafe.Pointer(n), unsafe.Pointer(node))
if !ok {
panic("BUG: failed swapping head")
}
go node.initBuckets()
}
return true
}
func ehash(i interface{}) uintptr {
return nilinterhash(noescape(unsafe.Pointer(&i)), 0xdeadbeef)
}
//go:linkname nilinterhash runtime.nilinterhash
func nilinterhash(p unsafe.Pointer, h uintptr) uintptr
//go:nocheckptr
//go:nosplit
func noescape(p unsafe.Pointer) unsafe.Pointer {
x := uintptr(p)
return unsafe.Pointer(x ^ 0)
}