-
Notifications
You must be signed in to change notification settings - Fork 1
/
intlisteners.go
81 lines (68 loc) · 1.25 KB
/
intlisteners.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
package listener
import (
"sync"
)
type (
IntListeners struct {
creater func() Listener
lmap map[int]Listener
mu sync.RWMutex
}
)
func NewIntListeners(creater ...func() Listener) *IntListeners {
var c func() Listener = NewListener
if len(creater) != 0 && creater[0] != nil {
c = creater[0]
}
return &IntListeners{
creater: c,
lmap: make(map[int]Listener, 8),
}
}
func (l *IntListeners) GetOrCreate(key int) (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 *IntListeners) Get(key int) (li Listener, found bool) {
l.mu.RLock()
li, found = l.lmap[key]
l.mu.RUnlock()
return
}
func (l *IntListeners) Len() int {
return len(l.lmap)
}
func (l *IntListeners) Delete(key int) {
l.mu.Lock()
delete(l.lmap, key)
l.mu.Unlock()
}
func (l *IntListeners) Put(key int, li Listener) (old Listener) {
l.mu.Lock()
old = l.lmap[key]
if li != nil {
l.lmap[key] = li
}
l.mu.Unlock()
return
}
func (l *IntListeners) Range(f func(key int, li Listener) bool) {
l.mu.RLock()
defer l.mu.RUnlock()
for key, li := range l.lmap {
if !f(key, li) {
break
}
}
}