Path: blob/main/crates/bevy_reflect/src/tuple_struct.rs
6598 views
use bevy_reflect_derive::impl_type_path;12use crate::generics::impl_generic_info_methods;3use crate::{4attributes::{impl_custom_attribute_methods, CustomAttributes},5type_info::impl_type_methods,6ApplyError, DynamicTuple, Generics, PartialReflect, Reflect, ReflectKind, ReflectMut,7ReflectOwned, ReflectRef, Tuple, Type, TypeInfo, TypePath, UnnamedField,8};9use alloc::{boxed::Box, vec::Vec};10use bevy_platform::sync::Arc;11use core::{12fmt::{Debug, Formatter},13slice::Iter,14};1516/// A trait used to power [tuple struct-like] operations via [reflection].17///18/// This trait uses the [`Reflect`] trait to allow implementors to have their fields19/// be dynamically addressed by index.20///21/// When using [`#[derive(Reflect)]`](derive@crate::Reflect) on a tuple struct,22/// this trait will be automatically implemented.23///24/// # Example25///26/// ```27/// use bevy_reflect::{PartialReflect, Reflect, TupleStruct};28///29/// #[derive(Reflect)]30/// struct Foo(u32);31///32/// let foo = Foo(123);33///34/// assert_eq!(foo.field_len(), 1);35///36/// let field: &dyn PartialReflect = foo.field(0).unwrap();37/// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123));38/// ```39///40/// [tuple struct-like]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-tuple-structs-without-named-fields-to-create-different-types41/// [reflection]: crate42pub trait TupleStruct: PartialReflect {43/// Returns a reference to the value of the field with index `index` as a44/// `&dyn Reflect`.45fn field(&self, index: usize) -> Option<&dyn PartialReflect>;4647/// Returns a mutable reference to the value of the field with index `index`48/// as a `&mut dyn Reflect`.49fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;5051/// Returns the number of fields in the tuple struct.52fn field_len(&self) -> usize;5354/// Returns an iterator over the values of the tuple struct's fields.55fn iter_fields(&self) -> TupleStructFieldIter<'_>;5657/// Creates a new [`DynamicTupleStruct`] from this tuple struct.58fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct {59DynamicTupleStruct {60represented_type: self.get_represented_type_info(),61fields: self.iter_fields().map(PartialReflect::to_dynamic).collect(),62}63}6465/// Will return `None` if [`TypeInfo`] is not available.66fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo> {67self.get_represented_type_info()?.as_tuple_struct().ok()68}69}7071/// A container for compile-time tuple struct info.72#[derive(Clone, Debug)]73pub struct TupleStructInfo {74ty: Type,75generics: Generics,76fields: Box<[UnnamedField]>,77custom_attributes: Arc<CustomAttributes>,78#[cfg(feature = "documentation")]79docs: Option<&'static str>,80}8182impl TupleStructInfo {83/// Create a new [`TupleStructInfo`].84///85/// # Arguments86///87/// * `fields`: The fields of this struct in the order they are defined88pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self {89Self {90ty: Type::of::<T>(),91generics: Generics::new(),92fields: fields.to_vec().into_boxed_slice(),93custom_attributes: Arc::new(CustomAttributes::default()),94#[cfg(feature = "documentation")]95docs: None,96}97}9899/// Sets the docstring for this struct.100#[cfg(feature = "documentation")]101pub fn with_docs(self, docs: Option<&'static str>) -> Self {102Self { docs, ..self }103}104105/// Sets the custom attributes for this struct.106pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {107Self {108custom_attributes: Arc::new(custom_attributes),109..self110}111}112113/// Get the field at the given index.114pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {115self.fields.get(index)116}117118/// Iterate over the fields of this struct.119pub fn iter(&self) -> Iter<'_, UnnamedField> {120self.fields.iter()121}122123/// The total number of fields in this struct.124pub fn field_len(&self) -> usize {125self.fields.len()126}127128impl_type_methods!(ty);129130/// The docstring of this struct, if any.131#[cfg(feature = "documentation")]132pub fn docs(&self) -> Option<&'static str> {133self.docs134}135136impl_custom_attribute_methods!(self.custom_attributes, "struct");137138impl_generic_info_methods!(generics);139}140141/// An iterator over the field values of a tuple struct.142pub struct TupleStructFieldIter<'a> {143pub(crate) tuple_struct: &'a dyn TupleStruct,144pub(crate) index: usize,145}146147impl<'a> TupleStructFieldIter<'a> {148/// Creates a new [`TupleStructFieldIter`].149pub fn new(value: &'a dyn TupleStruct) -> Self {150TupleStructFieldIter {151tuple_struct: value,152index: 0,153}154}155}156157impl<'a> Iterator for TupleStructFieldIter<'a> {158type Item = &'a dyn PartialReflect;159160fn next(&mut self) -> Option<Self::Item> {161let value = self.tuple_struct.field(self.index);162self.index += value.is_some() as usize;163value164}165166fn size_hint(&self) -> (usize, Option<usize>) {167let size = self.tuple_struct.field_len();168(size, Some(size))169}170}171172impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {}173174/// A convenience trait which combines fetching and downcasting of tuple175/// struct fields.176///177/// # Example178///179/// ```180/// use bevy_reflect::{GetTupleStructField, Reflect};181///182/// #[derive(Reflect)]183/// struct Foo(String);184///185/// # fn main() {186/// let mut foo = Foo("Hello, world!".to_string());187///188/// foo.get_field_mut::<String>(0).unwrap().truncate(5);189/// assert_eq!(foo.get_field::<String>(0), Some(&"Hello".to_string()));190/// # }191/// ```192pub trait GetTupleStructField {193/// Returns a reference to the value of the field with index `index`,194/// downcast to `T`.195fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;196197/// Returns a mutable reference to the value of the field with index198/// `index`, downcast to `T`.199fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>;200}201202impl<S: TupleStruct> GetTupleStructField for S {203fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {204self.field(index)205.and_then(|value| value.try_downcast_ref::<T>())206}207208fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {209self.field_mut(index)210.and_then(|value| value.try_downcast_mut::<T>())211}212}213214impl GetTupleStructField for dyn TupleStruct {215fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {216self.field(index)217.and_then(|value| value.try_downcast_ref::<T>())218}219220fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {221self.field_mut(index)222.and_then(|value| value.try_downcast_mut::<T>())223}224}225226/// A tuple struct which allows fields to be added at runtime.227#[derive(Default)]228pub struct DynamicTupleStruct {229represented_type: Option<&'static TypeInfo>,230fields: Vec<Box<dyn PartialReflect>>,231}232233impl DynamicTupleStruct {234/// Sets the [type] to be represented by this `DynamicTupleStruct`.235///236/// # Panics237///238/// Panics if the given [type] is not a [`TypeInfo::TupleStruct`].239///240/// [type]: TypeInfo241pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {242if let Some(represented_type) = represented_type {243assert!(244matches!(represented_type, TypeInfo::TupleStruct(_)),245"expected TypeInfo::TupleStruct but received: {represented_type:?}"246);247}248249self.represented_type = represented_type;250}251252/// Appends an element with value `value` to the tuple struct.253pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) {254self.fields.push(value);255}256257/// Appends a typed element with value `value` to the tuple struct.258pub fn insert<T: PartialReflect>(&mut self, value: T) {259self.insert_boxed(Box::new(value));260}261}262263impl TupleStruct for DynamicTupleStruct {264#[inline]265fn field(&self, index: usize) -> Option<&dyn PartialReflect> {266self.fields.get(index).map(|field| &**field)267}268269#[inline]270fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {271self.fields.get_mut(index).map(|field| &mut **field)272}273274#[inline]275fn field_len(&self) -> usize {276self.fields.len()277}278279#[inline]280fn iter_fields(&self) -> TupleStructFieldIter<'_> {281TupleStructFieldIter {282tuple_struct: self,283index: 0,284}285}286}287288impl PartialReflect for DynamicTupleStruct {289#[inline]290fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {291self.represented_type292}293294#[inline]295fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {296self297}298299#[inline]300fn as_partial_reflect(&self) -> &dyn PartialReflect {301self302}303304#[inline]305fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {306self307}308309fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {310Err(self)311}312313fn try_as_reflect(&self) -> Option<&dyn Reflect> {314None315}316317fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {318None319}320321fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {322let tuple_struct = value.reflect_ref().as_tuple_struct()?;323324for (i, value) in tuple_struct.iter_fields().enumerate() {325if let Some(v) = self.field_mut(i) {326v.try_apply(value)?;327}328}329330Ok(())331}332333#[inline]334fn reflect_kind(&self) -> ReflectKind {335ReflectKind::TupleStruct336}337338#[inline]339fn reflect_ref(&self) -> ReflectRef<'_> {340ReflectRef::TupleStruct(self)341}342343#[inline]344fn reflect_mut(&mut self) -> ReflectMut<'_> {345ReflectMut::TupleStruct(self)346}347348#[inline]349fn reflect_owned(self: Box<Self>) -> ReflectOwned {350ReflectOwned::TupleStruct(self)351}352353#[inline]354fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {355tuple_struct_partial_eq(self, value)356}357358fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {359write!(f, "DynamicTupleStruct(")?;360tuple_struct_debug(self, f)?;361write!(f, ")")362}363364#[inline]365fn is_dynamic(&self) -> bool {366true367}368}369370impl_type_path!((in bevy_reflect) DynamicTupleStruct);371372impl Debug for DynamicTupleStruct {373fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {374self.debug(f)375}376}377378impl From<DynamicTuple> for DynamicTupleStruct {379fn from(value: DynamicTuple) -> Self {380Self {381represented_type: None,382fields: Box::new(value).drain(),383}384}385}386387impl FromIterator<Box<dyn PartialReflect>> for DynamicTupleStruct {388fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(fields: I) -> Self {389Self {390represented_type: None,391fields: fields.into_iter().collect(),392}393}394}395396impl IntoIterator for DynamicTupleStruct {397type Item = Box<dyn PartialReflect>;398type IntoIter = alloc::vec::IntoIter<Self::Item>;399400fn into_iter(self) -> Self::IntoIter {401self.fields.into_iter()402}403}404405impl<'a> IntoIterator for &'a DynamicTupleStruct {406type Item = &'a dyn PartialReflect;407type IntoIter = TupleStructFieldIter<'a>;408409fn into_iter(self) -> Self::IntoIter {410self.iter_fields()411}412}413414/// Compares a [`TupleStruct`] with a [`PartialReflect`] value.415///416/// Returns true if and only if all of the following are true:417/// - `b` is a tuple struct;418/// - `b` has the same number of fields as `a`;419/// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise fields of `a` and `b`.420///421/// Returns [`None`] if the comparison couldn't even be performed.422#[inline]423pub fn tuple_struct_partial_eq<S: TupleStruct + ?Sized>(424a: &S,425b: &dyn PartialReflect,426) -> Option<bool> {427let ReflectRef::TupleStruct(tuple_struct) = b.reflect_ref() else {428return Some(false);429};430431if a.field_len() != tuple_struct.field_len() {432return Some(false);433}434435for (i, value) in tuple_struct.iter_fields().enumerate() {436if let Some(field_value) = a.field(i) {437let eq_result = field_value.reflect_partial_eq(value);438if let failed @ (Some(false) | None) = eq_result {439return failed;440}441} else {442return Some(false);443}444}445446Some(true)447}448449/// The default debug formatter for [`TupleStruct`] types.450///451/// # Example452/// ```453/// use bevy_reflect::Reflect;454/// #[derive(Reflect)]455/// struct MyTupleStruct(usize);456///457/// let my_tuple_struct: &dyn Reflect = &MyTupleStruct(123);458/// println!("{:#?}", my_tuple_struct);459///460/// // Output:461///462/// // MyTupleStruct (463/// // 123,464/// // )465/// ```466#[inline]467pub fn tuple_struct_debug(468dyn_tuple_struct: &dyn TupleStruct,469f: &mut Formatter<'_>,470) -> core::fmt::Result {471let mut debug = f.debug_tuple(472dyn_tuple_struct473.get_represented_type_info()474.map(TypeInfo::type_path)475.unwrap_or("_"),476);477for field in dyn_tuple_struct.iter_fields() {478debug.field(&field as &dyn Debug);479}480debug.finish()481}482483#[cfg(test)]484mod tests {485use crate::*;486#[derive(Reflect)]487struct Ts(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8);488#[test]489fn next_index_increment() {490let mut iter = Ts(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields();491let size = iter.len();492iter.index = size - 1;493let prev_index = iter.index;494assert!(iter.next().is_some());495assert_eq!(prev_index, iter.index - 1);496497// When None we should no longer increase index498assert!(iter.next().is_none());499assert_eq!(size, iter.index);500assert!(iter.next().is_none());501assert_eq!(size, iter.index);502}503}504505506