//! Helpers for working with Bevy reflection.12use crate::TypeInfo;3use alloc::boxed::Box;4use bevy_platform::{5hash::{DefaultHasher, FixedHasher, NoOpHash},6sync::{OnceLock, PoisonError, RwLock},7};8use bevy_utils::TypeIdMap;9use core::{10any::{Any, TypeId},11hash::BuildHasher,12};1314/// A type that can be stored in a ([`Non`])[`GenericTypeCell`].15///16/// [`Non`]: NonGenericTypeCell17pub trait TypedProperty: sealed::Sealed {18/// The type of the value stored in [`GenericTypeCell`].19type Stored: 'static;20}2122/// Used to store a [`String`] in a [`GenericTypePathCell`] as part of a [`TypePath`] implementation.23///24/// [`TypePath`]: crate::TypePath25/// [`String`]: alloc::string::String26pub struct TypePathComponent;2728mod sealed {29use super::{TypeInfo, TypePathComponent, TypedProperty};30use alloc::string::String;3132pub trait Sealed {}3334impl Sealed for TypeInfo {}35impl Sealed for TypePathComponent {}3637impl TypedProperty for TypeInfo {38type Stored = Self;39}4041impl TypedProperty for TypePathComponent {42type Stored = String;43}44}4546/// 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 all50/// monomorphizations of your type.51///52/// Non-generic [`TypePath`]s should be trivially generated with string literals and [`concat!`].53///54/// ## Example55///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: i3263/// }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::TypePath104pub struct NonGenericTypeCell<T: TypedProperty>(OnceLock<T::Stored>);105106/// See [`NonGenericTypeCell`].107pub type NonGenericTypeInfoCell = NonGenericTypeCell<TypeInfo>;108109impl<T: TypedProperty> NonGenericTypeCell<T> {110/// Initialize a [`NonGenericTypeCell`] for non-generic types.111pub const fn new() -> Self {112Self(OnceLock::new())113}114115/// 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.118pub fn get_or_set<F>(&self, f: F) -> &T::Stored119where120F: FnOnce() -> T::Stored,121{122self.0.get_or_init(f)123}124}125126impl<T: TypedProperty> Default for NonGenericTypeCell<T> {127fn default() -> Self {128Self::new()129}130}131132/// 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/// ## Examples141///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_path224/// [`TypePath`]: crate::TypePath225pub struct GenericTypeCell<T: TypedProperty>(RwLock<TypeIdMap<&'static T::Stored>>);226227/// See [`GenericTypeCell`].228pub type GenericTypeInfoCell = GenericTypeCell<TypeInfo>;229/// See [`GenericTypeCell`].230pub type GenericTypePathCell = GenericTypeCell<TypePathComponent>;231232impl<T: TypedProperty> GenericTypeCell<T> {233/// Initialize a [`GenericTypeCell`] for generic types.234pub const fn new() -> Self {235Self(RwLock::new(TypeIdMap::with_hasher(NoOpHash)))236}237238/// 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.242pub fn get_or_insert<G, F>(&self, f: F) -> &T::Stored243where244G: Any + ?Sized,245F: FnOnce() -> T::Stored,246{247self.get_or_insert_by_type_id(TypeId::of::<G>(), f)248}249250/// 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`.253fn get_by_type_id(&self, type_id: TypeId) -> Option<&T::Stored> {254self.0255.read()256.unwrap_or_else(PoisonError::into_inner)257.get(&type_id)258.copied()259}260261/// 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.265fn get_or_insert_by_type_id<F>(&self, type_id: TypeId, f: F) -> &T::Stored266where267F: FnOnce() -> T::Stored,268{269match self.get_by_type_id(type_id) {270Some(info) => info,271None => self.insert_by_type_id(type_id, f()),272}273}274275fn insert_by_type_id(&self, type_id: TypeId, value: T::Stored) -> &T::Stored {276let mut write_lock = self.0.write().unwrap_or_else(PoisonError::into_inner);277278write_lock279.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 statically284// available over the course of the application.285Box::leak(Box::new(value))286})287.get()288}289}290291impl<T: TypedProperty> Default for GenericTypeCell<T> {292fn default() -> Self {293Self::new()294}295}296297/// 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 as300/// checksums for saved scenes, rollback snapshots etc. This function returns301/// such a hasher.302///303/// [`Reflect::reflect_hash`]: crate::Reflect304#[inline]305pub fn reflect_hasher() -> DefaultHasher<'static> {306FixedHasher.build_hasher()307}308309310