use std::{error::Error, fmt};
use crate::core::Ctx;
pub type HandlerResult = Result<Vec<u8>, HandlerError>;
pub type HandlerFn = for<'a> fn(&[u8], &mut Ctx<'a>) -> HandlerResult;
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum HandlerError {
InvalidInput(String),
Failed(String),
}
impl HandlerError {
#[must_use]
pub fn invalid_input(message: impl Into<String>) -> Self {
Self::InvalidInput(message.into())
}
#[must_use]
pub fn failed(message: impl Into<String>) -> Self {
Self::Failed(message.into())
}
#[must_use]
pub const fn class(&self) -> &'static str {
match self {
Self::InvalidInput(_) => "invalid_input",
Self::Failed(_) => "failed",
}
}
#[must_use]
pub fn message(&self) -> &str {
match self {
Self::InvalidInput(message) | Self::Failed(message) => message,
}
}
}
impl fmt::Display for HandlerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.class(), self.message())
}
}
impl Error for HandlerError {}
pub trait Handler {
fn handle(&mut self, input: &[u8], cx: &mut Ctx<'_>) -> HandlerResult;
}
impl<F> Handler for F
where
F: for<'a> FnMut(&[u8], &mut Ctx<'a>) -> HandlerResult,
{
fn handle(&mut self, input: &[u8], cx: &mut Ctx<'_>) -> HandlerResult {
self(input, cx)
}
}