#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
use core::{error::Error, fmt};
pub struct Dispatcher<'table, Item, M> {
table: &'table [Item],
matcher: M,
}
impl<'table, Item, M> Dispatcher<'table, Item, M> {
pub const fn new(table: &'table [Item], matcher: M) -> Self {
Self { table, matcher }
}
pub fn select<Input>(&self, input: &Input) -> Option<&'table Item>
where
Input: ?Sized,
M: Matcher<Item, Input>,
{
self.table
.iter()
.find(|item| self.matcher.matches(item, input))
}
pub fn dispatch<'input, Input, Output, ExecuteError, Execute>(
&self,
input: &'input Input,
execute: Execute,
) -> Result<Output, DispatchError<ExecuteError>>
where
Input: ?Sized,
M: Matcher<Item, Input>,
Execute: FnOnce(&'table Item, &'input Input) -> Result<Output, ExecuteError>,
{
let item = self.select(input).ok_or(DispatchError::NotFound)?;
execute(item, input).map_err(DispatchError::Execute)
}
pub const fn table(&self) -> &'table [Item] {
self.table
}
pub const fn matcher(&self) -> &M {
&self.matcher
}
pub fn matcher_mut(&mut self) -> &mut M {
&mut self.matcher
}
pub fn into_parts(self) -> (&'table [Item], M) {
(self.table, self.matcher)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DispatchError<E> {
NotFound,
Execute(E),
}
impl<E> fmt::Display for DispatchError<E>
where
E: fmt::Display,
{
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotFound => formatter.write_str("no matching dispatch item"),
Self::Execute(error) => write!(formatter, "dispatch execution failed: {error}"),
}
}
}
impl<E> Error for DispatchError<E>
where
E: Error + 'static,
{
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::NotFound => None,
Self::Execute(error) => Some(error),
}
}
}
pub trait Matcher<Item, Input: ?Sized> {
fn matches(&self, item: &Item, input: &Input) -> bool;
}
impl<Item, Input, F> Matcher<Item, Input> for F
where
Input: ?Sized,
F: Fn(&Item, &Input) -> bool,
{
fn matches(&self, item: &Item, input: &Input) -> bool {
self(item, input)
}
}