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
#[macro_export]
macro_rules! register_hook {
($b:expr, $p:expr, $t:ty, $h:expr) => {
{
let bus: &$crate::EventBus = $b;
let hook = $h;
let pri = $p;
{
static EVENT_ID: ::std::sync::atomic::AtomicUsize = std::sync::atomic::ATOMIC_USIZE_INIT;
static EVENT_ID_INIT: ::std::sync::Once = std::sync::ONCE_INIT;
static DUMMY: ::std::marker::PhantomData<dyn Fn(&mut $t) + Send + Sync> = ::std::marker::PhantomData;
EVENT_ID_INIT.call_once(|| {
EVENT_ID.store($crate::get_event_id::<$t>(), std::sync::atomic::Ordering::Relaxed);
});
let id = EVENT_ID.load(std::sync::atomic::Ordering::Relaxed);
$crate::register::<$t, _>(bus, pri, hook, id)
}
}
}
}
#[macro_export]
macro_rules! post_event {
($b:expr, $t:ty, $e:expr) => {
{
let bus: &$crate::EventBus = $b;
let event: &mut _ = $e;
{
static CANCELLABLE: ::std::sync::atomic::AtomicBool = ::std::sync::atomic::ATOMIC_BOOL_INIT;
static CANCELLABLE_INIT: ::std::sync::Once = ::std::sync::ONCE_INIT;
CANCELLABLE_INIT.call_once(|| {
CANCELLABLE.store(<$crate::Event>::cancellable(event), std::sync::atomic::Ordering::Relaxed);
});
let cancellable = CANCELLABLE.load(std::sync::atomic::Ordering::Relaxed);
static EVENT_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::ATOMIC_USIZE_INIT;
static EVENT_ID_INIT: ::std::sync::Once = ::std::sync::ONCE_INIT;
static DUMMY: ::std::marker::PhantomData<dyn Fn(&mut $t) + Send + Sync> = ::std::marker::PhantomData;
EVENT_ID_INIT.call_once(|| {
EVENT_ID.store($crate::get_event_id::<$t>(), std::sync::atomic::Ordering::Relaxed);
});
let id = EVENT_ID.load(std::sync::atomic::Ordering::Relaxed);
let event: &mut $t = event;
let handlers = $crate::get_post_targets::<$t>(bus, event, id);
for (_pri, fun) in handlers.iter() {
fun(event);
if cancellable && <$t as $crate::Event>::cancelled(event) {
break;
}
}
cancellable && <$t as $crate::Event>::cancelled(event)
}
}
}
}
pub trait Event: 'static {
fn cancellable(&self) -> bool {
false
}
fn cancelled(&self) -> bool {
false
}
fn set_cancelled(&mut self, cancel: bool) {
let _ = cancel;
panic!("not cancellable");
}
}
pub struct EventBus {
id: usize,
dropper: Mutex<LinkedList<Box<dyn Fn(usize) + Send + Sync>>>,
}
#[macro_use]
extern crate lazy_static;
extern crate anymap;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::ATOMIC_USIZE_INIT;
use std::sync::atomic::Ordering as AtomicOrdering;
use std::sync::Mutex;
use std::collections::LinkedList;
use std::any::Any;
use std::sync::Arc;
use std::sync::RwLock;
use std::mem;
mod id_map {
use std::marker::PhantomData;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::ATOMIC_USIZE_INIT;
use std::sync::atomic::Ordering as AtomicOrdering;
use std::sync::Mutex;
use std::sync::Arc;
use super::Event;
use super::Handlers;
lazy_static! {
static ref EVENT_ID_MAP: Mutex<::anymap::Map<::anymap::any::Any + Send + Sync>> = Mutex::new(::anymap::Map::new());
}
struct EventId<T: Event + ?Sized> {
id: usize,
_t: PhantomData<dyn Fn(&mut T) + Send + Sync>
}
pub fn get_event_id<T: Event + ?Sized>() -> usize {
static EVENT_ID_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
let id = EVENT_ID_MAP.lock().expect("failed to allocate event id").entry::<EventId<T>>().or_insert_with(|| EventId { id: EVENT_ID_COUNT.fetch_add(1, AtomicOrdering::SeqCst), _t: PhantomData }).id;
let handlers: Arc<Handlers<T>> = Default::default();
Arc::make_mut(&mut super::HANDLERS.write().expect("???")).push(handlers);
id
}
}
pub fn get_event_id<T: Event + ?Sized>() -> usize {
id_map::get_event_id::<T>()
}
type RwArcVec<T> = RwLock<Arc<Vec<T>>>;
struct Handlers<T: Event + ?Sized>(RwArcVec<RwArcVec<(i32, Arc<dyn Fn(&mut T) + Send + Sync>)>>);
impl<T: Event + ?Sized> Default for Handlers<T> {
fn default() -> Self {
Handlers(Default::default())
}
}
lazy_static! {
static ref HANDLERS: RwArcVec<Arc<dyn Any + Send + Sync>> = Default::default();
}
pub fn get_post_targets<T: Event + ?Sized>(bus: &EventBus, _event: &mut T, id: usize) -> Arc<Vec<(i32, Arc<dyn Fn(&mut T) + Send + Sync>)>> {
let target: Option<Arc<Vec<_>>> = HANDLERS.read().expect("failed to lock for reading").get(id).map(|arc| Arc::clone(arc))
.map(|any| Arc::downcast::<Handlers<T>>(any).expect("Wrong id"))
.and_then(|handlers| handlers.0.read().expect("failed to lock for reading").get(bus.id).map(|hooks| Arc::clone(&*hooks.read().expect("failed to lock for reading"))));
target.unwrap_or_else(|| Arc::new(Vec::new()))
}
pub fn register<T: Event + ?Sized, F: for<'a> Fn(&'a mut T) + Send + Sync + 'static>(bus: &EventBus, priority: i32, handler: F, id: usize) {
HANDLERS.read().expect("failed to lock for reading").get(id).map(|arc| Arc::clone(arc))
.map(|any| Arc::downcast::<Handlers<T>>(any).expect("Wrong id"))
.map(|handlers| {
let mut lock = handlers.0.read().expect("failed to lock for reading");
if lock.len() <= id {
mem::drop(lock);
let mut wlock = handlers.0.write().expect("failed to lock for writing");
if wlock.len() <= id { let vec = Arc::get_mut(&mut wlock).expect("failed to mutate busses");
let count = id - vec.len() + 1;
vec.reserve_exact(count);
for _ in 0..count {
vec.push(Default::default());
}
}
mem::drop(wlock);
lock = handlers.0.read().expect("failed to lock for reading");
}
let option = lock.get(bus.id);
let hooks = option.expect("failed to make vecs");
let hook: (i32, Arc<dyn Fn(&mut T) + Send + Sync + 'static>) = (priority, Arc::new(handler));
let mut wlock = hooks.write().expect("failed to lock for writing");
let vec = Arc::make_mut(&mut wlock);
let pos = match vec.binary_search_by(|probe| probe.0.cmp(&priority)) { Ok(p) => p, Err(p) => p };
vec.insert(pos, hook);
}).expect("No such id");
}
static BUS_ID: AtomicUsize = ATOMIC_USIZE_INIT;
lazy_static! {
static ref FREED_BUS_IDS: Mutex<LinkedList<usize>> = Mutex::new(LinkedList::new());
}
impl EventBus {
pub fn new() -> EventBus {
EventBus {
id: FREED_BUS_IDS.lock().unwrap().pop_front().unwrap_or_else(|| BUS_ID.fetch_add(1, AtomicOrdering::SeqCst)),
dropper: Default::default(),
}
}
}
impl Drop for EventBus {
fn drop(&mut self) {
}
}