Skip to main content

dispatch_core/
handler.rs

1use crate::{StageError, SystemParam, param::ParamSet};
2
3/// Adapts a typed command function to a uniform resource-aware invocation.
4///
5/// `Params` is a tuple of [`SystemParam`] marker types. Implementations are
6/// provided for functions with zero through eight injected arguments. Most
7/// applications create the adapter through [`crate::command!`].
8pub trait Handler<C, R, O, E, Params> {
9    /// Validates resource access, extracts arguments, and invokes the function.
10    fn run(&self, context: &mut C, resources: &mut R) -> Result<O, StageError<E>>;
11}
12
13impl<C, R, O, E, F> Handler<C, R, O, E, ()> for F
14where
15    F: Fn(&mut C) -> Result<O, E>,
16{
17    fn run(&self, context: &mut C, _resources: &mut R) -> Result<O, StageError<E>> {
18        self(context).map_err(StageError::User)
19    }
20}
21
22macro_rules! impl_handler {
23    ($($param:ident => $value:ident @ $index:expr),+ $(,)?) => {
24        impl<C, R, O, E, F, $($param),+> Handler<C, R, O, E, ($($param,)+)> for F
25        where
26            $($param: SystemParam<R>,)+
27            F: Fn(&mut C, $($param),+) -> Result<O, E>,
28            for<'context, 'resources> F:
29                Fn(&'context mut C, $($param::Item<'resources>),+) -> Result<O, E>,
30        {
31            fn run(
32                &self,
33                context: &mut C,
34                resources: &mut R,
35            ) -> Result<O, StageError<E>> {
36                let ($($value,)+) =
37                    <($($param,)+) as ParamSet<R>>::fetch(resources)
38                        .map_err(StageError::Param)?;
39
40                self(context, $($value),+).map_err(StageError::User)
41            }
42        }
43    };
44}
45
46impl_handler!(P0 => p0 @ 0);
47impl_handler!(P0 => p0 @ 0, P1 => p1 @ 1);
48impl_handler!(P0 => p0 @ 0, P1 => p1 @ 1, P2 => p2 @ 2);
49impl_handler!(P0 => p0 @ 0, P1 => p1 @ 1, P2 => p2 @ 2, P3 => p3 @ 3);
50impl_handler!(
51    P0 => p0 @ 0,
52    P1 => p1 @ 1,
53    P2 => p2 @ 2,
54    P3 => p3 @ 3,
55    P4 => p4 @ 4,
56);
57impl_handler!(
58    P0 => p0 @ 0,
59    P1 => p1 @ 1,
60    P2 => p2 @ 2,
61    P3 => p3 @ 3,
62    P4 => p4 @ 4,
63    P5 => p5 @ 5,
64);
65impl_handler!(
66    P0 => p0 @ 0,
67    P1 => p1 @ 1,
68    P2 => p2 @ 2,
69    P3 => p3 @ 3,
70    P4 => p4 @ 4,
71    P5 => p5 @ 5,
72    P6 => p6 @ 6,
73);
74impl_handler!(
75    P0 => p0 @ 0,
76    P1 => p1 @ 1,
77    P2 => p2 @ 2,
78    P3 => p3 @ 3,
79    P4 => p4 @ 4,
80    P5 => p5 @ 5,
81    P6 => p6 @ 6,
82    P7 => p7 @ 7,
83);