-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafemap.go
86 lines (75 loc) · 1.44 KB
/
safemap.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
package safemap
import "sync"
type SafeMap struct {
lock *sync.RWMutex
m map[interface{}]interface{}
}
func NewSafeMap() *SafeMap {
return &SafeMap{
lock: new(sync.RWMutex),
m: make(map[interface{}]interface{}),
}
}
func (s *SafeMap) Get(key interface{}) interface{} {
s.lock.RLock()
defer s.lock.RUnlock()
if val, ok := s.m[key]; ok {
return val
}
return nil
}
func (s *SafeMap) Set(key interface{}, value interface{}) bool {
s.lock.Lock()
defer s.lock.Unlock()
if val, ok := s.m[key]; !ok {
s.m[key] = value
} else if val != value {
s.m[key] = value
} else {
return false
}
return true
}
func (s *SafeMap) Delete(key interface{}) {
s.lock.Lock()
defer s.lock.Unlock()
delete(s.m, key)
}
func (s *SafeMap) Exist(key interface{}) bool {
s.lock.RLock()
defer s.lock.RUnlock()
_, ok := s.m[key]
return ok
}
func (s *SafeMap) Len() int {
s.lock.RLock()
defer s.lock.RUnlock()
return len(s.m)
}
func (s *SafeMap) Items() map[interface{}]interface{} {
s.lock.RLock()
defer s.lock.RUnlock()
r := make(map[interface{}]interface{})
for k, v := range s.m {
r[k] = v
}
return r
}
func (s *SafeMap) Keys() []interface{} {
s.lock.RLock()
defer s.lock.RUnlock()
r := make([]interface{}, 0)
for k, _ := range s.m {
r = append(r, k)
}
return r
}
func (s *SafeMap) Values() []interface{} {
s.lock.RLock()
defer s.lock.RUnlock()
r := make([]interface{}, 0)
for _, v := range s.m {
r = append(r, v)
}
return r
}