bevy_reflect/
tuple_struct.rs

1use bevy_reflect_derive::impl_type_path;
2
3use crate::generics::impl_generic_info_methods;
4use crate::{
5    attributes::{impl_custom_attribute_methods, CustomAttributes},
6    type_info::impl_type_methods,
7    ApplyError, DynamicTuple, Generics, PartialReflect, Reflect, ReflectKind, ReflectMut,
8    ReflectOwned, ReflectRef, Tuple, Type, TypeInfo, TypePath, UnnamedField,
9};
10use alloc::{boxed::Box, vec::Vec};
11use bevy_platform::sync::Arc;
12use core::{
13    fmt::{Debug, Formatter},
14    slice::Iter,
15};
16
17/// A trait used to power [tuple struct-like] operations via [reflection].
18///
19/// This trait uses the [`Reflect`] trait to allow implementors to have their fields
20/// be dynamically addressed by index.
21///
22/// When using [`#[derive(Reflect)]`](derive@crate::Reflect) on a tuple struct,
23/// this trait will be automatically implemented.
24///
25/// # Example
26///
27/// ```
28/// use bevy_reflect::{PartialReflect, Reflect, TupleStruct};
29///
30/// #[derive(Reflect)]
31/// struct Foo(u32);
32///
33/// let foo = Foo(123);
34///
35/// assert_eq!(foo.field_len(), 1);
36///
37/// let field: &dyn PartialReflect = foo.field(0).unwrap();
38/// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123));
39/// ```
40///
41/// [tuple struct-like]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-tuple-structs-without-named-fields-to-create-different-types
42/// [reflection]: crate
43pub trait TupleStruct: PartialReflect {
44    /// Returns a reference to the value of the field with index `index` as a
45    /// `&dyn Reflect`.
46    fn field(&self, index: usize) -> Option<&dyn PartialReflect>;
47
48    /// Returns a mutable reference to the value of the field with index `index`
49    /// as a `&mut dyn Reflect`.
50    fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
51
52    /// Returns the number of fields in the tuple struct.
53    fn field_len(&self) -> usize;
54
55    /// Returns an iterator over the values of the tuple struct's fields.
56    fn iter_fields(&self) -> TupleStructFieldIter;
57
58    /// Clones the struct into a [`DynamicTupleStruct`].
59    #[deprecated(since = "0.16.0", note = "use `to_dynamic_tuple_struct` instead")]
60    fn clone_dynamic(&self) -> DynamicTupleStruct {
61        self.to_dynamic_tuple_struct()
62    }
63
64    /// Creates a new [`DynamicTupleStruct`] from this tuple struct.
65    fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct {
66        DynamicTupleStruct {
67            represented_type: self.get_represented_type_info(),
68            fields: self.iter_fields().map(PartialReflect::to_dynamic).collect(),
69        }
70    }
71
72    /// Will return `None` if [`TypeInfo`] is not available.
73    fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo> {
74        self.get_represented_type_info()?.as_tuple_struct().ok()
75    }
76}
77
78/// A container for compile-time tuple struct info.
79#[derive(Clone, Debug)]
80pub struct TupleStructInfo {
81    ty: Type,
82    generics: Generics,
83    fields: Box<[UnnamedField]>,
84    custom_attributes: Arc<CustomAttributes>,
85    #[cfg(feature = "documentation")]
86    docs: Option<&'static str>,
87}
88
89impl TupleStructInfo {
90    /// Create a new [`TupleStructInfo`].
91    ///
92    /// # Arguments
93    ///
94    /// * `fields`: The fields of this struct in the order they are defined
95    pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self {
96        Self {
97            ty: Type::of::<T>(),
98            generics: Generics::new(),
99            fields: fields.to_vec().into_boxed_slice(),
100            custom_attributes: Arc::new(CustomAttributes::default()),
101            #[cfg(feature = "documentation")]
102            docs: None,
103        }
104    }
105
106    /// Sets the docstring for this struct.
107    #[cfg(feature = "documentation")]
108    pub fn with_docs(self, docs: Option<&'static str>) -> Self {
109        Self { docs, ..self }
110    }
111
112    /// Sets the custom attributes for this struct.
113    pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {
114        Self {
115            custom_attributes: Arc::new(custom_attributes),
116            ..self
117        }
118    }
119
120    /// Get the field at the given index.
121    pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {
122        self.fields.get(index)
123    }
124
125    /// Iterate over the fields of this struct.
126    pub fn iter(&self) -> Iter<'_, UnnamedField> {
127        self.fields.iter()
128    }
129
130    /// The total number of fields in this struct.
131    pub fn field_len(&self) -> usize {
132        self.fields.len()
133    }
134
135    impl_type_methods!(ty);
136
137    /// The docstring of this struct, if any.
138    #[cfg(feature = "documentation")]
139    pub fn docs(&self) -> Option<&'static str> {
140        self.docs
141    }
142
143    impl_custom_attribute_methods!(self.custom_attributes, "struct");
144
145    impl_generic_info_methods!(generics);
146}
147
148/// An iterator over the field values of a tuple struct.
149pub struct TupleStructFieldIter<'a> {
150    pub(crate) tuple_struct: &'a dyn TupleStruct,
151    pub(crate) index: usize,
152}
153
154impl<'a> TupleStructFieldIter<'a> {
155    pub fn new(value: &'a dyn TupleStruct) -> Self {
156        TupleStructFieldIter {
157            tuple_struct: value,
158            index: 0,
159        }
160    }
161}
162
163impl<'a> Iterator for TupleStructFieldIter<'a> {
164    type Item = &'a dyn PartialReflect;
165
166    fn next(&mut self) -> Option<Self::Item> {
167        let value = self.tuple_struct.field(self.index);
168        self.index += value.is_some() as usize;
169        value
170    }
171
172    fn size_hint(&self) -> (usize, Option<usize>) {
173        let size = self.tuple_struct.field_len();
174        (size, Some(size))
175    }
176}
177
178impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {}
179
180/// A convenience trait which combines fetching and downcasting of tuple
181/// struct fields.
182///
183/// # Example
184///
185/// ```
186/// use bevy_reflect::{GetTupleStructField, Reflect};
187///
188/// #[derive(Reflect)]
189/// struct Foo(String);
190///
191/// # fn main() {
192/// let mut foo = Foo("Hello, world!".to_string());
193///
194/// foo.get_field_mut::<String>(0).unwrap().truncate(5);
195/// assert_eq!(foo.get_field::<String>(0), Some(&"Hello".to_string()));
196/// # }
197/// ```
198pub trait GetTupleStructField {
199    /// Returns a reference to the value of the field with index `index`,
200    /// downcast to `T`.
201    fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;
202
203    /// Returns a mutable reference to the value of the field with index
204    /// `index`, downcast to `T`.
205    fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>;
206}
207
208impl<S: TupleStruct> GetTupleStructField for S {
209    fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
210        self.field(index)
211            .and_then(|value| value.try_downcast_ref::<T>())
212    }
213
214    fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
215        self.field_mut(index)
216            .and_then(|value| value.try_downcast_mut::<T>())
217    }
218}
219
220impl GetTupleStructField for dyn TupleStruct {
221    fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
222        self.field(index)
223            .and_then(|value| value.try_downcast_ref::<T>())
224    }
225
226    fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
227        self.field_mut(index)
228            .and_then(|value| value.try_downcast_mut::<T>())
229    }
230}
231
232/// A tuple struct which allows fields to be added at runtime.
233#[derive(Default)]
234pub struct DynamicTupleStruct {
235    represented_type: Option<&'static TypeInfo>,
236    fields: Vec<Box<dyn PartialReflect>>,
237}
238
239impl DynamicTupleStruct {
240    /// Sets the [type] to be represented by this `DynamicTupleStruct`.
241    ///
242    /// # Panics
243    ///
244    /// Panics if the given [type] is not a [`TypeInfo::TupleStruct`].
245    ///
246    /// [type]: TypeInfo
247    pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
248        if let Some(represented_type) = represented_type {
249            assert!(
250                matches!(represented_type, TypeInfo::TupleStruct(_)),
251                "expected TypeInfo::TupleStruct but received: {:?}",
252                represented_type
253            );
254        }
255
256        self.represented_type = represented_type;
257    }
258
259    /// Appends an element with value `value` to the tuple struct.
260    pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) {
261        self.fields.push(value);
262    }
263
264    /// Appends a typed element with value `value` to the tuple struct.
265    pub fn insert<T: PartialReflect>(&mut self, value: T) {
266        self.insert_boxed(Box::new(value));
267    }
268}
269
270impl TupleStruct for DynamicTupleStruct {
271    #[inline]
272    fn field(&self, index: usize) -> Option<&dyn PartialReflect> {
273        self.fields.get(index).map(|field| &**field)
274    }
275
276    #[inline]
277    fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
278        self.fields.get_mut(index).map(|field| &mut **field)
279    }
280
281    #[inline]
282    fn field_len(&self) -> usize {
283        self.fields.len()
284    }
285
286    #[inline]
287    fn iter_fields(&self) -> TupleStructFieldIter {
288        TupleStructFieldIter {
289            tuple_struct: self,
290            index: 0,
291        }
292    }
293}
294
295impl PartialReflect for DynamicTupleStruct {
296    #[inline]
297    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
298        self.represented_type
299    }
300
301    #[inline]
302    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
303        self
304    }
305
306    #[inline]
307    fn as_partial_reflect(&self) -> &dyn PartialReflect {
308        self
309    }
310
311    #[inline]
312    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
313        self
314    }
315
316    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
317        Err(self)
318    }
319
320    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
321        None
322    }
323
324    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
325        None
326    }
327
328    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
329        let tuple_struct = value.reflect_ref().as_tuple_struct()?;
330
331        for (i, value) in tuple_struct.iter_fields().enumerate() {
332            if let Some(v) = self.field_mut(i) {
333                v.try_apply(value)?;
334            }
335        }
336
337        Ok(())
338    }
339
340    #[inline]
341    fn reflect_kind(&self) -> ReflectKind {
342        ReflectKind::TupleStruct
343    }
344
345    #[inline]
346    fn reflect_ref(&self) -> ReflectRef {
347        ReflectRef::TupleStruct(self)
348    }
349
350    #[inline]
351    fn reflect_mut(&mut self) -> ReflectMut {
352        ReflectMut::TupleStruct(self)
353    }
354
355    #[inline]
356    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
357        ReflectOwned::TupleStruct(self)
358    }
359
360    #[inline]
361    fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
362        tuple_struct_partial_eq(self, value)
363    }
364
365    fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
366        write!(f, "DynamicTupleStruct(")?;
367        tuple_struct_debug(self, f)?;
368        write!(f, ")")
369    }
370
371    #[inline]
372    fn is_dynamic(&self) -> bool {
373        true
374    }
375}
376
377impl_type_path!((in bevy_reflect) DynamicTupleStruct);
378
379impl Debug for DynamicTupleStruct {
380    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
381        self.debug(f)
382    }
383}
384
385impl From<DynamicTuple> for DynamicTupleStruct {
386    fn from(value: DynamicTuple) -> Self {
387        Self {
388            represented_type: None,
389            fields: Box::new(value).drain(),
390        }
391    }
392}
393
394impl FromIterator<Box<dyn PartialReflect>> for DynamicTupleStruct {
395    fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(fields: I) -> Self {
396        Self {
397            represented_type: None,
398            fields: fields.into_iter().collect(),
399        }
400    }
401}
402
403impl IntoIterator for DynamicTupleStruct {
404    type Item = Box<dyn PartialReflect>;
405    type IntoIter = alloc::vec::IntoIter<Self::Item>;
406
407    fn into_iter(self) -> Self::IntoIter {
408        self.fields.into_iter()
409    }
410}
411
412impl<'a> IntoIterator for &'a DynamicTupleStruct {
413    type Item = &'a dyn PartialReflect;
414    type IntoIter = TupleStructFieldIter<'a>;
415
416    fn into_iter(self) -> Self::IntoIter {
417        self.iter_fields()
418    }
419}
420
421/// Compares a [`TupleStruct`] with a [`PartialReflect`] value.
422///
423/// Returns true if and only if all of the following are true:
424/// - `b` is a tuple struct;
425/// - `b` has the same number of fields as `a`;
426/// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise fields of `a` and `b`.
427///
428/// Returns [`None`] if the comparison couldn't even be performed.
429#[inline]
430pub fn tuple_struct_partial_eq<S: TupleStruct + ?Sized>(
431    a: &S,
432    b: &dyn PartialReflect,
433) -> Option<bool> {
434    let ReflectRef::TupleStruct(tuple_struct) = b.reflect_ref() else {
435        return Some(false);
436    };
437
438    if a.field_len() != tuple_struct.field_len() {
439        return Some(false);
440    }
441
442    for (i, value) in tuple_struct.iter_fields().enumerate() {
443        if let Some(field_value) = a.field(i) {
444            let eq_result = field_value.reflect_partial_eq(value);
445            if let failed @ (Some(false) | None) = eq_result {
446                return failed;
447            }
448        } else {
449            return Some(false);
450        }
451    }
452
453    Some(true)
454}
455
456/// The default debug formatter for [`TupleStruct`] types.
457///
458/// # Example
459/// ```
460/// use bevy_reflect::Reflect;
461/// #[derive(Reflect)]
462/// struct MyTupleStruct(usize);
463///
464/// let my_tuple_struct: &dyn Reflect = &MyTupleStruct(123);
465/// println!("{:#?}", my_tuple_struct);
466///
467/// // Output:
468///
469/// // MyTupleStruct (
470/// //   123,
471/// // )
472/// ```
473#[inline]
474pub fn tuple_struct_debug(
475    dyn_tuple_struct: &dyn TupleStruct,
476    f: &mut Formatter<'_>,
477) -> core::fmt::Result {
478    let mut debug = f.debug_tuple(
479        dyn_tuple_struct
480            .get_represented_type_info()
481            .map(TypeInfo::type_path)
482            .unwrap_or("_"),
483    );
484    for field in dyn_tuple_struct.iter_fields() {
485        debug.field(&field as &dyn Debug);
486    }
487    debug.finish()
488}
489
490#[cfg(test)]
491mod tests {
492    use crate::*;
493    #[derive(Reflect)]
494    struct Ts(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8);
495    #[test]
496    fn next_index_increment() {
497        let mut iter = Ts(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields();
498        let size = iter.len();
499        iter.index = size - 1;
500        let prev_index = iter.index;
501        assert!(iter.next().is_some());
502        assert_eq!(prev_index, iter.index - 1);
503
504        // When None we should no longer increase index
505        assert!(iter.next().is_none());
506        assert_eq!(size, iter.index);
507        assert!(iter.next().is_none());
508        assert_eq!(size, iter.index);
509    }
510}