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
17pub trait TupleStruct: PartialReflect {
44 fn field(&self, index: usize) -> Option<&dyn PartialReflect>;
47
48 fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
51
52 fn field_len(&self) -> usize;
54
55 fn iter_fields(&self) -> TupleStructFieldIter<'_>;
57
58 fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct {
60 DynamicTupleStruct {
61 represented_type: self.get_represented_type_info(),
62 fields: self.iter_fields().map(PartialReflect::to_dynamic).collect(),
63 }
64 }
65
66 fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo> {
68 self.get_represented_type_info()?.as_tuple_struct().ok()
69 }
70}
71
72#[derive(Clone, Debug)]
74pub struct TupleStructInfo {
75 ty: Type,
76 generics: Generics,
77 fields: Box<[UnnamedField]>,
78 custom_attributes: Arc<CustomAttributes>,
79 #[cfg(feature = "documentation")]
80 docs: Option<&'static str>,
81}
82
83impl TupleStructInfo {
84 pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self {
90 Self {
91 ty: Type::of::<T>(),
92 generics: Generics::new(),
93 fields: fields.to_vec().into_boxed_slice(),
94 custom_attributes: Arc::new(CustomAttributes::default()),
95 #[cfg(feature = "documentation")]
96 docs: None,
97 }
98 }
99
100 #[cfg(feature = "documentation")]
102 pub fn with_docs(self, docs: Option<&'static str>) -> Self {
103 Self { docs, ..self }
104 }
105
106 pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {
108 Self {
109 custom_attributes: Arc::new(custom_attributes),
110 ..self
111 }
112 }
113
114 pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {
116 self.fields.get(index)
117 }
118
119 pub fn iter(&self) -> Iter<'_, UnnamedField> {
121 self.fields.iter()
122 }
123
124 pub fn field_len(&self) -> usize {
126 self.fields.len()
127 }
128
129 impl_type_methods!(ty);
130
131 #[cfg(feature = "documentation")]
133 pub fn docs(&self) -> Option<&'static str> {
134 self.docs
135 }
136
137 impl_custom_attribute_methods!(self.custom_attributes, "struct");
138
139 impl_generic_info_methods!(generics);
140}
141
142pub struct TupleStructFieldIter<'a> {
144 pub(crate) tuple_struct: &'a dyn TupleStruct,
145 pub(crate) index: usize,
146}
147
148impl<'a> TupleStructFieldIter<'a> {
149 pub fn new(value: &'a dyn TupleStruct) -> Self {
151 TupleStructFieldIter {
152 tuple_struct: value,
153 index: 0,
154 }
155 }
156}
157
158impl<'a> Iterator for TupleStructFieldIter<'a> {
159 type Item = &'a dyn PartialReflect;
160
161 fn next(&mut self) -> Option<Self::Item> {
162 let value = self.tuple_struct.field(self.index);
163 self.index += value.is_some() as usize;
164 value
165 }
166
167 fn size_hint(&self) -> (usize, Option<usize>) {
168 let size = self.tuple_struct.field_len();
169 (size, Some(size))
170 }
171}
172
173impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {}
174
175pub trait GetTupleStructField {
194 fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;
197
198 fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>;
201}
202
203impl<S: TupleStruct> GetTupleStructField for S {
204 fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
205 self.field(index)
206 .and_then(|value| value.try_downcast_ref::<T>())
207 }
208
209 fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
210 self.field_mut(index)
211 .and_then(|value| value.try_downcast_mut::<T>())
212 }
213}
214
215impl GetTupleStructField for dyn TupleStruct {
216 fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
217 self.field(index)
218 .and_then(|value| value.try_downcast_ref::<T>())
219 }
220
221 fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
222 self.field_mut(index)
223 .and_then(|value| value.try_downcast_mut::<T>())
224 }
225}
226
227#[derive(Default)]
229pub struct DynamicTupleStruct {
230 represented_type: Option<&'static TypeInfo>,
231 fields: Vec<Box<dyn PartialReflect>>,
232}
233
234impl DynamicTupleStruct {
235 pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
243 if let Some(represented_type) = represented_type {
244 assert!(
245 matches!(represented_type, TypeInfo::TupleStruct(_)),
246 "expected TypeInfo::TupleStruct but received: {represented_type:?}"
247 );
248 }
249
250 self.represented_type = represented_type;
251 }
252
253 pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) {
255 self.fields.push(value);
256 }
257
258 pub fn insert<T: PartialReflect>(&mut self, value: T) {
260 self.insert_boxed(Box::new(value));
261 }
262}
263
264impl TupleStruct for DynamicTupleStruct {
265 #[inline]
266 fn field(&self, index: usize) -> Option<&dyn PartialReflect> {
267 self.fields.get(index).map(|field| &**field)
268 }
269
270 #[inline]
271 fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
272 self.fields.get_mut(index).map(|field| &mut **field)
273 }
274
275 #[inline]
276 fn field_len(&self) -> usize {
277 self.fields.len()
278 }
279
280 #[inline]
281 fn iter_fields(&self) -> TupleStructFieldIter<'_> {
282 TupleStructFieldIter {
283 tuple_struct: self,
284 index: 0,
285 }
286 }
287}
288
289impl PartialReflect for DynamicTupleStruct {
290 #[inline]
291 fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
292 self.represented_type
293 }
294
295 #[inline]
296 fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
297 self
298 }
299
300 #[inline]
301 fn as_partial_reflect(&self) -> &dyn PartialReflect {
302 self
303 }
304
305 #[inline]
306 fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
307 self
308 }
309
310 fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
311 Err(self)
312 }
313
314 fn try_as_reflect(&self) -> Option<&dyn Reflect> {
315 None
316 }
317
318 fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
319 None
320 }
321
322 fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
323 let tuple_struct = value.reflect_ref().as_tuple_struct()?;
324
325 for (i, value) in tuple_struct.iter_fields().enumerate() {
326 if let Some(v) = self.field_mut(i) {
327 v.try_apply(value)?;
328 }
329 }
330
331 Ok(())
332 }
333
334 #[inline]
335 fn reflect_kind(&self) -> ReflectKind {
336 ReflectKind::TupleStruct
337 }
338
339 #[inline]
340 fn reflect_ref(&self) -> ReflectRef<'_> {
341 ReflectRef::TupleStruct(self)
342 }
343
344 #[inline]
345 fn reflect_mut(&mut self) -> ReflectMut<'_> {
346 ReflectMut::TupleStruct(self)
347 }
348
349 #[inline]
350 fn reflect_owned(self: Box<Self>) -> ReflectOwned {
351 ReflectOwned::TupleStruct(self)
352 }
353
354 #[inline]
355 fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
356 tuple_struct_partial_eq(self, value)
357 }
358
359 fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
360 write!(f, "DynamicTupleStruct(")?;
361 tuple_struct_debug(self, f)?;
362 write!(f, ")")
363 }
364
365 #[inline]
366 fn is_dynamic(&self) -> bool {
367 true
368 }
369}
370
371impl_type_path!((in bevy_reflect) DynamicTupleStruct);
372
373impl Debug for DynamicTupleStruct {
374 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
375 self.debug(f)
376 }
377}
378
379impl From<DynamicTuple> for DynamicTupleStruct {
380 fn from(value: DynamicTuple) -> Self {
381 Self {
382 represented_type: None,
383 fields: Box::new(value).drain(),
384 }
385 }
386}
387
388impl FromIterator<Box<dyn PartialReflect>> for DynamicTupleStruct {
389 fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(fields: I) -> Self {
390 Self {
391 represented_type: None,
392 fields: fields.into_iter().collect(),
393 }
394 }
395}
396
397impl IntoIterator for DynamicTupleStruct {
398 type Item = Box<dyn PartialReflect>;
399 type IntoIter = alloc::vec::IntoIter<Self::Item>;
400
401 fn into_iter(self) -> Self::IntoIter {
402 self.fields.into_iter()
403 }
404}
405
406impl<'a> IntoIterator for &'a DynamicTupleStruct {
407 type Item = &'a dyn PartialReflect;
408 type IntoIter = TupleStructFieldIter<'a>;
409
410 fn into_iter(self) -> Self::IntoIter {
411 self.iter_fields()
412 }
413}
414
415#[inline]
424pub fn tuple_struct_partial_eq<S: TupleStruct + ?Sized>(
425 a: &S,
426 b: &dyn PartialReflect,
427) -> Option<bool> {
428 let ReflectRef::TupleStruct(tuple_struct) = b.reflect_ref() else {
429 return Some(false);
430 };
431
432 if a.field_len() != tuple_struct.field_len() {
433 return Some(false);
434 }
435
436 for (i, value) in tuple_struct.iter_fields().enumerate() {
437 if let Some(field_value) = a.field(i) {
438 let eq_result = field_value.reflect_partial_eq(value);
439 if let failed @ (Some(false) | None) = eq_result {
440 return failed;
441 }
442 } else {
443 return Some(false);
444 }
445 }
446
447 Some(true)
448}
449
450#[inline]
468pub fn tuple_struct_debug(
469 dyn_tuple_struct: &dyn TupleStruct,
470 f: &mut Formatter<'_>,
471) -> core::fmt::Result {
472 let mut debug = f.debug_tuple(
473 dyn_tuple_struct
474 .get_represented_type_info()
475 .map(TypeInfo::type_path)
476 .unwrap_or("_"),
477 );
478 for field in dyn_tuple_struct.iter_fields() {
479 debug.field(&field as &dyn Debug);
480 }
481 debug.finish()
482}
483
484#[cfg(test)]
485mod tests {
486 use crate::*;
487 #[derive(Reflect)]
488 struct Ts(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8);
489 #[test]
490 fn next_index_increment() {
491 let mut iter = Ts(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields();
492 let size = iter.len();
493 iter.index = size - 1;
494 let prev_index = iter.index;
495 assert!(iter.next().is_some());
496 assert_eq!(prev_index, iter.index - 1);
497
498 assert!(iter.next().is_none());
500 assert_eq!(size, iter.index);
501 assert!(iter.next().is_none());
502 assert_eq!(size, iter.index);
503 }
504}