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 #[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 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 fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo> {
74 self.get_represented_type_info()?.as_tuple_struct().ok()
75 }
76}
77
78#[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 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 #[cfg(feature = "documentation")]
108 pub fn with_docs(self, docs: Option<&'static str>) -> Self {
109 Self { docs, ..self }
110 }
111
112 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 pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {
122 self.fields.get(index)
123 }
124
125 pub fn iter(&self) -> Iter<'_, UnnamedField> {
127 self.fields.iter()
128 }
129
130 pub fn field_len(&self) -> usize {
132 self.fields.len()
133 }
134
135 impl_type_methods!(ty);
136
137 #[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
148pub 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
180pub trait GetTupleStructField {
199 fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;
202
203 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#[derive(Default)]
234pub struct DynamicTupleStruct {
235 represented_type: Option<&'static TypeInfo>,
236 fields: Vec<Box<dyn PartialReflect>>,
237}
238
239impl DynamicTupleStruct {
240 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 pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) {
261 self.fields.push(value);
262 }
263
264 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#[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#[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 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}