Skip to main content

use_event_handler/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4pub trait EventHandler<E> {
5    type Output;
6    type Error;
7
8    fn handle(&self, event: E) -> Result<Self::Output, Self::Error>;
9}
10
11impl<E, F, Output, Error> EventHandler<E> for F
12where
13    F: Fn(E) -> Result<Output, Error>,
14{
15    type Output = Output;
16    type Error = Error;
17
18    fn handle(&self, event: E) -> Result<Self::Output, Self::Error> {
19        self(event)
20    }
21}
22
23#[cfg(test)]
24mod tests {
25    use super::EventHandler;
26    use core::convert::Infallible;
27
28    #[test]
29    fn closures_handle_events() {
30        let handler = |event: &str| -> Result<usize, Infallible> { Ok(event.len()) };
31
32        assert_eq!(handler.handle("command.started"), Ok(15));
33    }
34}