forked from ninibe/netlog
/
streamer_atomicmap.go
82 lines (66 loc) · 1.84 KB
/
streamer_atomicmap.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
// generated file - DO NOT EDIT
// command: atomicmapper -pointer -type netlog/biglog.Streamer
package netlog
import (
"sync"
"sync/atomic"
"github.com/ninibe/netlog/biglog"
)
// StreamerAtomicMap is a copy-on-write thread-safe map of pointers to Streamer
type StreamerAtomicMap struct {
mu sync.Mutex
val atomic.Value
}
type _StreamerMap map[string]*biglog.Streamer
// NewStreamerAtomicMap returns a new initialized StreamerAtomicMap
func NewStreamerAtomicMap() *StreamerAtomicMap {
am := &StreamerAtomicMap{}
am.val.Store(make(_StreamerMap, 0))
return am
}
// Get returns a pointer to Streamer for a given key
func (am *StreamerAtomicMap) Get(key string) (value *biglog.Streamer, ok bool) {
value, ok = am.val.Load().(_StreamerMap)[key]
return value, ok
}
// GetAll returns the underlying map of pointers to Streamer
// this map must NOT be modified, to change the map safely use the Set and Delete
// functions and Get the value again
func (am *StreamerAtomicMap) GetAll() map[string]*biglog.Streamer {
return am.val.Load().(_StreamerMap)
}
// Len returns the number of elements in the map
func (am *StreamerAtomicMap) Len() int {
return len(am.val.Load().(_StreamerMap))
}
// Set inserts in the map a pointer to Streamer under a given key
func (am *StreamerAtomicMap) Set(key string, value *biglog.Streamer) {
am.mu.Lock()
defer am.mu.Unlock()
m1 := am.val.Load().(_StreamerMap)
m2 := make(_StreamerMap, len(m1)+1)
for k, v := range m1 {
m2[k] = v
}
m2[key] = value
am.val.Store(m2)
return
}
// Delete removes the pointer to Streamer under key from the map
func (am *StreamerAtomicMap) Delete(key string) {
am.mu.Lock()
defer am.mu.Unlock()
m1 := am.val.Load().(_StreamerMap)
_, ok := m1[key]
if !ok {
return
}
m2 := make(_StreamerMap, len(m1)-1)
for k, v := range m1 {
if k != key {
m2[k] = v
}
}
am.val.Store(m2)
return
}