Skip to main content

dispatch_core/
command.rs

1use crate::{
2    After, AfterFn, AfterHandler, Before, BeforeFn, DispatchError, DispatchStage, Handler,
3    IdentityResponse, NoAfter, NoBefore, ResponseFn, ResponseHandler, ResponseStage, StageError,
4};
5
6/// Erased function pointer stored by a [`CommandEntry`].
7pub type CommandHandler<C, R, O, E> = fn(&mut C, &mut R) -> Result<O, StageError<E>>;
8
9/// One command in a static dispatch table.
10///
11/// The entry stores only its key and an erased function pointer. It owns no
12/// context or resources and requires no heap allocation.
13pub struct CommandEntry<K, C, R, O, E> {
14    key: K,
15    handler: CommandHandler<C, R, O, E>,
16}
17
18impl<K, C, R, O, E> CommandEntry<K, C, R, O, E> {
19    /// Creates an entry from a key and already-erased handler function.
20    ///
21    /// Applications normally use [`crate::command!`] to generate `handler`.
22    pub const fn new(key: K, handler: CommandHandler<C, R, O, E>) -> Self {
23        Self { key, handler }
24    }
25
26    /// Returns the command key.
27    pub const fn key(&self) -> &K {
28        &self.key
29    }
30
31    /// Invokes the command without performing matching.
32    pub fn invoke(&self, context: &mut C, resources: &mut R) -> Result<O, StageError<E>> {
33        (self.handler)(context, resources)
34    }
35}
36
37/// Determines whether a command key accepts the current context.
38///
39/// Matching receives only shared references and should not produce application
40/// side effects. The selected command receives mutable context and resources
41/// only after matching has finished.
42pub trait Matcher<K, C: ?Sized> {
43    /// Returns `true` when `key` identifies the command for `context`.
44    fn matches(&self, key: &K, context: &C) -> bool;
45}
46
47impl<K, C, F> Matcher<K, C> for F
48where
49    C: ?Sized,
50    F: Fn(&K, &C) -> bool,
51{
52    fn matches(&self, key: &K, context: &C) -> bool {
53        self(key, context)
54    }
55}
56
57/// Exposes the command key stored in an application context.
58///
59/// Implementing this trait enables the convenience [`dispatch`] function and
60/// [`KeyMatcher`]. Custom [`Matcher`] implementations need not use it.
61pub trait CommandKey<K> {
62    /// Returns the key of the command that should handle this context.
63    fn command_key(&self) -> &K;
64}
65
66/// Matches an entry key against [`CommandKey::command_key`].
67#[derive(Debug, Clone, Copy, Default)]
68pub struct KeyMatcher;
69
70impl<K, C> Matcher<K, C> for KeyMatcher
71where
72    K: PartialEq,
73    C: CommandKey<K>,
74{
75    fn matches(&self, key: &K, context: &C) -> bool {
76        key == context.command_key()
77    }
78}
79
80/// A borrowed command table paired with a matching strategy.
81///
82/// Table order defines priority: the first matching entry is executed.
83pub struct Dispatcher<'table, K, C, R, O, E, M, B = NoBefore, A = NoAfter, S = IdentityResponse> {
84    table: &'table [CommandEntry<K, C, R, O, E>],
85    matcher: M,
86    before: B,
87    after: A,
88    response: S,
89}
90
91/// Dispatcher type returned by [`Dispatcher::with_response`].
92pub type ResponseDispatcher<'table, K, C, R, O, E, M, B, A, F, Params, T> =
93    Dispatcher<'table, K, C, R, O, E, M, B, A, ResponseFn<F, Params, T>>;
94
95impl<'table, K, C, R, O, E, M>
96    Dispatcher<'table, K, C, R, O, E, M, NoBefore, NoAfter, IdentityResponse>
97{
98    /// Creates a dispatcher over `table`.
99    pub const fn new(table: &'table [CommandEntry<K, C, R, O, E>], matcher: M) -> Self {
100        Self {
101            table,
102            matcher,
103            before: NoBefore,
104            after: NoAfter,
105            response: IdentityResponse,
106        }
107    }
108}
109
110impl<'table, K, C, R, O, E, M, B, A, S> Dispatcher<'table, K, C, R, O, E, M, B, A, S> {
111    /// Installs a resource-injected before function.
112    ///
113    /// This does not install an after function. Calling `with_before` again
114    /// replaces only the previous before stage.
115    pub fn with_before<F, Params>(
116        self,
117        function: F,
118    ) -> Dispatcher<'table, K, C, R, O, E, M, BeforeFn<F, Params>, A, S>
119    where
120        F: Handler<C, R, (), E, Params>,
121    {
122        Dispatcher {
123            table: self.table,
124            matcher: self.matcher,
125            before: BeforeFn::new(function),
126            after: self.after,
127            response: self.response,
128        }
129    }
130
131    /// Installs a resource-injected after function.
132    ///
133    /// The function receives mutable access to a successful command output.
134    /// This does not install a before function.
135    pub fn with_after<F, Params>(
136        self,
137        function: F,
138    ) -> Dispatcher<'table, K, C, R, O, E, M, B, AfterFn<F, Params>, S>
139    where
140        F: AfterHandler<C, R, O, E, Params>,
141    {
142        Dispatcher {
143            table: self.table,
144            matcher: self.matcher,
145            before: self.before,
146            after: AfterFn::new(function),
147            response: self.response,
148        }
149    }
150
151    /// Installs a resource-injected successful-response function.
152    ///
153    /// The function consumes the command output after the after stage and may
154    /// convert it to a different final type.
155    pub fn with_response<F, Params, T>(
156        self,
157        function: F,
158    ) -> ResponseDispatcher<'table, K, C, R, O, E, M, B, A, F, Params, T>
159    where
160        F: ResponseHandler<C, R, O, T, E, Params>,
161    {
162        Dispatcher {
163            table: self.table,
164            matcher: self.matcher,
165            before: self.before,
166            after: self.after,
167            response: ResponseFn::new(function),
168        }
169    }
170
171    /// Returns the first command accepted by the matcher.
172    pub fn select(&self, context: &C) -> Option<&'table CommandEntry<K, C, R, O, E>>
173    where
174        M: Matcher<K, C>,
175    {
176        self.table
177            .iter()
178            .find(|command| self.matcher.matches(command.key(), context))
179    }
180
181    /// Selects a command and runs the configured execution pipeline.
182    ///
183    /// Execution stops at the first failure. The after stage runs only after a
184    /// successful command, and response handling runs only after a successful
185    /// after stage.
186    pub fn dispatch(
187        &self,
188        context: &mut C,
189        resources: &mut R,
190    ) -> Result<S::Output, DispatchError<E>>
191    where
192        M: Matcher<K, C>,
193        B: Before<C, R, E>,
194        A: After<C, R, O, E>,
195        S: ResponseStage<C, R, O, E>,
196    {
197        let command = self.select(context).ok_or(DispatchError::NotFound)?;
198
199        self.before
200            .run_before(context, resources)
201            .map_err(|error| DispatchError::at(DispatchStage::Before, error))?;
202
203        let mut output = command
204            .invoke(context, resources)
205            .map_err(|error| DispatchError::at(DispatchStage::Command, error))?;
206
207        self.after
208            .run_after(context, &mut output, resources)
209            .map_err(|error| DispatchError::at(DispatchStage::After, error))?;
210
211        self.response
212            .run_response(context, output, resources)
213            .map_err(|error| DispatchError::at(DispatchStage::Response, error))
214    }
215
216    /// Returns the borrowed command table.
217    pub const fn table(&self) -> &'table [CommandEntry<K, C, R, O, E>] {
218        self.table
219    }
220
221    /// Returns the matcher.
222    pub const fn matcher(&self) -> &M {
223        &self.matcher
224    }
225
226    /// Returns a mutable matcher reference for between-dispatch configuration.
227    pub fn matcher_mut(&mut self) -> &mut M {
228        &mut self.matcher
229    }
230
231    /// Returns the configured before stage.
232    pub const fn before(&self) -> &B {
233        &self.before
234    }
235
236    /// Returns a mutable reference to the configured before stage.
237    pub fn before_mut(&mut self) -> &mut B {
238        &mut self.before
239    }
240
241    /// Returns the configured after stage.
242    pub const fn after(&self) -> &A {
243        &self.after
244    }
245
246    /// Returns a mutable reference to the configured after stage.
247    pub fn after_mut(&mut self) -> &mut A {
248        &mut self.after
249    }
250
251    /// Returns the configured response stage.
252    pub const fn response(&self) -> &S {
253        &self.response
254    }
255
256    /// Returns a mutable reference to the configured response stage.
257    pub fn response_mut(&mut self) -> &mut S {
258        &mut self.response
259    }
260}
261
262/// Dispatches through a table using the key exposed by the context.
263///
264/// This is the smallest API for the common exact-key case. Construct a
265/// [`Dispatcher`] when matching requires a custom strategy.
266pub fn dispatch<K, C, R, O, E>(
267    table: &[CommandEntry<K, C, R, O, E>],
268    context: &mut C,
269    resources: &mut R,
270) -> Result<O, DispatchError<E>>
271where
272    K: PartialEq,
273    C: CommandKey<K>,
274{
275    Dispatcher::new(table, KeyMatcher).dispatch(context, resources)
276}