-
Notifications
You must be signed in to change notification settings - Fork 1
/
concurrent_map.go
84 lines (72 loc) · 1.77 KB
/
concurrent_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
package maps
import "sync"
// NewConcurrentMap creates a new concurrent map
func NewConcurrentMap() *ConcurrentMap {
return &ConcurrentMap{
internalMap: make(map[string]interface{}),
lock: &sync.RWMutex{},
}
}
// ConcurrentMap concurrent map
type ConcurrentMap struct {
internalMap map[string]interface{}
lock *sync.RWMutex
}
// Set concurrent set to map
func (c *ConcurrentMap) Set(key string, value interface{}) {
c.lock.Lock()
c.internalMap[key] = value
c.lock.Unlock()
}
// Get concurrent get from map
func (c *ConcurrentMap) Get(key string) (interface{}, bool) {
c.lock.RLock()
value, ok := c.internalMap[key]
c.lock.RUnlock()
return value, ok
}
// Remove concurrent remove from map
func (c *ConcurrentMap) Remove(key string) {
c.lock.Lock()
delete(c.internalMap, key)
c.lock.Unlock()
}
// ContainsKey concurrent contains key in map
func (c *ConcurrentMap) ContainsKey(key string) bool {
_, ok := c.Get(key)
return ok
}
// ContainsEntry concurrent contains entry in map
func (c *ConcurrentMap) ContainsEntry(key string, value interface{}) bool {
existingValue, ok := c.Get(key)
return ok && existingValue == value
}
// Size concurrent size of map
func (c *ConcurrentMap) Size() int {
c.lock.RLock()
size := len(c.internalMap)
c.lock.RUnlock()
return size
}
// IsEmpty concurrent check of map's emptiness
func (c *ConcurrentMap) IsEmpty() bool {
return c.Size() == 0
}
// Keys concurrent retrieval of keys from map
func (c *ConcurrentMap) Keys() []string {
c.lock.RLock()
keys := make([]string, len(c.internalMap))
i := 0
for key := range c.internalMap {
keys[i] = key
i++
}
c.lock.RUnlock()
return keys
}
// Clear concurrent map
func (c *ConcurrentMap) Clear() {
c.lock.Lock()
c.internalMap = make(map[string]interface{})
c.lock.Unlock()
}