use async_trait::async_trait;
use crate::traits::{Event, EventConsumer};
pub struct Adaptor<I: Event, O: Event, C: EventConsumer<O>> {
closure: Box<dyn Fn(I) -> Option<O> + Send + Sync>,
consumer: C,
}
impl<I: Event, O: Event, C: EventConsumer<O>> Adaptor<I, O, C> {
pub fn wrap(closure: impl Fn(I) -> Option<O> + Send + Sync + 'static, consumer: C) -> Self {
Self {
closure: Box::new(closure),
consumer,
}
}
}
#[async_trait]
impl<I: Event, O: Event, C: EventConsumer<O>> EventConsumer<I> for Adaptor<I, O, C> {
type Error = <C as EventConsumer<O>>::Error;
async fn accept(&self, event: I) -> Result<(), Self::Error> {
match (self.closure)(event) {
Some(x) => self.consumer.accept(x).await,
None => Ok(()),
}
}
fn accept_sync(&self, event: I) -> Result<(), Self::Error> {
match (self.closure)(event) {
Some(x) => self.consumer.accept_sync(x),
None => Ok(()),
}
}
}