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
// std
//use std::collections::HashMap;
//use std::marker::PhantomData;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering, AtomicBool};
use std::sync::{RwLock, Arc, Weak, Mutex};
use std::mem;
use std::collections::{BTreeSet, LinkedList};
use std::hash::{Hasher, Hash};

extern crate fnv;
use fnv::FnvHashMap;

#[macro_use]
extern crate lazy_static;

#[cfg(test)]
mod tests;

// ////// //
// PUBLIC //
// ////// //

// traits

/// Trait for event types.
// in theory there'd be a way to allow an Event to have non-'static &refs
// idk how to do it tho
// (perhaps defer the data with an associated type? altho we don't have GATs yet...)
pub trait Event where Self: 'static {
    // type properties

    /// Returns the metadata for this event type.
    fn event_metadata() -> &'static EventMetadata<Self>;

    /// Returns whether this event is cancellable.
    ///
    /// When this is true, `cancelled` and `cancel` should also be implemented.
    fn cancellable() -> bool { false }

    // instance properties

    /// Returns whether this event has been cancelled.
    fn cancelled(&self) -> bool { false }

    /// Sets whether this event is cancelled.
    ///
    /// # Panics
    ///
    /// Panics if this event is not cancellable.
    fn cancel(&mut self, bool) { panic!() }
}

// structs

/// An event handler ID.
///
/// Used to unregister the event handler.
pub struct EventHandlerId<T: Event + ?Sized> {
    priority: i32,
    f: fn(&mut T),
    valid_for: Weak<EventBusDetails>,
    cleared: Arc<AtomicBool>,
}

/// Metadata for an event type.
pub struct EventMetadata<T: Event + ?Sized> {
    // we use a HashMap here rather than a BTreeMap because you're likely to have a low number of
    // event handlers. (usually 0 or 1, even)
    handlers: RwLock<FnvHashMap<Arc<EventBusDetails>, EventHandlers<T>>>,
}

/// An event bus, where events are posted.
///
/// # Examples
///
/// Given an event `StartEvent`:
///
/// ```rust
/// # extern crate eventbus;
/// # use eventbus::{Event, EventMetadata, EventBus};
/// # #[macro_use]
/// # extern crate lazy_static;
/// # struct StartEvent;
/// # impl Event for StartEvent {
/// #     fn event_metadata() -> &'static EventMetadata<Self> {
/// #         lazy_static! {
/// #             static ref METADATA: EventMetadata<StartEvent> = EventMetadata::new();
/// #         }
/// #         &*METADATA
/// #     }
/// # }
/// # fn main() {
/// fn on_start(_event: &mut StartEvent) {
///     println!("Started!");
/// }
/// let eventbus = EventBus::new();
/// eventbus.register(on_start, 0);
/// eventbus.post(&mut StartEvent);
/// # }
/// ```
// #[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct EventBus {
    // needed for this thing to actually work
    inner: Arc<EventBusDetails>,
    // we don't have weak keys, so we use this instead.
    // note that we don't store the inner in each dropper because that'd be inefficient.
    // TODO replace LinkedList with something else (a linked list of arrays would be a good
    // candidate), so as to reduce memory overhead.
    dropper: Mutex<LinkedList<Box<Fn(&Arc<EventBusDetails>)>>>,
    cleared: RwLock<Arc<AtomicBool>>,
}

// /////// //
// PRIVATE //
// /////// //

// traits

// structs

// fucking HRTBs
// #[derive(Eq, PartialEq, Ord, PartialOrd, Hash)]
struct EventHandler<T: Event + ?Sized> {
    // this NEEDS to be in this order: priority, fn
    // (well, it would need to, if derive worked.)
    priority: i32,
    f: fn(&mut T),
}

#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
struct EventBusDetails {
    id: usize,
}

struct EventHandlers<T: Event + ?Sized> {
    handlers: RwLock<BTreeSet<EventHandler<T>>>,
}

// ///////////////// //
// STATICS (private) //
// ///////////////// //

static BUS_ID: AtomicUsize = ATOMIC_USIZE_INIT;

lazy_static! {
    // this is the closest to high-performance we can get with std
    // would be nicer if this was lock-free
    static ref FREED_BUS_IDS: Mutex<LinkedList<usize>> = Mutex::new(LinkedList::new());
}

// ///////////// //
// FNs (private) //
// ///////////// //

// since Weaks are completely useless...
// this checks if the arc and weak point to the same value without attempting to upgrade the weak.
// btw rust community is great. you ask them to help with this stuff and all they do is say you're
// doing it wrong. and refuse to help you with anything. you're on your own for everything.
fn compare_arc_weak<T>(arc: &Arc<T>, weak: &Weak<T>) -> bool {
    unsafe {
        // we assume arc and weak have same size and alignment as usize
        let arcusize: usize = mem::transmute_copy(arc);
        let weakusize: usize = mem::transmute_copy(weak);
        arcusize == weakusize
    }
}

// ///// //
// IMPLS //
// ///// //

// fucking HRTBs
// I've no idea if these are correct tbh.
impl<T: Event + ?Sized> Eq for EventHandler<T> {}
impl<T: Event + ?Sized> Ord for EventHandler<T> {
    fn cmp(&self, other: &EventHandler<T>) -> std::cmp::Ordering {
        self.priority.cmp(&other.priority).then_with(|| (self.f as usize).cmp(&(other.f as usize)))
    }
}
impl<T: Event + ?Sized> PartialEq for EventHandler<T> {
    fn eq(&self, other: &EventHandler<T>) -> bool {
        self.priority == other.priority && (self.f as usize == other.f as usize)
    }
}
impl<T: Event + ?Sized> PartialOrd for EventHandler<T> {
    fn partial_cmp(&self, other: &EventHandler<T>) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl<T: Event + ?Sized> Hash for EventHandler<T> {
    fn hash<H>(&self, state: &mut H) where H: Hasher {
        self.priority.hash(state);
        (self.f as usize).hash(state);
    }
}

impl<T: Event + ?Sized> EventHandlers<T> {
    fn new() -> EventHandlers<T> {
        EventHandlers {
            handlers: RwLock::new(BTreeSet::new()),
        }
    }
}

impl<T: Event + ?Sized> EventMetadata<T> {
    /// Creates an EventMetadata.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # extern crate eventbus;
    /// # use eventbus::{Event, EventMetadata};
    /// #[macro_use]
    /// extern crate lazy_static;
    ///
    /// struct StartEvent;
    ///
    /// impl Event for StartEvent {
    ///     fn event_metadata() -> &'static EventMetadata<Self> {
    ///         lazy_static! {
    ///             static ref METADATA: EventMetadata<StartEvent> = EventMetadata::new();
    ///         }
    ///         &*METADATA
    ///     }
    /// }
    ///
    /// # fn main() {
    /// # }
    /// ```
    pub fn new() -> EventMetadata<T> {
        EventMetadata { handlers: RwLock::new(FnvHashMap::default()) }
    }

    fn put(&'static self, bus: &EventBus, f: fn(&mut T), priority: i32) -> EventHandlerId<T> {
        // lock cleared in read-mode. we want to do it this early to avoid race conditions
        // with bus.clear();
        let cleared = bus.cleared.read().unwrap();
        // check if we're already in the map
        let rlock = self.handlers.read().unwrap();
        let have_handlers = rlock.get(&bus.inner).is_some();
        // explicitly unlock
        mem::drop(rlock);
        // if we're not in the map, we need to get in the map
        if !have_handlers {
            // we might have been added to the map, so check again, this time with entry
            let mut wlock = self.handlers.write().unwrap();
            wlock.entry(bus.inner.clone()).or_insert_with(|| {
                // add dropper function
                bus.dropper.lock().unwrap().push_back(Box::new(move |the_inner| {
                    self.handlers.write().unwrap().remove(the_inner);
                }));
                EventHandlers::new()
            });
        }
        // now we're in the map (or else we have a bug)
        // (this is fine because we locked cleared.)
        // just add the handler
        let rlock = self.handlers.read().unwrap();
        let handlers = rlock.get(&bus.inner).unwrap();
        if !handlers.handlers.write().unwrap().insert(EventHandler { priority, f, }) {
            // note that it is possible to insert the same handler with different priorities.
            // this is probably good enough tho.
            panic!("Tried to insert the same event handler twice");
        }
        EventHandlerId {
            priority, f, valid_for: Arc::downgrade(&bus.inner), cleared: cleared.clone(),
        }
    }

    fn remove(&'static self, bus: &EventBus, f: EventHandlerId<T>) {
        // lock cleared in read-mode
        let cleared = bus.cleared.read().unwrap();

        if !compare_arc_weak(&bus.inner, &f.valid_for) {
            // already removed?
            if !f.cleared.load(Ordering::SeqCst) { // this could be Relaxed
                // TODO we might want to return the EventHandlerId again instead.
                panic!("Attempt to unregister event handler from the wrong bus");
            }
            return;
        }

        let rlock = self.handlers.read().unwrap();
        if let Some(handlers) = rlock.get(&bus.inner) {
            handlers.handlers.write().unwrap().remove(&EventHandler { priority: f.priority, f: f.f });
        } else {
            // hmm. how did you get an EventHandlerId for an EventHandler that doesn't exist?
            panic!("if you're seeing this let me know. ebb7d092-bf57-410c-a317-c05ead9347e0");
        }

        // unlock cleared
        mem::drop(cleared);
    }

    fn post(&'static self, bus: &EventBus, event: &mut T) -> bool {
        // lock cleared in read-mode.
        let cleared = bus.cleared.read().unwrap();
        // TODO document somewhere that adding/removing handlers has no effect until the next call
        // to bus.post()!
        // this should be in sorted order. TODO test.
        // let rlock = self.handlers.read().unwrap();
        let handlers: Vec<_> = self.handlers.read().unwrap().get(&bus.inner).map(|handlers| handlers.handlers.read().unwrap().iter().map(|x| x.f).collect()).unwrap_or(Vec::new());
        // unlock cleared so handlers can be added/removed.
        mem::drop(cleared);
        // TODO we might want to walk these backwards. there's a reason this is 0.2.0 and not
        // 1.0.0.
        handlers.iter().any(|f| {
            f(event);
            T::cancellable() && event.cancelled()
        })
    }
}

impl EventBus {
    /// Creates a new EventBus.
    pub fn new() -> EventBus {
        // use SeqCst because we need these to be unique
        EventBus {
            inner: Arc::new(EventBusDetails {
                id: FREED_BUS_IDS.lock().unwrap().pop_front().unwrap_or_else(|| BUS_ID.fetch_add(1, Ordering::SeqCst)),
            }),
            cleared: RwLock::new(Arc::new(AtomicBool::new(false))),
            dropper: Mutex::new(LinkedList::new()),
        }
    }

    /// Registers an event handler with this event bus.
    ///
    /// Returns a handle that can later be used to unregister the handler.
    /// 
    /// # Panics
    ///
    /// Panics if the same handler is registered twice.
    pub fn register<T: Event>(&self, f: fn(&mut T), priority: i32) -> EventHandlerId<T> {
        let meta = T::event_metadata();
        meta.put(self, f, priority)
    }

    /// Unregisters an event handler on this event bus.
    ///
    /// # Panics
    ///
    /// Panics if the handler is from another event bus.
    pub fn unregister<T: Event>(&self, f: EventHandlerId<T>) {
        let meta = T::event_metadata();
        meta.remove(self, f)
    }

    /// Posts an event on this event bus.
    pub fn post<T: Event>(&self, event: &mut T) -> bool {
        let meta = T::event_metadata();
        meta.post(self, event)
    }

    /// Clears all event handlers registered on this bus.
    pub fn clear(&self) {
        let mut wlock = self.cleared.write().unwrap();
        let dropper: LinkedList<Box<Fn(&Arc<EventBusDetails>)>> = mem::replace(&mut *self.dropper.lock().unwrap(), LinkedList::new());
        for f in dropper {
            f(&self.inner);
        }
        wlock.store(false, Ordering::SeqCst); // this could be Relaxed
        *wlock = Arc::new(AtomicBool::new(false));
    }
}

impl Drop for EventBus {
    fn drop(&mut self) {
        // we are the only reference, so we don't need to worry about race conditions
        // remove Arcs from maps here
        self.clear();
        // sanity check: after removing all Arcs, we should be left with only 1
        // also, since drop takes &mut self, there can't be outstanding references to this
        // EventBus.
        assert_eq!(Arc::strong_count(&self.inner), 1);
        FREED_BUS_IDS.lock().unwrap().push_back(self.inner.id);
    }
}