-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlisteners.go
89 lines (74 loc) · 1.4 KB
/
listeners.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
// +build !go1.9
package listener
import (
"sync"
)
type (
Listener interface {
Broadcast(value interface{})
Receive() (interface{}, bool)
Wait() interface{}
}
Listeners struct {
creater func() Listener
lmap map[interface{}]Listener
mu sync.RWMutex
}
)
func NewListeners(creater ...func() Listener) *Listeners {
var c func() Listener = NewListener
if len(creater) != 0 && creater[0] != nil {
c = creater[0]
}
return &Listeners{
creater: c,
lmap: make(map[interface{}]Listener, 8),
}
}
func (l *Listeners) GetOrCreate(key interface{}) (li Listener, found bool) {
l.mu.RLock()
li, found = l.lmap[key]
l.mu.RUnlock()
if !found {
l.mu.Lock()
li, found = l.lmap[key]
if !found {
li = l.creater()
l.lmap[key] = li
}
l.mu.Unlock()
}
return
}
func (l *Listeners) Get(key interface{}) (li Listener, found bool) {
l.mu.RLock()
li, found = l.lmap[key]
l.mu.RUnlock()
return
}
func (l *Listeners) Len() int {
return len(l.lmap)
}
func (l *Listeners) Delete(key interface{}) {
l.mu.Lock()
delete(l.lmap, key)
l.mu.Unlock()
}
func (l *Listeners) Put(key interface{}, li Listener) (old Listener) {
l.mu.Lock()
old = l.lmap[key]
if li != nil {
l.lmap[key] = li
}
l.mu.Unlock()
return
}
func (l *Listeners) Range(f func(key interface{}, li Listener) bool) {
l.mu.RLock()
defer l.mu.RUnlock()
for key, li := range l.lmap {
if !f(key, li) {
break
}
}
}