-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd.go
77 lines (63 loc) · 1.92 KB
/
add.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
package events
import (
"reflect"
)
// AddOptions is used by the Add method on a Manager
// and the package-level Add function.
// The Name and Names fields are used together to uniquely
// identify an event.
// The Handler field contains the function that will be
// added.
// The Order field is used to determine whether a handler
// will be called before or after another: lower values
// get called first.
// The ShouldWaitTillDone field determines whether the Run
// method (or package-level Run function) will wait for
// the handler to finish its work before returning.
type AddOptions struct {
Name string
Names []string
Handler HandlerFunc
Order HandlerOrder
ShouldWaitTillDone bool
}
// Add sets up a handler function that will be called
// when a named event is run.
func (m *Manager) Add(options AddOptions) {
if options.Handler == nil {
return
}
initManagerMethod(&m)
bitmaskValue := m.bitmaskValueFromNames(options.Name, options.Names)
defer m.dataMutex.Unlock()
m.dataMutex.Lock()
// just update event bitmask value if handler function is already found
{
p1 := reflect.ValueOf(options.Handler).Pointer()
for _, datum := range m.inner.data {
if datum.order == options.Order && datum.shouldWaitTillDone == options.ShouldWaitTillDone {
p2 := reflect.ValueOf(datum.handler).Pointer()
if p1 == p2 {
func() {
defer datum.mainMutex.Unlock()
datum.mainMutex.Lock()
datum.bitmaskValue.Combine(bitmaskValue)
}()
return
}
}
}
}
datum := handlerDatum{
bitmaskValue: bitmaskValue,
order: options.Order,
handler: options.Handler,
shouldWaitTillDone: options.ShouldWaitTillDone,
doneChan: make(chan struct{}),
}
m.inner.data = append(m.inner.data, &datum)
}
// Add calls the Add method on the default manager.
func Add(options AddOptions) {
defaultManager.Add(options)
}