use crate::Sequence;
pub trait EventHandler<E>: Send {
fn on_event(&mut self, event: &E, sequence: Sequence, end_of_batch: bool);
}
#[derive(Debug, Clone, Default)]
pub struct HandlerChain<H1, H2> {
first: H1,
second: H2,
}
impl<H1, H2> HandlerChain<H1, H2> {
#[inline]
pub fn new(first: H1, second: H2) -> Self {
Self { first, second }
}
}
impl<E, H1, H2> EventHandler<E> for HandlerChain<H1, H2>
where
H1: EventHandler<E>,
H2: EventHandler<E>,
{
#[inline]
fn on_event(&mut self, event: &E, sequence: Sequence, end_of_batch: bool) {
self.first.on_event(event, sequence, end_of_batch);
self.second.on_event(event, sequence, end_of_batch);
}
}
pub trait EventHandlerChainExt<E>: EventHandler<E> + Sized {
#[inline]
fn chain<H>(self, other: H) -> HandlerChain<Self, H>
where
H: EventHandler<E>,
{
HandlerChain::new(self, other)
}
}
impl<E, T> EventHandlerChainExt<E> for T where T: EventHandler<E> + Sized {}
impl<E, F> EventHandler<E> for F
where
F: FnMut(&E, Sequence, bool) + Send,
{
#[inline]
fn on_event(&mut self, event: &E, sequence: Sequence, end_of_batch: bool) {
(self)(event, sequence, end_of_batch)
}
}
pub trait EventHandlerWithState<E, S>: Send {
fn on_event(&mut self, state: &mut S, event: &E, sequence: Sequence, end_of_batch: bool);
}
impl<E, S, F> EventHandlerWithState<E, S> for F
where
F: FnMut(&mut S, &E, Sequence, bool) + Send,
{
#[inline]
fn on_event(&mut self, state: &mut S, event: &E, sequence: Sequence, end_of_batch: bool) {
(self)(state, event, sequence, end_of_batch)
}
}