Skip to main content

dispatch_core/
lib.rs

1#![no_std]
2#![forbid(unsafe_code)]
3#![doc = include_str!("../README.md")]
4
5/// A dispatcher that owns the components used to select and wrap a handler.
6///
7/// The dispatch table is supplied for each call, so the dispatcher itself does
8/// not own application data or state. This makes it suitable as a small core
9/// for higher-level abstractions such as a state machine.
10pub struct Dispatcher<M, W> {
11    matcher: M,
12    middleware: W,
13}
14
15impl<M, W> Dispatcher<M, W> {
16    /// Creates a dispatcher from a matcher and middleware.
17    pub const fn new(matcher: M, middleware: W) -> Self {
18        Self {
19            matcher,
20            middleware,
21        }
22    }
23
24    /// Dispatches an input to the first matching item in `table`.
25    pub fn dispatch<Item, Input, Output, Error>(
26        &mut self,
27        table: &[Item],
28        input: &Input,
29    ) -> Result<Output, DispatchError<Error>>
30    where
31        M: Matcher<Item, Input>,
32        W: Middleware<Item, Input, Output, Error>,
33        Item: Handler<Input = Input, Output = Output, Error = Error>,
34    {
35        dispatch(self, table, input)
36    }
37
38    /// Returns a shared reference to the matcher.
39    pub const fn matcher(&self) -> &M {
40        &self.matcher
41    }
42
43    /// Returns a mutable reference to the matcher.
44    pub fn matcher_mut(&mut self) -> &mut M {
45        &mut self.matcher
46    }
47
48    /// Returns a shared reference to the middleware.
49    pub const fn middleware(&self) -> &W {
50        &self.middleware
51    }
52
53    /// Returns a mutable reference to the middleware.
54    pub fn middleware_mut(&mut self) -> &mut W {
55        &mut self.middleware
56    }
57
58    /// Splits the dispatcher into its matcher and middleware.
59    pub fn into_parts(self) -> (M, W) {
60        (self.matcher, self.middleware)
61    }
62}
63
64/// An error raised while dispatching an input.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum DispatchError<E> {
67    /// No item in the table matched the input.
68    NotFound,
69
70    /// Middleware rejected the input before the handler ran.
71    Before(E),
72
73    /// The selected handler failed.
74    Execute(E),
75
76    /// Middleware failed while processing the handler output.
77    After(E),
78}
79
80/// Selects table items for an input.
81pub trait Matcher<Item, Input> {
82    /// Returns `true` when `item` can handle `input`.
83    fn matches(&self, item: &Item, input: &Input) -> bool;
84}
85
86/// Handles a dispatched input.
87pub trait Handler {
88    /// Input accepted by the handler.
89    type Input;
90
91    /// Value produced by the handler.
92    type Output;
93
94    /// Error produced by the handler.
95    type Error;
96
97    /// Handles `input` and returns an output.
98    fn handle(&self, input: &Self::Input) -> Result<Self::Output, Self::Error>;
99}
100
101/// Runs logic immediately before and after the selected handler.
102///
103/// The input is immutable because item selection has already happened. This
104/// prevents middleware from invalidating the match. The output remains mutable
105/// so middleware can decorate or normalize successful results.
106pub trait Middleware<Item, Input, Output, Error> {
107    /// Runs after an item is selected and before its handler is called.
108    fn before(&mut self, item: &Item, input: &Input) -> Result<(), Error>;
109
110    /// Runs after the handler succeeds.
111    ///
112    /// This hook is skipped when [`Self::before`] or [`Handler::handle`] fails.
113    fn after(&mut self, item: &Item, input: &Input, output: &mut Output) -> Result<(), Error>;
114}
115
116/// Middleware that performs no work.
117#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
118pub struct NoopMiddleware;
119
120impl<Item, Input, Output, Error> Middleware<Item, Input, Output, Error> for NoopMiddleware {
121    fn before(&mut self, _item: &Item, _input: &Input) -> Result<(), Error> {
122        Ok(())
123    }
124
125    fn after(&mut self, _item: &Item, _input: &Input, _output: &mut Output) -> Result<(), Error> {
126        Ok(())
127    }
128}
129
130/// Dispatches `input` to the first matching item in `table`.
131///
132/// Execution order is:
133///
134/// 1. select the first item accepted by the matcher;
135/// 2. call [`Middleware::before`];
136/// 3. call [`Handler::handle`];
137/// 4. call [`Middleware::after`].
138///
139/// Processing stops at the first error. In particular, `after` only runs when
140/// both `before` and the handler succeed.
141pub fn dispatch<M, W, Item, Input, Output, Error>(
142    dispatcher: &mut Dispatcher<M, W>,
143    table: &[Item],
144    input: &Input,
145) -> Result<Output, DispatchError<Error>>
146where
147    M: Matcher<Item, Input>,
148    W: Middleware<Item, Input, Output, Error>,
149    Item: Handler<Input = Input, Output = Output, Error = Error>,
150{
151    let item = table
152        .iter()
153        .find(|item| dispatcher.matcher.matches(item, input))
154        .ok_or(DispatchError::NotFound)?;
155
156    dispatcher
157        .middleware
158        .before(item, input)
159        .map_err(DispatchError::Before)?;
160
161    let mut output = item.handle(input).map_err(DispatchError::Execute)?;
162
163    dispatcher
164        .middleware
165        .after(item, input, &mut output)
166        .map_err(DispatchError::After)?;
167
168    Ok(output)
169}
170
171#[cfg(test)]
172mod tests {
173    use core::cell::Cell;
174
175    use super::*;
176
177    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
178    enum TestError {
179        Before,
180        Execute,
181        After,
182    }
183
184    struct Rule {
185        key: u8,
186        value: u8,
187        fails: bool,
188        calls: Cell<u8>,
189    }
190
191    impl Handler for Rule {
192        type Input = u8;
193        type Output = u8;
194        type Error = TestError;
195
196        fn handle(&self, _input: &Self::Input) -> Result<Self::Output, Self::Error> {
197            self.calls.set(self.calls.get() + 1);
198            if self.fails {
199                Err(TestError::Execute)
200            } else {
201                Ok(self.value)
202            }
203        }
204    }
205
206    struct KeyMatcher;
207
208    impl Matcher<Rule, u8> for KeyMatcher {
209        fn matches(&self, item: &Rule, input: &u8) -> bool {
210            item.key == *input
211        }
212    }
213
214    #[derive(Default)]
215    struct TestMiddleware {
216        fail_before: bool,
217        fail_after: bool,
218        before_calls: u8,
219        after_calls: u8,
220    }
221
222    impl Middleware<Rule, u8, u8, TestError> for TestMiddleware {
223        fn before(&mut self, _item: &Rule, _input: &u8) -> Result<(), TestError> {
224            self.before_calls += 1;
225            if self.fail_before {
226                Err(TestError::Before)
227            } else {
228                Ok(())
229            }
230        }
231
232        fn after(&mut self, _item: &Rule, _input: &u8, output: &mut u8) -> Result<(), TestError> {
233            self.after_calls += 1;
234            if self.fail_after {
235                Err(TestError::After)
236            } else {
237                *output *= 2;
238                Ok(())
239            }
240        }
241    }
242
243    fn rule(key: u8, value: u8) -> Rule {
244        Rule {
245            key,
246            value,
247            fails: false,
248            calls: Cell::new(0),
249        }
250    }
251
252    #[test]
253    fn dispatches_to_the_first_matching_item() {
254        let table = [rule(1, 10), rule(1, 20)];
255        let mut dispatcher = Dispatcher::new(KeyMatcher, TestMiddleware::default());
256
257        let output = dispatcher.dispatch(&table, &1).unwrap();
258
259        assert_eq!(output, 20);
260        assert_eq!(table[0].calls.get(), 1);
261        assert_eq!(table[1].calls.get(), 0);
262        assert_eq!(dispatcher.middleware().before_calls, 1);
263        assert_eq!(dispatcher.middleware().after_calls, 1);
264    }
265
266    #[test]
267    fn returns_not_found_without_running_middleware() {
268        let table = [rule(1, 10)];
269        let mut dispatcher = Dispatcher::new(KeyMatcher, TestMiddleware::default());
270
271        let result = dispatcher.dispatch(&table, &2);
272
273        assert_eq!(result, Err(DispatchError::NotFound));
274        assert_eq!(dispatcher.middleware().before_calls, 0);
275        assert_eq!(dispatcher.middleware().after_calls, 0);
276    }
277
278    #[test]
279    fn stops_when_before_fails() {
280        let table = [rule(1, 10)];
281        let middleware = TestMiddleware {
282            fail_before: true,
283            ..TestMiddleware::default()
284        };
285        let mut dispatcher = Dispatcher::new(KeyMatcher, middleware);
286
287        let result = dispatcher.dispatch(&table, &1);
288
289        assert_eq!(result, Err(DispatchError::Before(TestError::Before)));
290        assert_eq!(table[0].calls.get(), 0);
291        assert_eq!(dispatcher.middleware().after_calls, 0);
292    }
293
294    #[test]
295    fn skips_after_when_handler_fails() {
296        let mut failing_rule = rule(1, 10);
297        failing_rule.fails = true;
298        let table = [failing_rule];
299        let mut dispatcher = Dispatcher::new(KeyMatcher, TestMiddleware::default());
300
301        let result = dispatcher.dispatch(&table, &1);
302
303        assert_eq!(result, Err(DispatchError::Execute(TestError::Execute)));
304        assert_eq!(table[0].calls.get(), 1);
305        assert_eq!(dispatcher.middleware().after_calls, 0);
306    }
307
308    #[test]
309    fn reports_after_errors() {
310        let table = [rule(1, 10)];
311        let middleware = TestMiddleware {
312            fail_after: true,
313            ..TestMiddleware::default()
314        };
315        let mut dispatcher = Dispatcher::new(KeyMatcher, middleware);
316
317        let result = dispatcher.dispatch(&table, &1);
318
319        assert_eq!(result, Err(DispatchError::After(TestError::After)));
320        assert_eq!(table[0].calls.get(), 1);
321    }
322
323    #[test]
324    fn noop_middleware_requires_no_configuration() {
325        let table = [rule(1, 10)];
326        let mut dispatcher = Dispatcher::new(KeyMatcher, NoopMiddleware);
327
328        let output = dispatcher.dispatch(&table, &1).unwrap();
329
330        assert_eq!(output, 10);
331    }
332}