Skip to main content

dispatch_core/
before.rs

1use core::marker::PhantomData;
2
3use crate::{Handler, StageError};
4
5/// Runs optional logic after command selection and before command execution.
6pub trait Before<C, R, E> {
7    /// Runs the before stage.
8    fn run_before(&self, context: &mut C, resources: &mut R) -> Result<(), StageError<E>>;
9}
10
11/// An omitted before stage.
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13pub struct NoBefore;
14
15impl<C, R, E> Before<C, R, E> for NoBefore {
16    fn run_before(&self, _context: &mut C, _resources: &mut R) -> Result<(), StageError<E>> {
17        Ok(())
18    }
19}
20
21/// Adapts one resource-injected function into a [`Before`] stage.
22pub struct BeforeFn<F, Params> {
23    function: F,
24    marker: PhantomData<fn() -> Params>,
25}
26
27impl<F, Params> BeforeFn<F, Params> {
28    pub(crate) const fn new(function: F) -> Self {
29        Self {
30            function,
31            marker: PhantomData,
32        }
33    }
34
35    /// Returns the wrapped function.
36    pub const fn function(&self) -> &F {
37        &self.function
38    }
39
40    /// Returns a mutable reference to the wrapped function.
41    pub fn function_mut(&mut self) -> &mut F {
42        &mut self.function
43    }
44
45    /// Consumes the adapter and returns the wrapped function.
46    pub fn into_inner(self) -> F {
47        self.function
48    }
49}
50
51impl<C, R, E, F, Params> Before<C, R, E> for BeforeFn<F, Params>
52where
53    F: Handler<C, R, (), E, Params>,
54{
55    fn run_before(&self, context: &mut C, resources: &mut R) -> Result<(), StageError<E>> {
56        self.function.run(context, resources)
57    }
58}