event/lib.rs
1#![allow(dead_code)]
2
3use std::collections::BTreeMap;
4
5/// Enumerator of the Event type. Whatever type E of Event::Args you implement here is the type E that will be used for the EventPublisher.
6pub enum Event<E> {
7 Args(E),
8 Missing,
9}
10
11// To deal with handler functions - F: Rc<Box<Fn(&event<E>)>>
12/// EventPublisher. Works similarly to C#'s event publishing pattern. Event handling functions are subscribed to the publisher.
13/// Whenever the publisher fires an event it calls all subscribed event handler functions.
14/// Use event::EventPublisher::<E>::new() to construct
15pub struct EventPublisher<E> {
16 //handlers: Vec<Rc<Box<Fn(&Event<E>) + 'static>>>,
17 handlers: BTreeMap<usize, fn(&Event<E>)>,
18}
19
20impl<E> EventPublisher<E> {
21
22 /// Event publisher constructor.
23 pub fn new() -> EventPublisher<E> {
24 EventPublisher{
25 handlers: BTreeMap::<usize, fn(&Event<E>)>::new()
26 }
27 }
28 /// Subscribes event handler functions to the EventPublisher.
29 /// INPUT: handler: fn(&Event<E>) handler is a pointer to a function to handle an event of the type E. The function must
30 /// be capable of handling references to the event type set up by the publisher, rather than the raw event itself.
31 /// OUTPUT: void
32 pub fn subscribe_handler(&mut self, handler: fn(&Event<E>)){
33 let p_handler: usize;
34 unsafe{
35 p_handler = *(handler as *const usize);
36 }
37 self.handlers.insert(p_handler, handler);
38 }
39
40 /// Unsubscribes an event handler from the publisher.
41 /// INPUT: handler: fn(&Event<E>) handler is a pointer to a function to handle an event of the type E.
42 /// OUTPUT: bool output is a bool of whether or not the function was found in the list of subscribed event handlers and subsequently removed.
43 pub fn unsubscribe_handler(&mut self, handler: fn(&Event<E>)) -> bool {
44 let p_handler: usize;
45 unsafe{
46 p_handler = *(handler as *const usize);
47 }
48 match self.handlers.remove(&p_handler){
49 Some(_) => true,
50 None => false,
51 }
52 }
53
54 // TODO: Implement this concurrently
55 /// Publishes events, pushing the &Event<E> to all handler functions stored by the event publisher.
56 /// INPUT: event: &Event<E> Reference to the Event<E> being pushed to all handling functions.
57 pub fn publish_event(&self, event: &Event<E>){
58 for (_, handler) in self.handlers.iter(){
59 handler(event);
60 }
61 }
62}