Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/src/tuple_struct.rs
6598 views
1
use bevy_reflect_derive::impl_type_path;
2
3
use crate::generics::impl_generic_info_methods;
4
use 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
};
10
use alloc::{boxed::Box, vec::Vec};
11
use bevy_platform::sync::Arc;
12
use 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
43
pub 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
/// Creates a new [`DynamicTupleStruct`] from this tuple struct.
59
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
/// Will return `None` if [`TypeInfo`] is not available.
67
fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo> {
68
self.get_represented_type_info()?.as_tuple_struct().ok()
69
}
70
}
71
72
/// A container for compile-time tuple struct info.
73
#[derive(Clone, Debug)]
74
pub 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
83
impl TupleStructInfo {
84
/// Create a new [`TupleStructInfo`].
85
///
86
/// # Arguments
87
///
88
/// * `fields`: The fields of this struct in the order they are defined
89
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
/// Sets the docstring for this struct.
101
#[cfg(feature = "documentation")]
102
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
103
Self { docs, ..self }
104
}
105
106
/// Sets the custom attributes for this struct.
107
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
/// Get the field at the given index.
115
pub fn field_at(&self, index: usize) -> Option<&UnnamedField> {
116
self.fields.get(index)
117
}
118
119
/// Iterate over the fields of this struct.
120
pub fn iter(&self) -> Iter<'_, UnnamedField> {
121
self.fields.iter()
122
}
123
124
/// The total number of fields in this struct.
125
pub fn field_len(&self) -> usize {
126
self.fields.len()
127
}
128
129
impl_type_methods!(ty);
130
131
/// The docstring of this struct, if any.
132
#[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
142
/// An iterator over the field values of a tuple struct.
143
pub struct TupleStructFieldIter<'a> {
144
pub(crate) tuple_struct: &'a dyn TupleStruct,
145
pub(crate) index: usize,
146
}
147
148
impl<'a> TupleStructFieldIter<'a> {
149
/// Creates a new [`TupleStructFieldIter`].
150
pub fn new(value: &'a dyn TupleStruct) -> Self {
151
TupleStructFieldIter {
152
tuple_struct: value,
153
index: 0,
154
}
155
}
156
}
157
158
impl<'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
173
impl<'a> ExactSizeIterator for TupleStructFieldIter<'a> {}
174
175
/// A convenience trait which combines fetching and downcasting of tuple
176
/// struct fields.
177
///
178
/// # Example
179
///
180
/// ```
181
/// use bevy_reflect::{GetTupleStructField, Reflect};
182
///
183
/// #[derive(Reflect)]
184
/// struct Foo(String);
185
///
186
/// # fn main() {
187
/// let mut foo = Foo("Hello, world!".to_string());
188
///
189
/// foo.get_field_mut::<String>(0).unwrap().truncate(5);
190
/// assert_eq!(foo.get_field::<String>(0), Some(&"Hello".to_string()));
191
/// # }
192
/// ```
193
pub trait GetTupleStructField {
194
/// Returns a reference to the value of the field with index `index`,
195
/// downcast to `T`.
196
fn get_field<T: Reflect>(&self, index: usize) -> Option<&T>;
197
198
/// Returns a mutable reference to the value of the field with index
199
/// `index`, downcast to `T`.
200
fn get_field_mut<T: Reflect>(&mut self, index: usize) -> Option<&mut T>;
201
}
202
203
impl<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
215
impl 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
/// A tuple struct which allows fields to be added at runtime.
228
#[derive(Default)]
229
pub struct DynamicTupleStruct {
230
represented_type: Option<&'static TypeInfo>,
231
fields: Vec<Box<dyn PartialReflect>>,
232
}
233
234
impl DynamicTupleStruct {
235
/// Sets the [type] to be represented by this `DynamicTupleStruct`.
236
///
237
/// # Panics
238
///
239
/// Panics if the given [type] is not a [`TypeInfo::TupleStruct`].
240
///
241
/// [type]: TypeInfo
242
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
/// Appends an element with value `value` to the tuple struct.
254
pub fn insert_boxed(&mut self, value: Box<dyn PartialReflect>) {
255
self.fields.push(value);
256
}
257
258
/// Appends a typed element with value `value` to the tuple struct.
259
pub fn insert<T: PartialReflect>(&mut self, value: T) {
260
self.insert_boxed(Box::new(value));
261
}
262
}
263
264
impl 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
289
impl 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
371
impl_type_path!((in bevy_reflect) DynamicTupleStruct);
372
373
impl Debug for DynamicTupleStruct {
374
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
375
self.debug(f)
376
}
377
}
378
379
impl 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
388
impl 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
397
impl 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
406
impl<'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
/// Compares a [`TupleStruct`] with a [`PartialReflect`] value.
416
///
417
/// Returns true if and only if all of the following are true:
418
/// - `b` is a tuple struct;
419
/// - `b` has the same number of fields as `a`;
420
/// - [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for pairwise fields of `a` and `b`.
421
///
422
/// Returns [`None`] if the comparison couldn't even be performed.
423
#[inline]
424
pub 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
/// The default debug formatter for [`TupleStruct`] types.
451
///
452
/// # Example
453
/// ```
454
/// use bevy_reflect::Reflect;
455
/// #[derive(Reflect)]
456
/// struct MyTupleStruct(usize);
457
///
458
/// let my_tuple_struct: &dyn Reflect = &MyTupleStruct(123);
459
/// println!("{:#?}", my_tuple_struct);
460
///
461
/// // Output:
462
///
463
/// // MyTupleStruct (
464
/// // 123,
465
/// // )
466
/// ```
467
#[inline]
468
pub 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)]
485
mod 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
// When None we should no longer increase index
499
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
}
505
506