-
Notifications
You must be signed in to change notification settings - Fork 6
/
map.go
62 lines (49 loc) · 1 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
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package safemap
import (
"fmt"
"sync"
"sync/atomic"
)
type Map struct {
sm sync.Map
count int64
}
func New() *Map {
return &Map{
count: 0,
}
}
func (m *Map) Load(key string) (value interface{}, ok bool) {
return m.sm.Load(key)
}
func (m *Map) MustLoad(key string) interface{} {
v, ok := m.Load(key)
if !ok {
panic(fmt.Errorf("key %s not exist", key))
}
return v
}
func (m *Map) Range(f func(key string, value interface{}) bool) {
m.sm.Range(func(key, value interface{}) bool {
return f(key.(string), value)
})
}
func (m *Map) Store(key string, value interface{}) {
atomic.AddInt64(&m.count, 1)
m.sm.Store(key, value)
}
func (m *Map) Delete(key string) {
if m.count > 0 {
atomic.AddInt64(&m.count, -1)
}
m.sm.Delete(key)
}
func (m *Map) Length() int64 {
return m.count
}
func (m *Map) Empty() bool {
return m.count == 0
}