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<'table, Item, M> {
13    table: &'table [Item],
14    matcher: M,
15}
16
17impl<'table, Item, M> Dispatcher<'table, Item, M> {
18    /// Creates a dispatcher backed by `table`.
19    pub const fn new(table: &'table [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. It does not invoke an executor or
26    /// otherwise operate on the selected item.
27    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    /// Selects an item and delegates execution to `execute`.
38    ///
39    /// The executor receives the selected item and the original input. It can
40    /// capture arbitrary per-call state and borrowed resources without making
41    /// them part of the dispatcher's type. The executor is not invoked when no
42    /// item matches.
43    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    /// Returns the dispatch table.
59    pub const fn table(&self) -> &'table [Item] {
60        self.table
61    }
62
63    /// Returns a shared reference to the matcher.
64    pub const fn matcher(&self) -> &M {
65        &self.matcher
66    }
67
68    /// Returns a mutable reference to the matcher.
69    ///
70    /// This can be used to reconfigure matching between dispatch calls. The
71    /// matcher itself remains immutable while selection is in progress.
72    pub fn matcher_mut(&mut self) -> &mut M {
73        &mut self.matcher
74    }
75
76    /// Splits the dispatcher into its table and matcher.
77    pub fn into_parts(self) -> (&'table [Item], M) {
78        (self.table, self.matcher)
79    }
80}
81
82/// An error raised while dispatching an input.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum DispatchError<E> {
85    /// No item in the table matched the input.
86    NotFound,
87
88    /// The caller-provided executor failed.
89    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
116/// Determines whether an item accepts an input.
117///
118/// Matching receives immutable references and should not produce application
119/// side effects. Stateful matching can still be configured between calls via
120/// [`Dispatcher::matcher_mut`].
121pub trait Matcher<Item, Input: ?Sized> {
122    /// Returns `true` when `item` accepts `input`.
123    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}