forked from corbym/gogiven
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafemap.go
55 lines (48 loc) · 1.13 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
package gogiven
import (
"github.com/corbym/gogiven/base"
"sync"
)
// safeMap is used internally to hold a threadsafe copy of the global test state.
type safeMap struct {
sync.RWMutex
internal map[string]interface{}
}
func newSafeMap() *safeMap {
return &safeMap{
internal: make(map[string]interface{}),
}
}
//Load a key from the map
func (rm *safeMap) Load(key string) (value interface{}, ok bool) {
rm.RLock()
defer rm.RUnlock()
result, ok := rm.internal[key]
return result, ok
}
//Store a value against a key from the map
func (rm *safeMap) Store(key string, value interface{}) {
rm.Lock()
rm.internal[key] = value
rm.Unlock()
}
//Keys returns an array of keys that the map contains
func (rm *safeMap) Keys() []string {
rm.RLock()
defer rm.RUnlock()
keys := make([]string, 0, len(rm.internal))
for k := range rm.internal {
keys = append(keys, k)
}
return keys
}
// AsMapOfSome copies the safeMap into a normal map[string]*Some type
func (rm *safeMap) AsMapOfSome() *base.SomeMap {
rm.RLock()
defer rm.RUnlock()
var newMap = &base.SomeMap{}
for k, v := range rm.internal {
(*newMap)[k] = v.(*base.Some)
}
return newMap
}