Skip to main content

dispatch_core/
lib.rs

1#![no_std]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4#![doc = include_str!("../README.md")]
5
6use core::{error::Error, fmt};
7
8/// A dispatcher backed by a borrowed table and a matching strategy.
9///
10/// The table is scanned from beginning to end. The first matching item is
11/// selected, so table order defines dispatch priority.
12pub struct Dispatcher<'a, Item, M> {
13    table: &'a [Item],
14    matcher: M,
15}
16
17impl<'a, Item, M> Dispatcher<'a, Item, M> {
18    /// Creates a dispatcher backed by `table`.
19    pub const fn new(table: &'a [Item], matcher: M) -> Self {
20        Self { table, matcher }
21    }
22
23    /// Returns the first item accepted by the matcher.
24    ///
25    /// This method performs selection only and does not invoke the item's
26    /// [`Handler`].
27    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    /// Selects and executes the first item accepted by the matcher.
38    ///
39    /// `input` is immutable for the entire operation. Runtime state and other
40    /// mutable resources should be carried by `context` instead.
41    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    /// Returns the dispatch table.
56    pub const fn table(&self) -> &'a [Item] {
57        self.table
58    }
59
60    /// Returns a shared reference to the matcher.
61    pub const fn matcher(&self) -> &M {
62        &self.matcher
63    }
64
65    /// Returns a mutable reference to the matcher.
66    ///
67    /// This can be used to reconfigure matching between dispatch calls. The
68    /// matcher itself remains immutable while selection is in progress.
69    pub fn matcher_mut(&mut self) -> &mut M {
70        &mut self.matcher
71    }
72
73    /// Splits the dispatcher into its table and matcher.
74    pub fn into_parts(self) -> (&'a [Item], M) {
75        (self.table, self.matcher)
76    }
77}
78
79/// An error raised while dispatching an input.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum DispatchError<E> {
82    /// No item in the table matched the input.
83    NotFound,
84
85    /// The selected item failed during execution.
86    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
113/// Determines whether an item accepts an input.
114///
115/// Matching receives immutable references and should not produce application
116/// side effects. Stateful matching can still be configured between calls via
117/// [`Dispatcher::matcher_mut`].
118pub trait Matcher<Item, Input: ?Sized> {
119    /// Returns `true` when `item` can handle `input`.
120    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
133/// Executes a selected dispatch-table item.
134///
135/// The input is immutable. Mutable runtime state, services, buffers, or device
136/// handles should be placed in [`Self::Context`]. Implementations that do not
137/// need a context can use `()`.
138pub trait Handler {
139    /// Input accepted by the handler.
140    type Input: ?Sized;
141
142    /// Mutable runtime context used by the handler.
143    type Context: ?Sized;
144
145    /// Value produced by the handler.
146    type Output;
147
148    /// Error produced by the handler.
149    type Error;
150
151    /// Handles `input` using `context` and returns an output.
152    fn handle(
153        &self,
154        input: &Self::Input,
155        context: &mut Self::Context,
156    ) -> Result<Self::Output, Self::Error>;
157}