-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
91 lines (75 loc) · 1.49 KB
/
handler.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
90
91
package observer
import (
"reflect"
"sync"
)
type handler struct {
t reflect.Type
observer interface{}
callback reflect.Value
}
func newHandler(t reflect.Type, observer interface{}, callback reflect.Value) *handler {
return &handler{
t: t,
observer: observer,
callback: callback,
}
}
func (h *handler) Same(b *handler) bool {
if h.t.String() == b.t.String() {
return true
}
return false
}
func (h *handler) Call(params ...reflect.Value) []reflect.Value {
return h.callback.Call(params)
}
type handlers []*handler
type syncHandler struct {
rwlock *sync.RWMutex
m map[string]handlers
}
func (s *syncHandler) Append(topic string, sameCheck bool, h *handler) {
s.rwlock.Lock()
defer s.rwlock.Unlock()
if sameCheck {
for _, v := range s.m[topic][:] {
if v == h {
return
}
}
}
s.m[topic] = append(s.m[topic], h)
}
func (s *syncHandler) Range(fc func(string, handlers)) {
s.rwlock.RLock()
defer s.rwlock.RUnlock()
for topic, h := range s.m {
fc(topic, h)
}
}
func (s *syncHandler) Del(topic string, h *handler) {
s.rwlock.Lock()
defer s.rwlock.Unlock()
handlers := s.m[topic]
for i, v := range handlers[:] {
if v != h {
continue
}
// 0,1,2,3
left := handlers[:i]
right := handlers[i+1:]
left = append(left, right...)
if len(left) <= 0 {
delete(s.m, topic)
return
}
s.m[topic] = left
return
}
}
func (s *syncHandler) Get(topic string) handlers {
s.rwlock.RLock()
defer s.rwlock.RUnlock()
return s.m[topic][:]
}