bevy_reflect/func/args/
ownership.rs

1use core::fmt::{Display, Formatter};
2
3/// The ownership of a type.
4#[derive(Debug, Copy, Clone, PartialEq, Eq)]
5pub enum Ownership {
6    /// The type is a reference (i.e. `&T`).
7    Ref,
8    /// The type is a mutable reference (i.e. `&mut T`).
9    Mut,
10    /// The type is owned (i.e. `T`).
11    Owned,
12}
13
14impl Display for Ownership {
15    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
16        match self {
17            Self::Ref => write!(f, "reference"),
18            Self::Mut => write!(f, "mutable reference"),
19            Self::Owned => write!(f, "owned"),
20        }
21    }
22}
23
24/// A trait for getting the ownership of a type.
25///
26/// This trait exists so that [`TypedFunction`] can automatically generate
27/// [`FunctionInfo`] containing the proper [`Ownership`] for its [argument] types.
28///
29/// This trait is automatically implemented for non-reference types when using the `Reflect`
30/// [derive macro]. Blanket impls cover `&T` and `&mut T`.
31///
32/// [`TypedFunction`]: crate::func::TypedFunction
33/// [`FunctionInfo`]: crate::func::FunctionInfo
34/// [argument]: crate::func::args::Arg
35/// [derive macro]: derive@crate::Reflect
36pub trait GetOwnership {
37    /// Returns the ownership of [`Self`].
38    fn ownership() -> Ownership {
39        Ownership::Owned
40    }
41}
42
43// Blanket impl.
44impl<T> GetOwnership for &'_ T {
45    fn ownership() -> Ownership {
46        Ownership::Ref
47    }
48}
49
50// Blanket impl.
51impl<T> GetOwnership for &'_ mut T {
52    fn ownership() -> Ownership {
53        Ownership::Mut
54    }
55}
56
57/// Implements the [`GetOwnership`] trait for the given type.
58///
59/// This will implement it for `$ty`, `&$ty`, and `&mut $ty`.
60///
61/// See [`impl_function_traits`] for details on syntax.
62///
63/// [`impl_function_traits`]: crate::func::macros::impl_function_traits
64macro_rules! impl_get_ownership {
65    (
66        $ty: ty
67        $(;
68            < $($T: ident $(: $T1: tt $(+ $T2: tt)*)?),* >
69        )?
70        $(
71            [ $(const $N: ident : $size: ident),* ]
72        )?
73        $(
74            where $($U: ty $(: $U1: tt $(+ $U2: tt)*)?),*
75        )?
76    ) => {
77        impl <
78            $($($T $(: $T1 $(+ $T2)*)?),*)?
79            $(, $(const $N : $size),*)?
80        > $crate::func::args::GetOwnership for $ty
81        $(
82            where $($U $(: $U1 $(+ $U2)*)?),*
83        )?
84        {}
85    };
86}
87
88pub(crate) use impl_get_ownership;