-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconcurrent_multi_map.go
105 lines (91 loc) · 2.23 KB
/
concurrent_multi_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
package maps
import "sync"
// NewConcurrentMultiMap creates a new concurrent multi map
func NewConcurrentMultiMap() *ConcurrentMultiMap {
return &ConcurrentMultiMap{
internalMap: make(map[string][]interface{}),
lock: &sync.RWMutex{},
}
}
// ConcurrentMultiMap concurrent map
type ConcurrentMultiMap struct {
internalMap map[string][]interface{}
lock *sync.RWMutex
}
// Set concurrent set to map
func (c *ConcurrentMultiMap) Set(key string, values []interface{}) {
c.lock.Lock()
c.internalMap[key] = values
c.lock.Unlock()
}
// Append concurrent append to map
func (c *ConcurrentMultiMap) Append(key string, value interface{}) {
c.lock.Lock()
values, ok := c.internalMap[key]
if !ok {
values = []interface{}{}
}
values = append(values, value)
c.internalMap[key] = values
c.lock.Unlock()
}
// Get concurrent get from map
func (c *ConcurrentMultiMap) 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 *ConcurrentMultiMap) Remove(key string) {
c.lock.Lock()
delete(c.internalMap, key)
c.lock.Unlock()
}
// ContainsKey concurrent contains key in map
func (c *ConcurrentMultiMap) ContainsKey(key string) bool {
_, ok := c.Get(key)
return ok
}
// ContainsEntry concurrent contains entry in map
func (c *ConcurrentMultiMap) ContainsEntry(key string, value interface{}) bool {
existingValues, ok := c.Get(key)
if !ok {
return false
}
for _, existingValue := range existingValues {
if existingValue == value {
return true
}
}
return false
}
// Size concurrent size of map
func (c *ConcurrentMultiMap) Size() int {
c.lock.RLock()
size := len(c.internalMap)
c.lock.RUnlock()
return size
}
// IsEmpty concurrent check of map's emptiness
func (c *ConcurrentMultiMap) IsEmpty() bool {
return c.Size() == 0
}
// Keys concurrent retrieval of keys from map
func (c *ConcurrentMultiMap) 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 *ConcurrentMultiMap) Clear() {
c.lock.Lock()
c.internalMap = make(map[string][]interface{})
c.lock.Unlock()
}