Skip to main content

dispatch_core/
lib.rs

1#![no_std]
2#![deny(unsafe_op_in_unsafe_fn)]
3#![warn(missing_docs)]
4#![doc = include_str!("../README.md")]
5
6mod after;
7mod before;
8mod command;
9mod error;
10mod handler;
11mod param;
12mod response;
13
14pub use after::{After, AfterFn, AfterHandler, NoAfter};
15pub use before::{Before, BeforeFn, NoBefore};
16pub use command::{
17    CommandEntry, CommandHandler, CommandKey, Dispatcher, KeyMatcher, Matcher, ResponseDispatcher,
18    dispatch,
19};
20pub use error::{DispatchError, DispatchStage, FetchError, ParamError, StageError};
21pub use handler::Handler;
22pub use param::{
23    AccessKind, DefaultResourceTag, Res, ResMut, ResourceAccess, ResourceId, ResourceProvider,
24    SystemParam,
25};
26pub use response::{IdentityResponse, ResponseFn, ResponseHandler, ResponseStage};
27
28/// Builds a statically dispatchable command entry from a function.
29///
30/// The entry declares only the routing relationship. Resource requirements are
31/// inferred from [`Res`] and [`ResMut`] parameters in the function signature.
32///
33/// ```text
34/// command!(0x01 => version)
35/// ```
36///
37/// The generated entry contains only the key and a monomorphized function
38/// pointer, so an array of entries can be stored in read-only memory.
39#[macro_export]
40macro_rules! command {
41    ($key:expr => $handler:path $(,)?) => {
42        $crate::CommandEntry::new($key, |context, resources| {
43            $crate::__private::run_handler::<_, _, _, _, _, _>($handler, context, resources)
44        })
45    };
46}
47
48/// Declares an application resource container and its typed field providers.
49///
50/// Each field type is available through [`Res<T>`](Res) and
51/// [`ResMut<T>`](ResMut). A tag after `=>` distinguishes fields that have the
52/// same type.
53///
54/// # Examples
55///
56/// ```
57/// use dispatch_core::resources;
58///
59/// struct Primary;
60/// struct Backup;
61///
62/// resources! {
63///     struct Resources {
64///         counter: u32,
65///         primary_port: u16 => Primary,
66///         backup_port: u16 => Backup,
67///     }
68/// }
69/// ```
70///
71/// A type may occur only once without a tag. Implement [`ResourceProvider`]
72/// manually when the container already exists or lookup requires a custom
73/// backend.
74///
75/// ```compile_fail
76/// use dispatch_core::resources;
77///
78/// resources! {
79///     struct Ambiguous {
80///         first: u32,
81///         second: u32,
82///     }
83/// }
84/// ```
85#[macro_export]
86macro_rules! resources {
87    (
88        $(#[$container_meta:meta])*
89        $container_vis:vis struct $container:ident {
90            $(
91                $(#[$field_meta:meta])*
92                $field_vis:vis $field:ident : $field_type:ty $(=> $tag:ty)?
93            ),* $(,)?
94        }
95    ) => {
96        $(#[$container_meta])*
97        $container_vis struct $container {
98            $(
99                $(#[$field_meta])*
100                $field_vis $field: $field_type,
101            )*
102        }
103
104        $(
105            $crate::resources!(@provider $container, $field, $field_type $(, $tag)?);
106        )*
107    };
108    (@provider $container:ident, $field:ident, $field_type:ty) => {
109        // SAFETY: the identity and pointer projection are generated from the
110        // same ordinary struct field.
111        unsafe impl $crate::ResourceProvider<$field_type> for $container {
112            const ID: $crate::ResourceId = $crate::ResourceId::new(
113                ::core::mem::offset_of!($container, $field),
114            );
115
116            unsafe fn get(resources: *mut Self) -> *mut $field_type {
117                // SAFETY: guaranteed by the `ResourceProvider::get` caller.
118                unsafe { ::core::ptr::addr_of_mut!((*resources).$field) }
119            }
120        }
121    };
122    (@provider $container:ident, $field:ident, $field_type:ty, $tag:ty) => {
123        // SAFETY: the identity and pointer projection are generated from the
124        // same ordinary struct field.
125        unsafe impl $crate::ResourceProvider<$field_type, $tag> for $container {
126            const ID: $crate::ResourceId = $crate::ResourceId::new(
127                ::core::mem::offset_of!($container, $field),
128            );
129
130            unsafe fn get(resources: *mut Self) -> *mut $field_type {
131                // SAFETY: guaranteed by the `ResourceProvider::get` caller.
132                unsafe { ::core::ptr::addr_of_mut!((*resources).$field) }
133            }
134        }
135    };
136}
137
138/// Implementation details used by exported macros.
139///
140/// This module is public only because macros expand in downstream crates. Its
141/// contents are not part of the stable API.
142#[doc(hidden)]
143pub mod __private {
144    use crate::{Handler, StageError};
145
146    pub fn run_handler<Params, C, R, O, E, H>(
147        handler: H,
148        context: &mut C,
149        resources: &mut R,
150    ) -> Result<O, StageError<E>>
151    where
152        H: Handler<C, R, O, E, Params>,
153    {
154        handler.run(context, resources)
155    }
156}