1use bevy_reflect_derive::impl_type_path;
5
6use crate::generics::impl_generic_info_methods;
7use crate::{
8 attributes::{impl_custom_attribute_methods, CustomAttributes},
9 tuple::{DynamicTuple, Tuple},
10 type_info::impl_type_methods,
11 ApplyError, Generics, PartialReflect, Reflect, ReflectKind, ReflectMut, ReflectOwned,
12 ReflectRef, Type, TypeInfo, TypePath, UnnamedField,
13};
14use alloc::{boxed::Box, vec::Vec};
15use bevy_platform::sync::Arc;
16use core::{
17 fmt::{Debug, Formatter},
18 slice::Iter,
19};
20
21pub trait TupleStruct: PartialReflect {
48 fn field(&self, index: usize) -> Option<&dyn PartialReflect>;
51
52 fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
55
56 fn field_len(&self) -> usize;
58
59 fn iter_fields(&self) -> TupleStructFieldIter<'_>;
61
62 fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct {
64 DynamicTupleStruct {
65 represented_type: self.get_represented_type_info(),
66 fields: self.iter_fields().map(PartialReflect::to_dynamic).collect(),
67 }
68 }
69
70 fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo> {
72 self.get_represented_type_info()?.as_tuple_struct().ok()
73 }
74}
75
76#[derive(Clone, Debug)]
78pub struct TupleStructInfo {
79 ty: Type,
80 generics: Generics,
81 fields: Box<[UnnamedField]>,
82 custom_attributes: Arc<CustomAttributes>,
83 #[cfg(feature = "reflect_documentation")]
84 docs: Option<&'static str>,
85}
86
87impl TupleStructInfo {
88 pub fn new<T: Reflect + TypePath>(fields: &[UnnamedField]) -> Self {
94 Self {
95 ty: Type::of::<T>(),
96 generics: Generics::new(),
97 fields: fields.to_vec().into_boxed_slice(),
98 custom_attributes: Arc::new(CustomAttributes::default()),
99 #[cfg(feature = "reflect_documentation")]
100 docs: None,
101 }
102 }
103
104 #[cfg(feature = "reflect_documentation")]
106 pub fn with_docs(self, docs: Option<&'static str>) -> Self {
107 Self { docs, ..self }
108 }
109
110 pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {
112 Self {
113 custom_attributes: Arc::new(custom_attributes),
114 ..self
115 }
116 }
117
118 pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {
120 self.fields.get(index)
121 }
122
123 pub fn iter(&self) -> Iter<'_, UnnamedField> {
125 self.fields.iter()
126 }
127
128 pub fn field_len(&self) -> usize {
130 self.fields.len()
131 }
132
133 impl_type_methods!(ty);
134
135 #[cfg(feature = "reflect_documentation")]
137 pub fn docs(&self) -> Option<&'static str> {
138 self.docs
139 }
140
141 impl_custom_attribute_methods!(self.custom_attributes, "struct");
142
143 impl_generic_info_methods!(generics);
144}
145
146pub struct TupleStructFieldIter<'a> {
148 pub(crate) tuple_struct: &'a dyn TupleStruct,
149 pub(crate) index: usize,
150}
151
152impl<'a> TupleStructFieldIter<'a> {
153 pub fn new(value: &'a dyn TupleStruct) -> Self {
155 TupleStructFieldIter {
156 tuple_struct: value,
157 index: 0,
158 }
159 }
160}
161
162impl<'a> Iterator for TupleStructFieldIter<'a> {
163 type Item = &'a dyn PartialReflect;
164
165 fn next(&mut self) -> Option<Self::Item> {
166 let value = self.tuple_struct.field(self.index);
167 self.index += value.is_some() as usize;
168 value
169 }
170
171 fn size_hint(&self) -> (usize, Option<usize>) {
172 let size = self.tuple_struct.field_len();
173 (size, Some(size))
174 }
175}
176
177impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {}
178
179pub trait GetTupleStructField {
198 fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;
201
202 fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>;
205}
206
207impl<S: TupleStruct> GetTupleStructField for S {
208 fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
209 self.field(index)
210 .and_then(|value| value.try_downcast_ref::<T>())
211 }
212
213 fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
214 self.field_mut(index)
215 .and_then(|value| value.try_downcast_mut::<T>())
216 }
217}
218
219impl GetTupleStructField for dyn TupleStruct {
220 fn get_field<T: Reflect>(&self, index: usize) -> Option<&T> {
221 self.field(index)
222 .and_then(|value| value.try_downcast_ref::<T>())
223 }
224
225 fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T> {
226 self.field_mut(index)
227 .and_then(|value| value.try_downcast_mut::<T>())
228 }
229}
230
231#[derive(Default)]
233pub struct DynamicTupleStruct {
234 represented_type: Option<&'static TypeInfo>,
235 fields: Vec<Box<dyn PartialReflect>>,
236}
237
238impl DynamicTupleStruct {
239 pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
247 if let Some(represented_type) = represented_type {
248 assert!(
249 matches!(represented_type, TypeInfo::TupleStruct(_)),
250 "expected TypeInfo::TupleStruct but received: {represented_type:?}"
251 );
252 }
253
254 self.represented_type = represented_type;
255 }
256
257 pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) {
259 self.fields.push(value);
260 }
261
262 pub fn insert<T: PartialReflect>(&mut self, value: T) {
264 self.insert_boxed(Box::new(value));
265 }
266}
267
268impl TupleStruct for DynamicTupleStruct {
269 #[inline]
270 fn field(&self, index: usize) -> Option<&dyn PartialReflect> {
271 self.fields.get(index).map(|field| &**field)
272 }
273
274 #[inline]
275 fn field_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
276 self.fields.get_mut(index).map(|field| &mut **field)
277 }
278
279 #[inline]
280 fn field_len(&self) -> usize {
281 self.fields.len()
282 }
283
284 #[inline]
285 fn iter_fields(&self) -> TupleStructFieldIter<'_> {
286 TupleStructFieldIter {
287 tuple_struct: self,
288 index: 0,
289 }
290 }
291}
292
293impl PartialReflect for DynamicTupleStruct {
294 #[inline]
295 fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
296 self.represented_type
297 }
298
299 #[inline]
300 fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
301 self
302 }
303
304 #[inline]
305 fn as_partial_reflect(&self) -> &dyn PartialReflect {
306 self
307 }
308
309 #[inline]
310 fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
311 self
312 }
313
314 fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
315 Err(self)
316 }
317
318 fn try_as_reflect(&self) -> Option<&dyn Reflect> {
319 None
320 }
321
322 fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
323 None
324 }
325
326 fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
327 let tuple_struct = value.reflect_ref().as_tuple_struct()?;
328
329 for (i, value) in tuple_struct.iter_fields().enumerate() {
330 if let Some(v) = self.field_mut(i) {
331 v.try_apply(value)?;
332 }
333 }
334
335 Ok(())
336 }
337
338 #[inline]
339 fn reflect_kind(&self) -> ReflectKind {
340 ReflectKind::TupleStruct
341 }
342
343 #[inline]
344 fn reflect_ref(&self) -> ReflectRef<'_> {
345 ReflectRef::TupleStruct(self)
346 }
347
348 #[inline]
349 fn reflect_mut(&mut self) -> ReflectMut<'_> {
350 ReflectMut::TupleStruct(self)
351 }
352
353 #[inline]
354 fn reflect_owned(self: Box<Self>) -> ReflectOwned {
355 ReflectOwned::TupleStruct(self)
356 }
357
358 #[inline]
359 fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
360 tuple_struct_partial_eq(self, value)
361 }
362
363 fn reflect_partial_cmp(&self, value: &dyn PartialReflect) -> Option<::core::cmp::Ordering> {
364 tuple_struct_partial_cmp(self, value)
365 }
366
367 fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
368 write!(f, "DynamicTupleStruct(")?;
369 tuple_struct_debug(self, f)?;
370 write!(f, ")")
371 }
372
373 #[inline]
374 fn is_dynamic(&self) -> bool {
375 true
376 }
377}
378
379impl_type_path!((in bevy_reflect) DynamicTupleStruct);
380
381impl Debug for DynamicTupleStruct {
382 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
383 self.debug(f)
384 }
385}
386
387impl From<DynamicTuple> for DynamicTupleStruct {
388 fn from(value: DynamicTuple) -> Self {
389 Self {
390 represented_type: None,
391 fields: Box::new(value).drain(),
392 }
393 }
394}
395
396impl FromIterator<Box<dyn PartialReflect>> for DynamicTupleStruct {
397 fn from_iter<I: IntoIterator<Item = Box<dyn PartialReflect>>>(fields: I) -> Self {
398 Self {
399 represented_type: None,
400 fields: fields.into_iter().collect(),
401 }
402 }
403}
404
405impl IntoIterator for DynamicTupleStruct {
406 type Item = Box<dyn PartialReflect>;
407 type IntoIter = alloc::vec::IntoIter<Self::Item>;
408
409 fn into_iter(self) -> Self::IntoIter {
410 self.fields.into_iter()
411 }
412}
413
414impl<'a> IntoIterator for &'a DynamicTupleStruct {
415 type Item = &'a dyn PartialReflect;
416 type IntoIter = TupleStructFieldIter<'a>;
417
418 fn into_iter(self) -> Self::IntoIter {
419 self.iter_fields()
420 }
421}
422
423#[inline(never)]
432pub fn tuple_struct_partial_eq(a: &dyn TupleStruct, b: &dyn PartialReflect) -> Option<bool> {
433 let ReflectRef::TupleStruct(tuple_struct) = b.reflect_ref() else {
434 return Some(false);
435 };
436
437 if a.field_len() != tuple_struct.field_len() {
438 return Some(false);
439 }
440
441 for (i, value) in tuple_struct.iter_fields().enumerate() {
442 if let Some(field_value) = a.field(i) {
443 let eq_result = field_value.reflect_partial_eq(value);
444 if let failed @ (Some(false) | None) = eq_result {
445 return failed;
446 }
447 } else {
448 return Some(false);
449 }
450 }
451
452 Some(true)
453}
454#[inline(never)]
459pub fn tuple_struct_partial_cmp(
460 a: &dyn TupleStruct,
461 b: &dyn PartialReflect,
462) -> Option<::core::cmp::Ordering> {
463 let ReflectRef::TupleStruct(tuple_struct) = b.reflect_ref() else {
464 return None;
465 };
466
467 if a.field_len() != tuple_struct.field_len() {
468 return None;
469 }
470
471 for (i, value) in tuple_struct.iter_fields().enumerate() {
472 if let Some(field_value) = a.field(i) {
473 match field_value.reflect_partial_cmp(value) {
474 None => return None,
475 Some(core::cmp::Ordering::Equal) => continue,
476 Some(ord) => return Some(ord),
477 }
478 }
479 return None;
480 }
481
482 Some(core::cmp::Ordering::Equal)
483}
484
485#[inline]
503pub fn tuple_struct_debug(
504 dyn_tuple_struct: &dyn TupleStruct,
505 f: &mut Formatter<'_>,
506) -> core::fmt::Result {
507 let mut debug = f.debug_tuple(
508 dyn_tuple_struct
509 .get_represented_type_info()
510 .map(TypeInfo::type_path)
511 .unwrap_or("_"),
512 );
513 for field in dyn_tuple_struct.iter_fields() {
514 debug.field(&field as &dyn Debug);
515 }
516 debug.finish()
517}
518
519#[cfg(test)]
520mod tests {
521 use super::TupleStruct;
522 use crate::Reflect;
523 #[derive(Reflect)]
524 struct Ts(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8);
525 #[test]
526 fn next_index_increment() {
527 let mut iter = Ts(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).iter_fields();
528 let size = iter.len();
529 iter.index = size - 1;
530 let prev_index = iter.index;
531 assert!(iter.next().is_some());
532 assert_eq!(prev_index, iter.index - 1);
533
534 assert!(iter.next().is_none());
536 assert_eq!(size, iter.index);
537 assert!(iter.next().is_none());
538 assert_eq!(size, iter.index);
539 }
540}