forked from tcolgate/godinstall
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafemap.go
61 lines (54 loc) · 1.11 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
package main
import (
"sync"
)
// SafeMap is a thread safe map stolen from somwhere else
type SafeMap struct {
sync.RWMutex
bm map[interface{}]interface{}
}
// NewSafeMap creates a thread safe map
func NewSafeMap() *SafeMap {
return &SafeMap{
RWMutex: sync.RWMutex{},
bm: make(map[interface{}]interface{}),
}
}
//Get from maps return the k's value
func (m *SafeMap) Get(k interface{}) interface{} {
m.RLock()
defer m.RUnlock()
if val, ok := m.bm[k]; ok {
return val
}
return nil
}
// Set maps the given key and value. Returns false
// if the key is already in the map and changes nothing.
func (m *SafeMap) Set(k interface{}, v interface{}) bool {
m.Lock()
defer m.Unlock()
if val, ok := m.bm[k]; !ok {
m.bm[k] = v
} else if val != v {
m.bm[k] = v
} else {
return false
}
return true
}
// Check returns true if k is exist in the map.
func (m *SafeMap) Check(k interface{}) bool {
m.RLock()
defer m.RUnlock()
if _, ok := m.bm[k]; !ok {
return false
}
return true
}
// Delete removes a key from a map
func (m *SafeMap) Delete(k interface{}) {
m.Lock()
defer m.Unlock()
delete(m.bm, k)
}