mirror of https://github.com/Trivernis/vented.git
parent
d5d8875e79
commit
c550acc129
@ -0,0 +1,49 @@
|
|||||||
|
use crate::event::Event;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use serde::Serialize;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
/// A handler for events
|
||||||
|
pub struct EventHandler<T> {
|
||||||
|
event_handlers: HashMap<String, Vec<Box<dyn Fn(&Event<T>)>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventHandler<T>
|
||||||
|
where
|
||||||
|
T: Serialize + DeserializeOwned,
|
||||||
|
{
|
||||||
|
/// Creates a new vented event_handler
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
event_handlers: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a handler for the given event
|
||||||
|
pub fn on<F: 'static>(&mut self, event_name: &str, handler: F)
|
||||||
|
where
|
||||||
|
F: Fn(&Event<T>),
|
||||||
|
{
|
||||||
|
match self.event_handlers.get_mut(event_name) {
|
||||||
|
Some(handlers) => handlers.push(Box::new(handler)),
|
||||||
|
None => {
|
||||||
|
self.event_handlers
|
||||||
|
.insert(event_name.to_string(), vec![Box::new(handler)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles a single event
|
||||||
|
pub fn handle_event(&mut self, event: Event<T>) -> bool {
|
||||||
|
if let Some(handlers) = self.event_handlers.get(&event.name) {
|
||||||
|
handlers.iter().for_each(|handler| handler(&event));
|
||||||
|
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
use crate::event::Event;
|
||||||
|
use crate::event_handler::EventHandler;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_handles_events() {
|
||||||
|
let mut handler = EventHandler::new();
|
||||||
|
let call_count = Arc::new(AtomicUsize::new(0));
|
||||||
|
{
|
||||||
|
let call_count = Arc::clone(&call_count);
|
||||||
|
handler.on("test", move |_event| {
|
||||||
|
call_count.fetch_add(1, Ordering::Relaxed);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let call_count = Arc::clone(&call_count);
|
||||||
|
handler.on("test2", move |_event| {
|
||||||
|
call_count.fetch_add(1, Ordering::Relaxed);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.handle_event(Event::new("test".to_string()));
|
||||||
|
handler.handle_event(Event::new("test".to_string()));
|
||||||
|
handler.handle_event(Event::new("test2".to_string()));
|
||||||
|
|
||||||
|
assert_eq!(call_count.load(Ordering::Relaxed), 3)
|
||||||
|
}
|
@ -1,2 +1,3 @@
|
|||||||
pub mod event;
|
pub mod event;
|
||||||
pub mod result;
|
pub mod event_handler;
|
||||||
|
pub mod result;
|
||||||
|
Loading…
Reference in New Issue