-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathevents.go
397 lines (331 loc) · 10.2 KB
/
events.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// Package events provides simple EventEmmiter support for Go Programming Language
package events
import (
"log"
"reflect"
"sync"
"sync/atomic"
)
const (
// Version current version number
Version = "0.0.3"
// DefaultMaxListeners is the number of max listeners per event
// default EventEmitters will print a warning if more than x listeners are
// added to it. This is a useful default which helps finding memory leaks.
// Defaults to 0, which means unlimited
DefaultMaxListeners = 0
// EnableWarning prints a warning when trying to add an event which it's len is equal to the maxListeners
// Defaults to false, which means it does not prints a warning
EnableWarning = false
)
type (
// EventName is just a type of string, it's the event name
EventName string
// Listener is the type of a Listener, it's a func which receives any,optional, arguments from the caller/emmiter
Listener func(...interface{})
// Events the type for registered listeners, it's just a map[string][]func(...interface{})
Events map[EventName][]Listener
// EventEmmiter is the message/or/event manager
EventEmmiter interface {
// AddListener is an alias for .On(eventName, listener).
AddListener(EventName, ...Listener)
// Emit fires a particular event,
// Synchronously calls each of the listeners registered for the event named
// eventName, in the order they were registered,
// passing the supplied arguments to each.
Emit(EventName, ...interface{})
// EventNames returns an array listing the events for which the emitter has registered listeners.
// The values in the array will be strings.
EventNames() []EventName
// GetMaxListeners returns the max listeners for this emmiter
// see SetMaxListeners
GetMaxListeners() int
// ListenerCount returns the length of all registered listeners to a particular event
ListenerCount(EventName) int
// Listeners returns a copy of the array of listeners for the event named eventName.
Listeners(EventName) []Listener
// On registers a particular listener for an event, func receiver parameter(s) is/are optional
On(EventName, ...Listener)
// Once adds a one time listener function for the event named eventName.
// The next time eventName is triggered, this listener is removed and then invoked.
Once(EventName, ...Listener)
// RemoveAllListeners removes all listeners, or those of the specified eventName.
// Note that it will remove the event itself.
// Returns an indicator if event and listeners were found before the remove.
RemoveAllListeners(EventName) bool
// RemoveListener removes given listener from the event named eventName.
// Returns an indicator whether listener was removed
RemoveListener(EventName, Listener) bool
// Clear removes all events and all listeners, restores Events to an empty value
Clear()
// SetMaxListeners obviously this function allows the MaxListeners
// to be decrease or increase. Set to zero for unlimited
SetMaxListeners(int)
// Len returns the length of all registered events
Len() int
}
emmiter struct {
maxListeners int
evtListeners Events
mu sync.RWMutex
}
)
// CopyTo copies the event listeners to an EventEmmiter
func (e Events) CopyTo(emmiter EventEmmiter) {
if e != nil && len(e) > 0 {
// register the events to/with their listeners
for evt, listeners := range e {
if len(listeners) > 0 {
emmiter.AddListener(evt, listeners...)
}
}
}
}
// New returns a new, empty, EventEmmiter
func New() EventEmmiter {
return &emmiter{maxListeners: DefaultMaxListeners, evtListeners: Events{}}
}
var (
_ EventEmmiter = &emmiter{}
defaultEmmiter = New()
)
// AddListener is an alias for .On(eventName, listener).
func AddListener(evt EventName, listener ...Listener) {
defaultEmmiter.AddListener(evt, listener...)
}
func (e *emmiter) AddListener(evt EventName, listener ...Listener) {
if len(listener) == 0 {
return
}
e.mu.Lock()
defer e.mu.Unlock()
if e.evtListeners == nil {
e.evtListeners = Events{}
}
listeners := e.evtListeners[evt]
if e.maxListeners > 0 && len(listeners) == e.maxListeners {
if EnableWarning {
log.Printf(`(events) warning: possible EventEmitter memory '
leak detected. %d listeners added. '
Use emitter.SetMaxListeners(n int) to increase limit.`, len(listeners))
}
return
}
if listeners == nil {
listeners = make([]Listener, e.maxListeners)
}
e.evtListeners[evt] = append(listeners, listener...)
}
// Emit fires a particular event,
// Synchronously calls each of the listeners registered for the event named
// eventName, in the order they were registered,
// passing the supplied arguments to each.
func Emit(evt EventName, data ...interface{}) {
defaultEmmiter.Emit(evt, data...)
}
func (e *emmiter) Emit(evt EventName, data ...interface{}) {
e.mu.RLock()
defer e.mu.RUnlock()
if e.evtListeners == nil {
return // has no listeners to emit/speak yet
}
if listeners := e.evtListeners[evt]; len(listeners) > 0 {
for i := range listeners {
l := listeners[i]
if l != nil {
l(data...)
}
}
}
}
// EventNames returns an array listing the events for which the emitter has registered listeners.
// The values in the array will be strings.
func EventNames() []EventName {
return defaultEmmiter.EventNames()
}
func (e *emmiter) EventNames() []EventName {
if e.evtListeners == nil || e.Len() == 0 {
return nil
}
names := make([]EventName, 0, e.Len())
i := 0
for k := range e.evtListeners {
names = append(names, k)
i++
}
return names
}
// GetMaxListeners returns the max listeners for this emmiter
// see SetMaxListeners
func GetMaxListeners() int {
return defaultEmmiter.GetMaxListeners()
}
func (e *emmiter) GetMaxListeners() int {
return e.maxListeners
}
// ListenerCount returns the length of all registered listeners to a particular event
func ListenerCount(evt EventName) int {
return defaultEmmiter.ListenerCount(evt)
}
func (e *emmiter) ListenerCount(evt EventName) (count int) {
e.mu.RLock()
evtListeners := e.evtListeners[evt]
e.mu.RUnlock()
return e.listenerCount(evtListeners)
}
func (e *emmiter) listenerCount(evtListeners []Listener) (count int) {
for _, l := range evtListeners {
if l == nil {
continue
}
count++
}
return
}
// Listeners returns a copy of the array of listeners for the event named eventName.
func Listeners(evt EventName) []Listener {
return defaultEmmiter.Listeners(evt)
}
func (e *emmiter) Listeners(evt EventName) []Listener {
if e.evtListeners == nil {
return nil
}
var listeners []Listener
if evtListeners := e.evtListeners[evt]; evtListeners != nil {
// do not pass any inactive/removed listeners(nil)
for _, l := range evtListeners {
if l == nil {
continue
}
listeners = append(listeners, l)
}
if len(listeners) > 0 {
return listeners
}
}
return nil
}
// On registers a particular listener for an event, func receiver parameter(s) is/are optional
func On(evt EventName, listener ...Listener) {
defaultEmmiter.On(evt, listener...)
}
func (e *emmiter) On(evt EventName, listener ...Listener) {
e.AddListener(evt, listener...)
}
// Once adds a one time listener function for the event named eventName.
// The next time eventName is triggered, this listener is removed and then invoked.
func Once(evt EventName, listener ...Listener) {
defaultEmmiter.Once(evt, listener...)
}
type oneTimelistener struct {
evt EventName
emitter *emmiter
listener Listener
fired int32
executeRef Listener
}
func (l *oneTimelistener) execute(vals ...interface{}) {
if atomic.CompareAndSwapInt32(&l.fired, 0, 1) {
l.listener(vals...)
go l.emitter.RemoveListener(l.evt, l.executeRef)
}
}
func (e *emmiter) Once(evt EventName, listener ...Listener) {
if len(listener) == 0 {
return
}
var modifiedListeners []Listener
for _, listener := range listener {
oneTime := &oneTimelistener{
evt: evt,
emitter: e,
listener: listener,
}
oneTime.executeRef = oneTime.execute
modifiedListeners = append(modifiedListeners, oneTime.executeRef)
}
e.AddListener(evt, modifiedListeners...)
}
// RemoveAllListeners removes all listeners, or those of the specified eventName.
// Note that it will remove the event itself.
// Returns an indicator if event and listeners were found before the remove.
func RemoveAllListeners(evt EventName) bool {
return defaultEmmiter.RemoveAllListeners(evt)
}
func (e *emmiter) RemoveAllListeners(evt EventName) bool {
e.mu.Lock()
defer e.mu.Unlock()
if e.evtListeners == nil {
return false // has nothing to remove
}
if listeners, ok := e.evtListeners[evt]; ok {
count := e.listenerCount(listeners)
delete(e.evtListeners, evt)
return count > 0
}
return false
}
// RemoveListener removes the specified listener from the listener array for the event named eventName.
func (e *emmiter) RemoveListener(evt EventName, listener Listener) bool {
if e.evtListeners == nil {
return false
}
if listener == nil {
return false
}
e.mu.Lock()
defer e.mu.Unlock()
listeners := e.evtListeners[evt]
if listeners == nil {
return false
}
idx := -1
listenerPointer := reflect.ValueOf(listener).Pointer()
for index, item := range listeners {
itemPointer := reflect.ValueOf(item).Pointer()
if itemPointer == listenerPointer {
idx = index
break
}
}
if idx < 0 {
return false
}
var modifiedListeners []Listener = nil
if len(listeners) > 1 {
modifiedListeners = append(listeners[:idx], listeners[idx+1:]...)
}
e.evtListeners[evt] = modifiedListeners
return true
}
// Clear removes all events and all listeners, restores Events to an empty value
func Clear() {
defaultEmmiter.Clear()
}
func (e *emmiter) Clear() {
e.evtListeners = Events{}
}
// SetMaxListeners obviously this function allows the MaxListeners
// to be decrease or increase. Set to zero for unlimited
func SetMaxListeners(n int) {
defaultEmmiter.SetMaxListeners(n)
}
func (e *emmiter) SetMaxListeners(n int) {
if n < 0 {
if EnableWarning {
log.Printf("(events) warning: MaxListeners must be positive number, tried to set: %d", n)
return
}
}
e.maxListeners = n
}
// Len returns the length of all registered events
func Len() int {
return defaultEmmiter.Len()
}
func (e *emmiter) Len() int {
if e.evtListeners == nil {
return 0
}
return len(e.evtListeners)
}