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<'table, Item, M> {
13 table: &'table [Item],
14 matcher: M,
15}
16
17impl<'table, Item, M> Dispatcher<'table, Item, M> {
18 pub const fn new(table: &'table [Item], matcher: M) -> Self {
20 Self { table, matcher }
21 }
22
23 pub fn select<Input>(&self, input: &Input) -> Option<&'table 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<'input, Input, Output, ExecuteError, Execute>(
44 &self,
45 input: &'input Input,
46 execute: Execute,
47 ) -> Result<Output, DispatchError<ExecuteError>>
48 where
49 Input: ?Sized,
50 M: Matcher<Item, Input>,
51 Execute: FnOnce(&'table Item, &'input Input) -> Result<Output, ExecuteError>,
52 {
53 let item = self.select(input).ok_or(DispatchError::NotFound)?;
54
55 execute(item, input).map_err(DispatchError::Execute)
56 }
57
58 pub const fn table(&self) -> &'table [Item] {
60 self.table
61 }
62
63 pub const fn matcher(&self) -> &M {
65 &self.matcher
66 }
67
68 pub fn matcher_mut(&mut self) -> &mut M {
73 &mut self.matcher
74 }
75
76 pub fn into_parts(self) -> (&'table [Item], M) {
78 (self.table, self.matcher)
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum DispatchError<E> {
85 NotFound,
87
88 Execute(E),
90}
91
92impl<E> fmt::Display for DispatchError<E>
93where
94 E: fmt::Display,
95{
96 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97 match self {
98 Self::NotFound => formatter.write_str("no matching dispatch item"),
99 Self::Execute(error) => write!(formatter, "dispatch execution failed: {error}"),
100 }
101 }
102}
103
104impl<E> Error for DispatchError<E>
105where
106 E: Error + 'static,
107{
108 fn source(&self) -> Option<&(dyn Error + 'static)> {
109 match self {
110 Self::NotFound => None,
111 Self::Execute(error) => Some(error),
112 }
113 }
114}
115
116pub trait Matcher<Item, Input: ?Sized> {
122 fn matches(&self, item: &Item, input: &Input) -> bool;
124}
125
126impl<Item, Input, F> Matcher<Item, Input> for F
127where
128 Input: ?Sized,
129 F: Fn(&Item, &Input) -> bool,
130{
131 fn matches(&self, item: &Item, input: &Input) -> bool {
132 self(item, input)
133 }
134}