Skip to main content

dispatch_core/
param.rs

1use core::{
2    fmt,
3    marker::PhantomData,
4    ops::{Deref, DerefMut},
5};
6
7use crate::ParamError;
8
9/// Default identity tag used when a resource type occurs only once.
10#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
11pub struct DefaultResourceTag;
12
13/// Stable identity of one logical resource within a resource container.
14///
15/// Equal identifiers mean that accesses may touch the same memory. Different
16/// identifiers must mean that returned values do not overlap. The
17/// [`crate::resources!`] macro derives identities from field offsets.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct ResourceId(usize);
20
21impl ResourceId {
22    /// Creates an identity from an application-defined value.
23    ///
24    /// Manual resource implementations must use the same value for every
25    /// provider that may access overlapping memory.
26    pub const fn new(value: usize) -> Self {
27        Self(value)
28    }
29
30    /// Returns the allocation-free identity value.
31    pub const fn get(self) -> usize {
32        self.0
33    }
34}
35
36/// The kind of access a system parameter requests.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum AccessKind {
39    /// The parameter does not borrow a resource.
40    None,
41
42    /// Any number of parameters may share this resource.
43    Shared,
44
45    /// Exactly one parameter may access this resource.
46    Exclusive,
47}
48
49/// Static access metadata for one system parameter.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct ResourceAccess {
52    resource: ResourceId,
53    kind: AccessKind,
54}
55
56impl ResourceAccess {
57    /// Declares a parameter that does not borrow from the resource container.
58    pub const fn none() -> Self {
59        Self {
60            resource: ResourceId::new(0),
61            kind: AccessKind::None,
62        }
63    }
64
65    /// Declares shared access to `resource`.
66    pub const fn shared(resource: ResourceId) -> Self {
67        Self {
68            resource,
69            kind: AccessKind::Shared,
70        }
71    }
72
73    /// Declares exclusive access to `resource`.
74    pub const fn exclusive(resource: ResourceId) -> Self {
75        Self {
76            resource,
77            kind: AccessKind::Exclusive,
78        }
79    }
80
81    /// Returns the logical resource identity.
82    pub const fn resource(self) -> ResourceId {
83        self.resource
84    }
85
86    /// Returns the requested access kind.
87    pub const fn kind(self) -> AccessKind {
88        self.kind
89    }
90
91    const fn conflicts(self, other: Self) -> bool {
92        if matches!(self.kind, AccessKind::None) || matches!(other.kind, AccessKind::None) {
93            return false;
94        }
95
96        self.resource.0 == other.resource.0
97            && (matches!(self.kind, AccessKind::Exclusive)
98                || matches!(other.kind, AccessKind::Exclusive))
99    }
100}
101
102/// Provides one typed resource from an application-owned container.
103///
104/// `Tag` distinguishes multiple fields with the same `T`. Applications should
105/// normally use [`crate::resources!`], which generates these implementations
106/// together with the resource container.
107///
108/// # Safety
109///
110/// Every implementation that may return overlapping memory must use the same
111/// `ID`. A non-null, aligned pointer returned by `get` must point to a live `T`
112/// inside `Self`, remain valid while the container is exclusively borrowed,
113/// and must not be used to move the container field. Null or misaligned
114/// pointers are reported as [`crate::FetchError::InvalidPointer`].
115pub unsafe trait ResourceProvider<T: ?Sized + 'static, Tag: 'static = DefaultResourceTag> {
116    /// Identity used to detect overlapping shared and exclusive access.
117    const ID: ResourceId;
118
119    /// Returns a pointer to the provided resource.
120    ///
121    /// # Safety
122    ///
123    /// `resources` must point to a live, properly aligned `Self` that is
124    /// exclusively borrowed for the entire lifetime of any value derived from
125    /// the returned pointer.
126    unsafe fn get(resources: *mut Self) -> *mut T;
127}
128
129/// Shared view of one resource.
130///
131/// The resource type and optional tag identify the required capability in a
132/// command signature. `Res` is a transparent borrowing wrapper and allocates
133/// no memory.
134#[repr(transparent)]
135pub struct Res<'resources, T: ?Sized + 'static, Tag: 'static = DefaultResourceTag> {
136    value: &'resources T,
137    marker: PhantomData<fn() -> Tag>,
138}
139
140impl<T, Tag> Clone for Res<'_, T, Tag>
141where
142    T: ?Sized + 'static,
143    Tag: 'static,
144{
145    fn clone(&self) -> Self {
146        *self
147    }
148}
149
150impl<T, Tag> Copy for Res<'_, T, Tag>
151where
152    T: ?Sized + 'static,
153    Tag: 'static,
154{
155}
156
157impl<'resources, T, Tag> Res<'resources, T, Tag>
158where
159    T: ?Sized + 'static,
160    Tag: 'static,
161{
162    /// Returns the wrapped shared reference.
163    pub const fn into_inner(self) -> &'resources T {
164        self.value
165    }
166}
167
168impl<T, Tag> Deref for Res<'_, T, Tag>
169where
170    T: ?Sized + 'static,
171    Tag: 'static,
172{
173    type Target = T;
174
175    fn deref(&self) -> &Self::Target {
176        self.value
177    }
178}
179
180impl<T, Tag> fmt::Debug for Res<'_, T, Tag>
181where
182    T: fmt::Debug + ?Sized + 'static,
183    Tag: 'static,
184{
185    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
186        self.value.fmt(formatter)
187    }
188}
189
190/// Exclusive view of one resource.
191///
192/// The resource type and optional tag identify the required capability in a
193/// command signature. `ResMut` is a transparent borrowing wrapper and
194/// allocates no memory.
195#[repr(transparent)]
196pub struct ResMut<'resources, T: ?Sized + 'static, Tag: 'static = DefaultResourceTag> {
197    value: &'resources mut T,
198    marker: PhantomData<fn() -> Tag>,
199}
200
201impl<'resources, T, Tag> ResMut<'resources, T, Tag>
202where
203    T: ?Sized + 'static,
204    Tag: 'static,
205{
206    /// Returns the wrapped exclusive reference.
207    pub fn into_inner(self) -> &'resources mut T {
208        self.value
209    }
210}
211
212impl<T, Tag> Deref for ResMut<'_, T, Tag>
213where
214    T: ?Sized + 'static,
215    Tag: 'static,
216{
217    type Target = T;
218
219    fn deref(&self) -> &Self::Target {
220        self.value
221    }
222}
223
224impl<T, Tag> DerefMut for ResMut<'_, T, Tag>
225where
226    T: ?Sized + 'static,
227    Tag: 'static,
228{
229    fn deref_mut(&mut self) -> &mut Self::Target {
230        self.value
231    }
232}
233
234impl<T, Tag> fmt::Debug for ResMut<'_, T, Tag>
235where
236    T: fmt::Debug + ?Sized + 'static,
237    Tag: 'static,
238{
239    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
240        self.value.fmt(formatter)
241    }
242}
243
244/// Extracts one typed argument from a resource container.
245///
246/// Most commands use [`Res`] and [`ResMut`], which implement this trait through
247/// [`ResourceProvider`]. Manual implementations support fallible maps, guards,
248/// handles, and application-specific parameter types.
249///
250/// # Safety
251///
252/// An implementation must uphold all of these requirements:
253///
254/// - every returned value is valid only for `Item<'resources>` and does not
255///   outlive the pointed-to container;
256/// - returned values access only the logical resource declared by `ACCESS`;
257/// - implementations that may touch overlapping memory use the same
258///   [`ResourceId`];
259/// - shared access never permits unsound mutation, while exclusive access may
260///   produce unique mutable references;
261/// - `fetch` does not move or invalidate the resource container.
262pub unsafe trait SystemParam<R> {
263    /// Argument passed to the command for one resource-container lifetime.
264    type Item<'resources>;
265
266    /// Memory access performed by this parameter.
267    const ACCESS: ResourceAccess;
268
269    /// Extracts the command argument from `resources`.
270    ///
271    /// # Safety
272    ///
273    /// `resources` must be non-null, properly aligned, and point to a valid `R`
274    /// exclusively borrowed for `'resources`. The caller must validate this
275    /// access against every other live parameter before calling `fetch`.
276    unsafe fn fetch<'resources>(
277        resources: *mut R,
278    ) -> Result<Self::Item<'resources>, crate::FetchError>;
279}
280
281// SAFETY: `ResourceProvider` supplies a valid pointer and identity. Handler
282// validation prevents an exclusive access from overlapping this shared view.
283unsafe impl<'param, R, T, Tag> SystemParam<R> for Res<'param, T, Tag>
284where
285    R: ResourceProvider<T, Tag>,
286    T: 'static,
287    Tag: 'static,
288{
289    type Item<'resources> = Res<'resources, T, Tag>;
290
291    const ACCESS: ResourceAccess = ResourceAccess::shared(R::ID);
292
293    unsafe fn fetch<'resources>(
294        resources: *mut R,
295    ) -> Result<Self::Item<'resources>, crate::FetchError> {
296        // SAFETY: delegated to the caller and `ResourceProvider` contract.
297        let value = unsafe { R::get(resources) };
298
299        if value.is_null() || !value.is_aligned() {
300            return Err(crate::FetchError::InvalidPointer);
301        }
302
303        // SAFETY: the provider guarantees a live, aligned pointer, and access
304        // validation has ruled out every overlapping mutable reference.
305        Ok(Res {
306            value: unsafe { &*value },
307            marker: PhantomData,
308        })
309    }
310}
311
312// SAFETY: `ResourceProvider` supplies a valid pointer and identity. Handler
313// validation guarantees that this is the only access to the same resource.
314unsafe impl<'param, R, T, Tag> SystemParam<R> for ResMut<'param, T, Tag>
315where
316    R: ResourceProvider<T, Tag>,
317    T: 'static,
318    Tag: 'static,
319{
320    type Item<'resources> = ResMut<'resources, T, Tag>;
321
322    const ACCESS: ResourceAccess = ResourceAccess::exclusive(R::ID);
323
324    unsafe fn fetch<'resources>(
325        resources: *mut R,
326    ) -> Result<Self::Item<'resources>, crate::FetchError> {
327        // SAFETY: delegated to the caller and `ResourceProvider` contract.
328        let value = unsafe { R::get(resources) };
329
330        if value.is_null() || !value.is_aligned() {
331            return Err(crate::FetchError::InvalidPointer);
332        }
333
334        // SAFETY: the provider guarantees a live, aligned pointer, and access
335        // validation has ruled out every overlapping reference.
336        Ok(ResMut {
337            value: unsafe { &mut *value },
338            marker: PhantomData,
339        })
340    }
341}
342
343pub(crate) trait ParamSet<R> {
344    type Item<'resources>
345    where
346        R: 'resources;
347
348    /// Validates and fetches one complete set of simultaneously live params.
349    fn fetch<'resources>(
350        resources: &'resources mut R,
351    ) -> Result<Self::Item<'resources>, ParamError>;
352}
353
354macro_rules! impl_param_set {
355    ($($param:ident => $value:ident @ $index:expr),+ $(,)?) => {
356        impl<R, $($param),+> ParamSet<R> for ($($param,)+)
357        where
358            $($param: SystemParam<R>,)+
359        {
360            type Item<'resources> = ($($param::Item<'resources>,)+)
361            where
362                R: 'resources;
363
364            fn fetch<'resources>(
365                resources: &'resources mut R,
366            ) -> Result<Self::Item<'resources>, ParamError> {
367                let accesses = [$($param::ACCESS),+];
368                validate_accesses(&accesses)?;
369                let resources = resources as *mut R;
370
371                $(
372                    // SAFETY: the pointer comes from the exclusive borrow for
373                    // `'resources`. All simultaneous accesses were validated
374                    // before this first parameter was fetched.
375                    let $value = unsafe { $param::fetch::<'resources>(resources) }
376                        .map_err(|error| ParamError::Fetch {
377                            index: $index,
378                            error,
379                        })?;
380                )+
381
382                Ok(($($value,)+))
383            }
384        }
385    };
386}
387
388impl_param_set!(P0 => p0 @ 0);
389impl_param_set!(P0 => p0 @ 0, P1 => p1 @ 1);
390impl_param_set!(P0 => p0 @ 0, P1 => p1 @ 1, P2 => p2 @ 2);
391impl_param_set!(P0 => p0 @ 0, P1 => p1 @ 1, P2 => p2 @ 2, P3 => p3 @ 3);
392impl_param_set!(
393    P0 => p0 @ 0,
394    P1 => p1 @ 1,
395    P2 => p2 @ 2,
396    P3 => p3 @ 3,
397    P4 => p4 @ 4,
398);
399impl_param_set!(
400    P0 => p0 @ 0,
401    P1 => p1 @ 1,
402    P2 => p2 @ 2,
403    P3 => p3 @ 3,
404    P4 => p4 @ 4,
405    P5 => p5 @ 5,
406);
407impl_param_set!(
408    P0 => p0 @ 0,
409    P1 => p1 @ 1,
410    P2 => p2 @ 2,
411    P3 => p3 @ 3,
412    P4 => p4 @ 4,
413    P5 => p5 @ 5,
414    P6 => p6 @ 6,
415);
416impl_param_set!(
417    P0 => p0 @ 0,
418    P1 => p1 @ 1,
419    P2 => p2 @ 2,
420    P3 => p3 @ 3,
421    P4 => p4 @ 4,
422    P5 => p5 @ 5,
423    P6 => p6 @ 6,
424    P7 => p7 @ 7,
425);
426
427pub(crate) fn validate_accesses(accesses: &[ResourceAccess]) -> Result<(), ParamError> {
428    let mut second = 1;
429
430    while second < accesses.len() {
431        let mut first = 0;
432
433        while first < second {
434            if accesses[first].conflicts(accesses[second]) {
435                return Err(ParamError::AccessConflict {
436                    first: first as u8,
437                    second: second as u8,
438                    resource: accesses[first].resource,
439                });
440            }
441
442            first += 1;
443        }
444
445        second += 1;
446    }
447
448    Ok(())
449}