1#![no_std]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4#![doc = include_str!("../README.md")]
5
6use core::{error::Error, fmt};
7
8pub struct Dispatcher<'a, Item, M> {
13 table: &'a [Item],
14 matcher: M,
15}
16
17impl<'a, Item, M> Dispatcher<'a, Item, M> {
18 pub const fn new(table: &'a [Item], matcher: M) -> Self {
20 Self { table, matcher }
21 }
22
23 pub fn select<Input>(&self, input: &Input) -> Option<&Item>
28 where
29 Input: ?Sized,
30 M: Matcher<Item, Input>,
31 {
32 self.table
33 .iter()
34 .find(|item| self.matcher.matches(item, input))
35 }
36
37 pub fn dispatch(
42 &self,
43 input: &Item::Input,
44 context: &mut Item::Context,
45 ) -> Result<Item::Output, DispatchError<Item::Error>>
46 where
47 Item: Handler,
48 M: Matcher<Item, Item::Input>,
49 {
50 let item = self.select(input).ok_or(DispatchError::NotFound)?;
51
52 item.handle(input, context).map_err(DispatchError::Execute)
53 }
54
55 pub const fn table(&self) -> &'a [Item] {
57 self.table
58 }
59
60 pub const fn matcher(&self) -> &M {
62 &self.matcher
63 }
64
65 pub fn matcher_mut(&mut self) -> &mut M {
70 &mut self.matcher
71 }
72
73 pub fn into_parts(self) -> (&'a [Item], M) {
75 (self.table, self.matcher)
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum DispatchError<E> {
82 NotFound,
84
85 Execute(E),
87}
88
89impl<E> fmt::Display for DispatchError<E>
90where
91 E: fmt::Display,
92{
93 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94 match self {
95 Self::NotFound => formatter.write_str("no matching dispatch item"),
96 Self::Execute(error) => write!(formatter, "dispatch handler failed: {error}"),
97 }
98 }
99}
100
101impl<E> Error for DispatchError<E>
102where
103 E: Error + 'static,
104{
105 fn source(&self) -> Option<&(dyn Error + 'static)> {
106 match self {
107 Self::NotFound => None,
108 Self::Execute(error) => Some(error),
109 }
110 }
111}
112
113pub trait Matcher<Item, Input: ?Sized> {
119 fn matches(&self, item: &Item, input: &Input) -> bool;
121}
122
123impl<Item, Input, F> Matcher<Item, Input> for F
124where
125 Input: ?Sized,
126 F: Fn(&Item, &Input) -> bool,
127{
128 fn matches(&self, item: &Item, input: &Input) -> bool {
129 self(item, input)
130 }
131}
132
133pub trait Handler {
139 type Input: ?Sized;
141
142 type Context: ?Sized;
144
145 type Output;
147
148 type Error;
150
151 fn handle(
153 &self,
154 input: &Self::Input,
155 context: &mut Self::Context,
156 ) -> Result<Self::Output, Self::Error>;
157}