bevy_reflect/
tuple.rs

1use bevy_reflect_derive::impl_type_path;
2use variadics_please::all_tuples;
3
4use crate::generics::impl_generic_info_methods;
5use crate::{
6    type_info::impl_type_methods, utility::GenericTypePathCell, ApplyError, FromReflect, Generics,
7    GetTypeRegistration, MaybeTyped, PartialReflect, Reflect, ReflectCloneError, ReflectKind,
8    ReflectMut, ReflectOwned, ReflectRef, Type, TypeInfo, TypePath, TypeRegistration, TypeRegistry,
9    Typed, UnnamedField,
10};
11use alloc::{boxed::Box, vec, vec::Vec};
12use core::{
13    any::Any,
14    fmt::{Debug, Formatter},
15    slice::Iter,
16};
17
18/// A trait used to power [tuple-like] operations via [reflection].
19///
20/// This trait uses the [`Reflect`] trait to allow implementors to have their fields
21/// be dynamically addressed by index.
22///
23/// This trait is automatically implemented for arbitrary tuples of up to 12
24/// elements, provided that each element implements [`Reflect`].
25///
26/// # Example
27///
28/// ```
29/// use bevy_reflect::{PartialReflect, Tuple};
30///
31/// let foo = (123_u32, true);
32/// assert_eq!(foo.field_len(), 2);
33///
34/// let field: &dyn PartialReflect = foo.field(0).unwrap();
35/// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123));
36/// ```
37///
38/// [tuple-like]: https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type
39/// [reflection]: crate
40pub trait Tuple: PartialReflect {
41    /// Returns a reference to the value of the field with index `index` as a
42    /// `&dyn Reflect`.
43    fn field(&self, index: usize) -> Option<&dyn PartialReflect>;
44
45    /// Returns a mutable reference to the value of the field with index `index`
46    /// as a `&mut dyn Reflect`.
47    fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
48
49    /// Returns the number of fields in the tuple.
50    fn field_len(&self) -> usize;
51
52    /// Returns an iterator over the values of the tuple's fields.
53    fn iter_fields(&self) -> TupleFieldIter<'_>;
54
55    /// Drain the fields of this tuple to get a vector of owned values.
56    fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>>;
57
58    /// Creates a new [`DynamicTuple`] from this tuple.
59    fn to_dynamic_tuple(&self) -> DynamicTuple {
60        DynamicTuple {
61            represented_type: self.get_represented_type_info(),
62            fields: self.iter_fields().map(PartialReflect::to_dynamic).collect(),
63        }
64    }
65
66    /// Will return `None` if [`TypeInfo`] is not available.
67    fn get_represented_tuple_info(&self) -> Option<&'static TupleInfo> {
68        self.get_represented_type_info()?.as_tuple().ok()
69    }
70}
71
72/// An iterator over the field values of a tuple.
73pub struct TupleFieldIter<'a> {
74    pub(crate) tuple: &'a dyn Tuple,
75    pub(crate) index: usize,
76}
77
78impl<'a> TupleFieldIter<'a> {
79    /// Creates a new [`TupleFieldIter`].
80    pub fn new(value: &'a dyn Tuple) -> Self {
81        TupleFieldIter {
82            tuple: value,
83            index: 0,
84        }
85    }
86}
87
88impl<'a> Iterator for TupleFieldIter<'a> {
89    type Item = &'a dyn PartialReflect;
90
91    fn next(&mut self) -> Option<Self::Item> {
92        let value = self.tuple.field(self.index);
93        self.index += value.is_some() as usize;
94        value
95    }
96
97    fn size_hint(&self) -> (usize, Option<usize>) {
98        let size = self.tuple.field_len();
99        (size, Some(size))
100    }
101}
102
103impl<'a> ExactSizeIterator for TupleFieldIter<'a> {}
104
105/// A convenience trait which combines fetching and downcasting of tuple
106/// fields.
107///
108/// # Example
109///
110/// ```
111/// use bevy_reflect::GetTupleField;
112///
113/// # fn main() {
114/// let foo = ("blue".to_string(), 42_i32);
115///
116/// assert_eq!(foo.get_field::<String>(0), Some(&"blue".to_string()));
117/// assert_eq!(foo.get_field::<i32>(1), Some(&42));
118/// # }
119/// ```
120pub trait GetTupleField {
121    /// Returns a reference to the value of the field with index `index`,
122    /// downcast to `T`.
123    fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;
124
125    /// Returns a mutable reference to the value of the field with index
126    /// `index`, downcast to `T`.
127    fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>;
128}
129
130impl<S: Tuple> GetTupleField for S {
131    fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
132        self.field(index)
133            .and_then(|value| value.try_downcast_ref::<T>())
134    }
135
136    fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
137        self.field_mut(index)
138            .and_then(|value| value.try_downcast_mut::<T>())
139    }
140}
141
142impl GetTupleField for dyn Tuple {
143    fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
144        self.field(index)
145            .and_then(|value| value.try_downcast_ref::<T>())
146    }
147
148    fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
149        self.field_mut(index)
150            .and_then(|value| value.try_downcast_mut::<T>())
151    }
152}
153
154/// A container for compile-time tuple info.
155#[derive(Clone, Debug)]
156pub struct TupleInfo {
157    ty: Type,
158    generics: Generics,
159    fields: Box<[UnnamedField]>,
160    #[cfg(feature = "documentation")]
161    docs: Option<&'static str>,
162}
163
164impl TupleInfo {
165    /// Create a new [`TupleInfo`].
166    ///
167    /// # Arguments
168    ///
169    /// * `fields`: The fields of this tuple in the order they are defined
170    pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self {
171        Self {
172            ty: Type::of::<T>(),
173            generics: Generics::new(),
174            fields: fields.to_vec().into_boxed_slice(),
175            #[cfg(feature = "documentation")]
176            docs: None,
177        }
178    }
179
180    /// Sets the docstring for this tuple.
181    #[cfg(feature = "documentation")]
182    pub fn with_docs(self, docs: Option<&'static str>) -> Self {
183        Self { docs, ..self }
184    }
185
186    /// Get the field at the given index.
187    pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {
188        self.fields.get(index)
189    }
190
191    /// Iterate over the fields of this tuple.
192    pub fn iter(&self) -> Iter<'_, UnnamedField> {
193        self.fields.iter()
194    }
195
196    /// The total number of fields in this tuple.
197    pub fn field_len(&self) -> usize {
198        self.fields.len()
199    }
200
201    impl_type_methods!(ty);
202
203    /// The docstring of this tuple, if any.
204    #[cfg(feature = "documentation")]
205    pub fn docs(&self) -> Option<&'static str> {
206        self.docs
207    }
208
209    impl_generic_info_methods!(generics);
210}
211
212/// A tuple which allows fields to be added at runtime.
213#[derive(Default, Debug)]
214pub struct DynamicTuple {
215    represented_type: Option<&'static TypeInfo>,
216    fields: Vec<Box<dyn PartialReflect>>,
217}
218
219impl DynamicTuple {
220    /// Sets the [type] to be represented by this `DynamicTuple`.
221    ///
222    /// # Panics
223    ///
224    /// Panics if the given [type] is not a [`TypeInfo::Tuple`].
225    ///
226    /// [type]: TypeInfo
227    pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
228        if let Some(represented_type) = represented_type {
229            assert!(
230                matches!(represented_type, TypeInfo::Tuple(_)),
231                "expected TypeInfo::Tuple but received: {represented_type:?}"
232            );
233        }
234        self.represented_type = represented_type;
235    }
236
237    /// Appends an element with value `value` to the tuple.
238    pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) {
239        self.represented_type = None;
240        self.fields.push(value);
241    }
242
243    /// Appends a typed element with value `value` to the tuple.
244    pub fn insert<T: PartialReflect>(&mut self, value: T) {
245        self.represented_type = None;
246        self.insert_boxed(Box::new(value));
247    }
248}
249
250impl Tuple for DynamicTuple {
251    #[inline]
252    fn field(&self, index: usize) -> Option<&dyn PartialReflect> {
253        self.fields.get(index).map(|field| &**field)
254    }
255
256    #[inline]
257    fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
258        self.fields.get_mut(index).map(|field| &mut **field)
259    }
260
261    #[inline]
262    fn field_len(&self) -> usize {
263        self.fields.len()
264    }
265
266    #[inline]
267    fn iter_fields(&self) -> TupleFieldIter<'_> {
268        TupleFieldIter {
269            tuple: self,
270            index: 0,
271        }
272    }
273
274    #[inline]
275    fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>> {
276        self.fields
277    }
278}
279
280impl PartialReflect for DynamicTuple {
281    #[inline]
282    fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
283        self.represented_type
284    }
285
286    #[inline]
287    fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
288        self
289    }
290
291    fn as_partial_reflect(&self) -> &dyn PartialReflect {
292        self
293    }
294
295    fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
296        self
297    }
298
299    fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
300        Err(self)
301    }
302
303    fn try_as_reflect(&self) -> Option<&dyn Reflect> {
304        None
305    }
306
307    fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
308        None
309    }
310
311    fn apply(&mut self, value: &dyn PartialReflect) {
312        tuple_apply(self, value);
313    }
314
315    #[inline]
316    fn reflect_kind(&self) -> ReflectKind {
317        ReflectKind::Tuple
318    }
319
320    #[inline]
321    fn reflect_ref(&self) -> ReflectRef<'_> {
322        ReflectRef::Tuple(self)
323    }
324
325    #[inline]
326    fn reflect_mut(&mut self) -> ReflectMut<'_> {
327        ReflectMut::Tuple(self)
328    }
329
330    #[inline]
331    fn reflect_owned(self: Box<Self>) -> ReflectOwned {
332        ReflectOwned::Tuple(self)
333    }
334
335    fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
336        tuple_try_apply(self, value)
337    }
338
339    fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
340        tuple_partial_eq(self, value)
341    }
342
343    fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
344        write!(f, "DynamicTuple(")?;
345        tuple_debug(self, f)?;
346        write!(f, ")")
347    }
348
349    #[inline]
350    fn is_dynamic(&self) -> bool {
351        true
352    }
353}
354
355impl_type_path!((in bevy_reflect) DynamicTuple);
356
357impl FromIterator<Box<dyn PartialReflect>> for DynamicTuple {
358    fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(fields: I) -> Self {
359        Self {
360            represented_type: None,
361            fields: fields.into_iter().collect(),
362        }
363    }
364}
365
366impl IntoIterator for DynamicTuple {
367    type Item = Box<dyn PartialReflect>;
368    type IntoIter = vec::IntoIter<Self::Item>;
369
370    fn into_iter(self) -> Self::IntoIter {
371        self.fields.into_iter()
372    }
373}
374
375impl<'a> IntoIterator for &'a DynamicTuple {
376    type Item = &'a dyn PartialReflect;
377    type IntoIter = TupleFieldIter<'a>;
378
379    fn into_iter(self) -> Self::IntoIter {
380        self.iter_fields()
381    }
382}
383
384/// Applies the elements of `b` to the corresponding elements of `a`.
385///
386/// # Panics
387///
388/// This function panics if `b` is not a tuple.
389#[inline]
390pub fn tuple_apply<T: Tuple>(a: &mut T, b: &dyn PartialReflect) {
391    if let Err(err) = tuple_try_apply(a, b) {
392        panic!("{err}");
393    }
394}
395
396/// Tries to apply the elements of `b` to the corresponding elements of `a` and
397/// returns a Result.
398///
399/// # Errors
400///
401/// This function returns an [`ApplyError::MismatchedKinds`] if `b` is not a tuple or if
402/// applying elements to each other fails.
403#[inline]
404pub fn tuple_try_apply<T: Tuple>(a: &mut T, b: &dyn PartialReflect) -> Result<(), ApplyError> {
405    let tuple = b.reflect_ref().as_tuple()?;
406
407    for (i, value) in tuple.iter_fields().enumerate() {
408        if let Some(v) = a.field_mut(i) {
409            v.try_apply(value)?;
410        }
411    }
412
413    Ok(())
414}
415
416/// Compares a [`Tuple`] with a [`PartialReflect`] value.
417///
418/// Returns true if and only if all of the following are true:
419/// - `b` is a tuple;
420/// - `b` has the same number of elements as `a`;
421/// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise elements of `a` and `b`.
422///
423/// Returns [`None`] if the comparison couldn't even be performed.
424#[inline]
425pub fn tuple_partial_eq<T: Tuple + ?Sized>(a: &T, b: &dyn PartialReflect) -> Option<bool> {
426    let ReflectRef::Tuple(b) = b.reflect_ref() else {
427        return Some(false);
428    };
429
430    if a.field_len() != b.field_len() {
431        return Some(false);
432    }
433
434    for (a_field, b_field) in a.iter_fields().zip(b.iter_fields()) {
435        let eq_result = a_field.reflect_partial_eq(b_field);
436        if let failed @ (Some(false) | None) = eq_result {
437            return failed;
438        }
439    }
440
441    Some(true)
442}
443
444/// The default debug formatter for [`Tuple`] types.
445///
446/// # Example
447/// ```
448/// use bevy_reflect::Reflect;
449///
450/// let my_tuple: &dyn Reflect = &(1, 2, 3);
451/// println!("{:#?}", my_tuple);
452///
453/// // Output:
454///
455/// // (
456/// //   1,
457/// //   2,
458/// //   3,
459/// // )
460/// ```
461#[inline]
462pub fn tuple_debug(dyn_tuple: &dyn Tuple, f: &mut Formatter<'_>) -> core::fmt::Result {
463    let mut debug = f.debug_tuple("");
464    for field in dyn_tuple.iter_fields() {
465        debug.field(&field as &dyn Debug);
466    }
467    debug.finish()
468}
469
470macro_rules! impl_reflect_tuple {
471    {$($index:tt : $name:tt),*} => {
472        impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> Tuple for ($($name,)*) {
473            #[inline]
474            fn field(&self, index: usize) -> Option<&dyn PartialReflect> {
475                match index {
476                    $($index => Some(&self.$index as &dyn PartialReflect),)*
477                    _ => None,
478                }
479            }
480
481            #[inline]
482            fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
483                match index {
484                    $($index => Some(&mut self.$index as &mut dyn PartialReflect),)*
485                    _ => None,
486                }
487            }
488
489            #[inline]
490            fn field_len(&self) -> usize {
491                let indices: &[usize] = &[$($index as usize),*];
492                indices.len()
493            }
494
495            #[inline]
496            fn iter_fields(&self) -> TupleFieldIter<'_> {
497                TupleFieldIter {
498                    tuple: self,
499                    index: 0,
500                }
501            }
502
503            #[inline]
504            fn drain(self: Box<Self>) -> Vec<Box<dyn PartialReflect>> {
505                vec![
506                    $(Box::new(self.$index),)*
507                ]
508            }
509        }
510
511        impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> PartialReflect for ($($name,)*) {
512            fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
513                Some(<Self as Typed>::type_info())
514            }
515
516            #[inline]
517            fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
518                self
519            }
520
521            fn as_partial_reflect(&self) -> &dyn PartialReflect {
522                self
523            }
524
525            fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
526                self
527            }
528
529            fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
530                Ok(self)
531            }
532
533            fn try_as_reflect(&self) -> Option<&dyn Reflect> {
534                Some(self)
535            }
536
537            fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
538                Some(self)
539            }
540
541            fn reflect_kind(&self) -> ReflectKind {
542                ReflectKind::Tuple
543            }
544
545            fn reflect_ref(&self) -> ReflectRef <'_> {
546                ReflectRef::Tuple(self)
547            }
548
549            fn reflect_mut(&mut self) -> ReflectMut <'_> {
550                ReflectMut::Tuple(self)
551            }
552
553            fn reflect_owned(self: Box<Self>) -> ReflectOwned {
554                ReflectOwned::Tuple(self)
555            }
556
557            fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
558                crate::tuple_partial_eq(self, value)
559            }
560
561            fn apply(&mut self, value: &dyn PartialReflect) {
562                crate::tuple_apply(self, value);
563            }
564
565            fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
566                crate::tuple_try_apply(self, value)
567            }
568
569            fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError> {
570                Ok(Box::new((
571                    $(
572                        self.$index.reflect_clone()?
573                            .take::<$name>()
574                            .expect("`Reflect::reflect_clone` should return the same type"),
575                    )*
576                )))
577            }
578        }
579
580        impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> Reflect for ($($name,)*) {
581            fn into_any(self: Box<Self>) -> Box<dyn Any> {
582                self
583            }
584
585            fn as_any(&self) -> &dyn Any {
586                self
587            }
588
589            fn as_any_mut(&mut self) -> &mut dyn Any {
590                self
591            }
592
593            fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
594                self
595            }
596
597            fn as_reflect(&self) -> &dyn Reflect {
598                self
599            }
600
601            fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
602                self
603            }
604
605            fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
606                *self = value.take()?;
607                Ok(())
608            }
609        }
610
611        impl <$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> Typed for ($($name,)*) {
612            fn type_info() -> &'static TypeInfo {
613                static CELL: $crate::utility::GenericTypeInfoCell = $crate::utility::GenericTypeInfoCell::new();
614                CELL.get_or_insert::<Self, _>(|| {
615                    let fields = [
616                        $(UnnamedField::new::<$name>($index),)*
617                    ];
618                    let info = TupleInfo::new::<Self>(&fields);
619                    TypeInfo::Tuple(info)
620                })
621            }
622        }
623
624        impl<$($name: Reflect + MaybeTyped + TypePath + GetTypeRegistration),*> GetTypeRegistration for ($($name,)*) {
625            fn get_type_registration() -> TypeRegistration {
626                TypeRegistration::of::<($($name,)*)>()
627            }
628
629            fn register_type_dependencies(_registry: &mut TypeRegistry) {
630                $(_registry.register::<$name>();)*
631            }
632        }
633
634        impl<$($name: FromReflect + MaybeTyped + TypePath + GetTypeRegistration),*> FromReflect for ($($name,)*)
635        {
636            fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
637                let _ref_tuple = reflect.reflect_ref().as_tuple().ok()?;
638
639                Some(
640                    (
641                        $(
642                            <$name as FromReflect>::from_reflect(_ref_tuple.field($index)?)?,
643                        )*
644                    )
645                )
646            }
647        }
648    }
649}
650
651impl_reflect_tuple! {}
652
653impl_reflect_tuple! {0: A}
654
655impl_reflect_tuple! {0: A, 1: B}
656
657impl_reflect_tuple! {0: A, 1: B, 2: C}
658
659impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D}
660
661impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E}
662
663impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F}
664
665impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G}
666
667impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H}
668
669impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I}
670
671impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J}
672
673impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K}
674
675impl_reflect_tuple! {0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H, 8: I, 9: J, 10: K, 11: L}
676
677macro_rules! impl_type_path_tuple {
678    ($(#[$meta:meta])*) => {
679        $(#[$meta])*
680        impl TypePath for () {
681            fn type_path() -> &'static str {
682                "()"
683            }
684
685            fn short_type_path() -> &'static str {
686                "()"
687            }
688        }
689    };
690
691    ($(#[$meta:meta])* $param:ident) => {
692        $(#[$meta])*
693        impl <$param: TypePath> TypePath for ($param,) {
694            fn type_path() -> &'static str {
695                use $crate::__macro_exports::alloc_utils::ToOwned;
696                static CELL: GenericTypePathCell = GenericTypePathCell::new();
697                CELL.get_or_insert::<Self, _>(|| {
698                    "(".to_owned() + $param::type_path() + ",)"
699                })
700            }
701
702            fn short_type_path() -> &'static str {
703                use $crate::__macro_exports::alloc_utils::ToOwned;
704                static CELL: GenericTypePathCell = GenericTypePathCell::new();
705                CELL.get_or_insert::<Self, _>(|| {
706                    "(".to_owned() + $param::short_type_path() + ",)"
707                })
708            }
709        }
710    };
711
712    ($(#[$meta:meta])* $last:ident $(,$param:ident)*) => {
713        $(#[$meta])*
714        impl <$($param: TypePath,)* $last: TypePath> TypePath for ($($param,)* $last) {
715            fn type_path() -> &'static str {
716                use $crate::__macro_exports::alloc_utils::ToOwned;
717                static CELL: GenericTypePathCell = GenericTypePathCell::new();
718                CELL.get_or_insert::<Self, _>(|| {
719                    "(".to_owned() $(+ $param::type_path() + ", ")* + $last::type_path() + ")"
720                })
721            }
722
723            fn short_type_path() -> &'static str {
724                use $crate::__macro_exports::alloc_utils::ToOwned;
725                static CELL: GenericTypePathCell = GenericTypePathCell::new();
726                CELL.get_or_insert::<Self, _>(|| {
727                    "(".to_owned() $(+ $param::short_type_path() + ", ")* + $last::short_type_path() + ")"
728                })
729            }
730        }
731    };
732}
733
734all_tuples!(
735    #[doc(fake_variadic)]
736    impl_type_path_tuple,
737    0,
738    12,
739    P
740);
741
742#[cfg(feature = "functions")]
743const _: () = {
744    macro_rules! impl_get_ownership_tuple {
745    ($(#[$meta:meta])* $($name: ident),*) => {
746        $(#[$meta])*
747        $crate::func::args::impl_get_ownership!(($($name,)*); <$($name),*>);
748    };
749}
750
751    all_tuples!(
752        #[doc(fake_variadic)]
753        impl_get_ownership_tuple,
754        0,
755        12,
756        P
757    );
758
759    macro_rules! impl_from_arg_tuple {
760    ($(#[$meta:meta])* $($name: ident),*) => {
761        $(#[$meta])*
762        $crate::func::args::impl_from_arg!(($($name,)*); <$($name: FromReflect + MaybeTyped + TypePath + GetTypeRegistration),*>);
763    };
764}
765
766    all_tuples!(
767        #[doc(fake_variadic)]
768        impl_from_arg_tuple,
769        0,
770        12,
771        P
772    );
773
774    macro_rules! impl_into_return_tuple {
775    ($(#[$meta:meta])* $($name: ident),+) => {
776        $(#[$meta])*
777        $crate::func::impl_into_return!(($($name,)*); <$($name: FromReflect + MaybeTyped + TypePath + GetTypeRegistration),*>);
778    };
779}
780
781    // The unit type (i.e. `()`) is special-cased, so we skip implementing it here.
782    all_tuples!(
783        #[doc(fake_variadic)]
784        impl_into_return_tuple,
785        1,
786        12,
787        P
788    );
789};
790
791#[cfg(test)]
792mod tests {
793    use super::Tuple;
794
795    #[test]
796    fn next_index_increment() {
797        let mut iter = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields();
798        let size = iter.len();
799        iter.index = size - 1;
800        let prev_index = iter.index;
801        assert!(iter.next().is_some());
802        assert_eq!(prev_index, iter.index - 1);
803
804        // When None we should no longer increase index
805        assert!(iter.next().is_none());
806        assert_eq!(size, iter.index);
807        assert!(iter.next().is_none());
808        assert_eq!(size, iter.index);
809    }
810}