bevy_reflect/
utility.rs

1//! Helpers for working with Bevy reflection.
2
3use crate::TypeInfo;
4use alloc::boxed::Box;
5use bevy_platform::{
6    hash::{DefaultHasher, FixedHasher, NoOpHash},
7    sync::{OnceLock, PoisonError, RwLock},
8};
9use bevy_utils::TypeIdMap;
10use core::{
11    any::{Any, TypeId},
12    hash::BuildHasher,
13};
14
15/// A type that can be stored in a ([`Non`])[`GenericTypeCell`].
16///
17/// [`Non`]: NonGenericTypeCell
18pub trait TypedProperty: sealed::Sealed {
19    type Stored: 'static;
20}
21
22/// Used to store a [`String`] in a [`GenericTypePathCell`] as part of a [`TypePath`] implementation.
23///
24/// [`TypePath`]: crate::TypePath
25/// [`String`]: alloc::string::String
26pub struct TypePathComponent;
27
28mod sealed {
29    use super::{TypeInfo, TypePathComponent, TypedProperty};
30    use alloc::string::String;
31
32    pub trait Sealed {}
33
34    impl Sealed for TypeInfo {}
35    impl Sealed for TypePathComponent {}
36
37    impl TypedProperty for TypeInfo {
38        type Stored = Self;
39    }
40
41    impl TypedProperty for TypePathComponent {
42        type Stored = String;
43    }
44}
45
46/// A container for [`TypeInfo`] over non-generic types, allowing instances to be stored statically.
47///
48/// This is specifically meant for use with _non_-generic types. If your type _is_ generic,
49/// then use [`GenericTypeCell`] instead. Otherwise, it will not take into account all
50/// monomorphizations of your type.
51///
52/// Non-generic [`TypePath`]s should be trivially generated with string literals and [`concat!`].
53///
54/// ## Example
55///
56/// ```
57/// # use core::any::Any;
58/// # use bevy_reflect::{DynamicTypePath, NamedField, PartialReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, StructInfo, Typed, TypeInfo, TypePath, ApplyError};
59/// use bevy_reflect::utility::NonGenericTypeInfoCell;
60///
61/// struct Foo {
62///     bar: i32
63/// }
64///
65/// impl Typed for Foo {
66///     fn type_info() -> &'static TypeInfo {
67///         static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
68///         CELL.get_or_set(|| {
69///             let fields = [NamedField::new::<i32>("bar")];
70///             let info = StructInfo::new::<Self>(&fields);
71///             TypeInfo::Struct(info)
72///         })
73///     }
74/// }
75/// # impl TypePath for Foo {
76/// #     fn type_path() -> &'static str { todo!() }
77/// #     fn short_type_path() -> &'static str { todo!() }
78/// # }
79/// # impl PartialReflect for Foo {
80/// #     fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { todo!() }
81/// #     fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { todo!() }
82/// #     fn as_partial_reflect(&self) -> &dyn PartialReflect { todo!() }
83/// #     fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { todo!() }
84/// #     fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { todo!() }
85/// #     fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() }
86/// #     fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() }
87/// #     fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() }
88/// #     fn reflect_ref(&self) -> ReflectRef { todo!() }
89/// #     fn reflect_mut(&mut self) -> ReflectMut { todo!() }
90/// #     fn reflect_owned(self: Box<Self>) -> ReflectOwned { todo!() }
91/// # }
92/// # impl Reflect for Foo {
93/// #     fn into_any(self: Box<Self>) -> Box<dyn Any> { todo!() }
94/// #     fn as_any(&self) -> &dyn Any { todo!() }
95/// #     fn as_any_mut(&mut self) -> &mut dyn Any { todo!() }
96/// #     fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> { todo!() }
97/// #     fn as_reflect(&self) -> &dyn Reflect { todo!() }
98/// #     fn as_reflect_mut(&mut self) -> &mut dyn Reflect { todo!() }
99/// #     fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> { todo!() }
100/// # }
101/// ```
102///
103/// [`TypePath`]: crate::TypePath
104pub struct NonGenericTypeCell<T: TypedProperty>(OnceLock<T::Stored>);
105
106/// See [`NonGenericTypeCell`].
107pub type NonGenericTypeInfoCell = NonGenericTypeCell<TypeInfo>;
108
109impl<T: TypedProperty> NonGenericTypeCell<T> {
110    /// Initialize a [`NonGenericTypeCell`] for non-generic types.
111    pub const fn new() -> Self {
112        Self(OnceLock::new())
113    }
114
115    /// Returns a reference to the [`TypedProperty`] stored in the cell.
116    ///
117    /// If there is no entry found, a new one will be generated from the given function.
118    pub fn get_or_set<F>(&self, f: F) -> &T::Stored
119    where
120        F: FnOnce() -> T::Stored,
121    {
122        self.0.get_or_init(f)
123    }
124}
125
126impl<T: TypedProperty> Default for NonGenericTypeCell<T> {
127    fn default() -> Self {
128        Self::new()
129    }
130}
131
132/// A container for [`TypedProperty`] over generic types, allowing instances to be stored statically.
133///
134/// This is specifically meant for use with generic types. If your type isn't generic,
135/// then use [`NonGenericTypeCell`] instead as it should be much more performant.
136///
137/// `#[derive(TypePath)]` and [`impl_type_path`] should always be used over [`GenericTypePathCell`]
138/// where possible.
139///
140/// ## Examples
141///
142/// Implementing [`TypeInfo`] with generics.
143///
144/// ```
145/// # use core::any::Any;
146/// # use bevy_reflect::{DynamicTypePath, PartialReflect, Reflect, ReflectMut, ReflectOwned, ReflectRef, TupleStructInfo, Typed, TypeInfo, TypePath, UnnamedField, ApplyError, Generics, TypeParamInfo};
147/// use bevy_reflect::utility::GenericTypeInfoCell;
148///
149/// struct Foo<T>(T);
150///
151/// impl<T: Reflect + Typed + TypePath> Typed for Foo<T> {
152///     fn type_info() -> &'static TypeInfo {
153///         static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
154///         CELL.get_or_insert::<Self, _>(|| {
155///             let fields = [UnnamedField::new::<T>(0)];
156///             let info = TupleStructInfo::new::<Self>(&fields)
157///                 .with_generics(Generics::from_iter([TypeParamInfo::new::<T>("T")]));
158///             TypeInfo::TupleStruct(info)
159///         })
160///     }
161/// }
162/// # impl<T: TypePath> TypePath for Foo<T> {
163/// #     fn type_path() -> &'static str { todo!() }
164/// #     fn short_type_path() -> &'static str { todo!() }
165/// # }
166/// # impl<T: PartialReflect + TypePath> PartialReflect for Foo<T> {
167/// #     fn get_represented_type_info(&self) -> Option<&'static TypeInfo> { todo!() }
168/// #     fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> { todo!() }
169/// #     fn as_partial_reflect(&self) -> &dyn PartialReflect { todo!() }
170/// #     fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect { todo!() }
171/// #     fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> { todo!() }
172/// #     fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() }
173/// #     fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() }
174/// #     fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() }
175/// #     fn reflect_ref(&self) -> ReflectRef { todo!() }
176/// #     fn reflect_mut(&mut self) -> ReflectMut { todo!() }
177/// #     fn reflect_owned(self: Box<Self>) -> ReflectOwned { todo!() }
178/// # }
179/// # impl<T: Reflect + Typed + TypePath> Reflect for Foo<T> {
180/// #     fn into_any(self: Box<Self>) -> Box<dyn Any> { todo!() }
181/// #     fn as_any(&self) -> &dyn Any { todo!() }
182/// #     fn as_any_mut(&mut self) -> &mut dyn Any { todo!() }
183/// #     fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> { todo!() }
184/// #     fn as_reflect(&self) -> &dyn Reflect { todo!() }
185/// #     fn as_reflect_mut(&mut self) -> &mut dyn Reflect { todo!() }
186/// #     fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> { todo!() }
187/// # }
188/// ```
189///
190///  Implementing [`TypePath`] with generics.
191///
192/// ```
193/// # use core::any::Any;
194/// # use bevy_reflect::TypePath;
195/// use bevy_reflect::utility::GenericTypePathCell;
196///
197/// struct Foo<T>(T);
198///
199/// impl<T: TypePath> TypePath for Foo<T> {
200///     fn type_path() -> &'static str {
201///         static CELL: GenericTypePathCell = GenericTypePathCell::new();
202///         CELL.get_or_insert::<Self, _>(|| format!("my_crate::foo::Foo<{}>", T::type_path()))
203///     }
204///     
205///     fn short_type_path() -> &'static str {
206///         static CELL: GenericTypePathCell = GenericTypePathCell::new();
207///         CELL.get_or_insert::<Self, _>(|| format!("Foo<{}>", T::short_type_path()))
208///     }
209///
210///     fn type_ident() -> Option<&'static str> {
211///         Some("Foo")
212///     }
213///
214///     fn module_path() -> Option<&'static str> {
215///         Some("my_crate::foo")
216///     }
217///
218///     fn crate_name() -> Option<&'static str> {
219///         Some("my_crate")
220///     }
221/// }
222/// ```
223/// [`impl_type_path`]: crate::impl_type_path
224/// [`TypePath`]: crate::TypePath
225pub struct GenericTypeCell<T: TypedProperty>(RwLock<TypeIdMap<&'static T::Stored>>);
226
227/// See [`GenericTypeCell`].
228pub type GenericTypeInfoCell = GenericTypeCell<TypeInfo>;
229/// See [`GenericTypeCell`].
230pub type GenericTypePathCell = GenericTypeCell<TypePathComponent>;
231
232impl<T: TypedProperty> GenericTypeCell<T> {
233    /// Initialize a [`GenericTypeCell`] for generic types.
234    pub const fn new() -> Self {
235        Self(RwLock::new(TypeIdMap::with_hasher(NoOpHash)))
236    }
237
238    /// Returns a reference to the [`TypedProperty`] stored in the cell.
239    ///
240    /// This method will then return the correct [`TypedProperty`] reference for the given type `T`.
241    /// If there is no entry found, a new one will be generated from the given function.
242    pub fn get_or_insert<G, F>(&self, f: F) -> &T::Stored
243    where
244        G: Any + ?Sized,
245        F: FnOnce() -> T::Stored,
246    {
247        self.get_or_insert_by_type_id(TypeId::of::<G>(), f)
248    }
249
250    /// Returns a reference to the [`TypedProperty`] stored in the cell, if any.
251    ///
252    /// This method will then return the correct [`TypedProperty`] reference for the given type `T`.
253    fn get_by_type_id(&self, type_id: TypeId) -> Option<&T::Stored> {
254        self.0
255            .read()
256            .unwrap_or_else(PoisonError::into_inner)
257            .get(&type_id)
258            .copied()
259    }
260
261    /// Returns a reference to the [`TypedProperty`] stored in the cell.
262    ///
263    /// This method will then return the correct [`TypedProperty`] reference for the given type `T`.
264    /// If there is no entry found, a new one will be generated from the given function.
265    fn get_or_insert_by_type_id<F>(&self, type_id: TypeId, f: F) -> &T::Stored
266    where
267        F: FnOnce() -> T::Stored,
268    {
269        match self.get_by_type_id(type_id) {
270            Some(info) => info,
271            None => self.insert_by_type_id(type_id, f()),
272        }
273    }
274
275    fn insert_by_type_id(&self, type_id: TypeId, value: T::Stored) -> &T::Stored {
276        let mut write_lock = self.0.write().unwrap_or_else(PoisonError::into_inner);
277
278        write_lock
279            .entry(type_id)
280            .insert({
281                // We leak here in order to obtain a `&'static` reference.
282                // Otherwise, we won't be able to return a reference due to the `RwLock`.
283                // This should be okay, though, since we expect it to remain statically
284                // available over the course of the application.
285                Box::leak(Box::new(value))
286            })
287            .get()
288    }
289}
290
291impl<T: TypedProperty> Default for GenericTypeCell<T> {
292    fn default() -> Self {
293        Self::new()
294    }
295}
296
297/// Deterministic fixed state hasher to be used by implementors of [`Reflect::reflect_hash`].
298///
299/// Hashes should be deterministic across processes so hashes can be used as
300/// checksums for saved scenes, rollback snapshots etc. This function returns
301/// such a hasher.
302///
303/// [`Reflect::reflect_hash`]: crate::Reflect
304#[inline]
305pub fn reflect_hasher() -> DefaultHasher {
306    FixedHasher.build_hasher()
307}