Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/src/structs.rs
9308 views
1
//! Traits and types used to power [struct-like] operations via reflection.
2
//!
3
//! [struct-like]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html
4
use crate::generics::impl_generic_info_methods;
5
use crate::{
6
attributes::{impl_custom_attribute_methods, CustomAttributes},
7
type_info::impl_type_methods,
8
ApplyError, Generics, NamedField, PartialReflect, Reflect, ReflectKind, ReflectMut,
9
ReflectOwned, ReflectRef, Type, TypeInfo, TypePath,
10
};
11
use alloc::{borrow::Cow, boxed::Box, vec::Vec};
12
use bevy_platform::collections::HashMap;
13
use bevy_platform::sync::Arc;
14
use bevy_reflect_derive::impl_type_path;
15
use core::{
16
fmt::{Debug, Formatter},
17
slice::Iter,
18
};
19
20
/// A trait used to power [struct-like] operations via [reflection].
21
///
22
/// This trait uses the [`Reflect`] trait to allow implementors to have their fields
23
/// be dynamically addressed by both name and index.
24
///
25
/// When using [`#[derive(Reflect)]`](derive@crate::Reflect) on a standard struct,
26
/// this trait will be automatically implemented.
27
/// This goes for [unit structs] as well.
28
///
29
/// # Example
30
///
31
/// ```
32
/// use bevy_reflect::{PartialReflect, Reflect, structs::Struct};
33
///
34
/// #[derive(Reflect)]
35
/// struct Foo {
36
/// bar: u32,
37
/// }
38
///
39
/// let foo = Foo { bar: 123 };
40
///
41
/// assert_eq!(foo.field_len(), 1);
42
/// assert_eq!(foo.name_at(0), Some("bar"));
43
///
44
/// let field: &dyn PartialReflect = foo.field("bar").unwrap();
45
/// assert_eq!(field.try_downcast_ref::<u32>(), Some(&123));
46
/// ```
47
///
48
/// [struct-like]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html
49
/// [reflection]: crate
50
/// [unit structs]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#unit-like-structs-without-any-fields
51
pub trait Struct: PartialReflect {
52
/// Returns a reference to the value of the field named `name` as a `&dyn
53
/// PartialReflect`.
54
fn field(&self, name: &str) -> Option<&dyn PartialReflect>;
55
56
/// Returns a mutable reference to the value of the field named `name` as a
57
/// `&mut dyn PartialReflect`.
58
fn field_mut(&mut self, name: &str) -> Option<&mut dyn PartialReflect>;
59
60
/// Returns a reference to the value of the field with index `index` as a
61
/// `&dyn PartialReflect`.
62
fn field_at(&self, index: usize) -> Option<&dyn PartialReflect>;
63
64
/// Returns a mutable reference to the value of the field with index `index`
65
/// as a `&mut dyn PartialReflect`.
66
fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect>;
67
68
/// Returns the name of the field with index `index`.
69
fn name_at(&self, index: usize) -> Option<&str>;
70
71
/// Returns the number of fields in the struct.
72
fn field_len(&self) -> usize;
73
74
/// Returns an iterator over the values of the reflectable fields for this struct.
75
fn iter_fields(&self) -> FieldIter<'_>;
76
77
/// Creates a new [`DynamicStruct`] from this struct.
78
fn to_dynamic_struct(&self) -> DynamicStruct {
79
let mut dynamic_struct = DynamicStruct::default();
80
dynamic_struct.set_represented_type(self.get_represented_type_info());
81
for (i, value) in self.iter_fields().enumerate() {
82
dynamic_struct.insert_boxed(self.name_at(i).unwrap(), value.to_dynamic());
83
}
84
dynamic_struct
85
}
86
87
/// Will return `None` if [`TypeInfo`] is not available.
88
fn get_represented_struct_info(&self) -> Option<&'static StructInfo> {
89
self.get_represented_type_info()?.as_struct().ok()
90
}
91
}
92
93
/// A container for compile-time named struct info.
94
#[derive(Clone, Debug)]
95
pub struct StructInfo {
96
ty: Type,
97
generics: Generics,
98
fields: Box<[NamedField]>,
99
field_names: Box<[&'static str]>,
100
field_indices: HashMap<&'static str, usize>,
101
custom_attributes: Arc<CustomAttributes>,
102
#[cfg(feature = "reflect_documentation")]
103
docs: Option<&'static str>,
104
}
105
106
impl StructInfo {
107
/// Create a new [`StructInfo`].
108
///
109
/// # Arguments
110
///
111
/// * `fields`: The fields of this struct in the order they are defined
112
pub fn new<T: Reflect + TypePath>(fields: &[NamedField]) -> Self {
113
let field_indices = fields
114
.iter()
115
.enumerate()
116
.map(|(index, field)| (field.name(), index))
117
.collect::<HashMap<_, _>>();
118
119
let field_names = fields.iter().map(NamedField::name).collect();
120
121
Self {
122
ty: Type::of::<T>(),
123
generics: Generics::new(),
124
fields: fields.to_vec().into_boxed_slice(),
125
field_names,
126
field_indices,
127
custom_attributes: Arc::new(CustomAttributes::default()),
128
#[cfg(feature = "reflect_documentation")]
129
docs: None,
130
}
131
}
132
133
/// Sets the docstring for this struct.
134
#[cfg(feature = "reflect_documentation")]
135
pub fn with_docs(self, docs: Option<&'static str>) -> Self {
136
Self { docs, ..self }
137
}
138
139
/// Sets the custom attributes for this struct.
140
pub fn with_custom_attributes(self, custom_attributes: CustomAttributes) -> Self {
141
Self {
142
custom_attributes: Arc::new(custom_attributes),
143
..self
144
}
145
}
146
147
/// A slice containing the names of all fields in order.
148
pub fn field_names(&self) -> &[&'static str] {
149
&self.field_names
150
}
151
152
/// Get the field with the given name.
153
pub fn field(&self, name: &str) -> Option<&NamedField> {
154
self.field_indices
155
.get(name)
156
.map(|index| &self.fields[*index])
157
}
158
159
/// Get the field at the given index.
160
pub fn field_at(&self, index: usize) -> Option<&NamedField> {
161
self.fields.get(index)
162
}
163
164
/// Get the index of the field with the given name.
165
pub fn index_of(&self, name: &str) -> Option<usize> {
166
self.field_indices.get(name).copied()
167
}
168
169
/// Iterate over the fields of this struct.
170
pub fn iter(&self) -> Iter<'_, NamedField> {
171
self.fields.iter()
172
}
173
174
/// The total number of fields in this struct.
175
pub fn field_len(&self) -> usize {
176
self.fields.len()
177
}
178
179
impl_type_methods!(ty);
180
181
/// The docstring of this struct, if any.
182
#[cfg(feature = "reflect_documentation")]
183
pub fn docs(&self) -> Option<&'static str> {
184
self.docs
185
}
186
187
impl_custom_attribute_methods!(self.custom_attributes, "struct");
188
189
impl_generic_info_methods!(generics);
190
}
191
192
/// An iterator over the field values of a struct.
193
pub struct FieldIter<'a> {
194
pub(crate) struct_val: &'a dyn Struct,
195
pub(crate) index: usize,
196
}
197
198
impl<'a> FieldIter<'a> {
199
/// Creates a new [`FieldIter`].
200
pub fn new(value: &'a dyn Struct) -> Self {
201
FieldIter {
202
struct_val: value,
203
index: 0,
204
}
205
}
206
}
207
208
impl<'a> Iterator for FieldIter<'a> {
209
type Item = &'a dyn PartialReflect;
210
211
fn next(&mut self) -> Option<Self::Item> {
212
let value = self.struct_val.field_at(self.index);
213
self.index += value.is_some() as usize;
214
value
215
}
216
217
fn size_hint(&self) -> (usize, Option<usize>) {
218
let size = self.struct_val.field_len();
219
(size, Some(size))
220
}
221
}
222
223
impl<'a> ExactSizeIterator for FieldIter<'a> {}
224
225
/// A convenience trait which combines fetching and downcasting of struct
226
/// fields.
227
///
228
/// # Example
229
///
230
/// ```
231
/// use bevy_reflect::{structs::GetField, Reflect};
232
///
233
/// #[derive(Reflect)]
234
/// struct Foo {
235
/// bar: String,
236
/// }
237
///
238
/// # fn main() {
239
/// let mut foo = Foo { bar: "Hello, world!".to_string() };
240
///
241
/// foo.get_field_mut::<String>("bar").unwrap().truncate(5);
242
/// assert_eq!(foo.get_field::<String>("bar"), Some(&"Hello".to_string()));
243
/// # }
244
/// ```
245
pub trait GetField {
246
/// Returns a reference to the value of the field named `name`, downcast to
247
/// `T`.
248
fn get_field<T: Reflect>(&self, name: &str) -> Option<&T>;
249
250
/// Returns a mutable reference to the value of the field named `name`,
251
/// downcast to `T`.
252
fn get_field_mut<T: Reflect>(&mut self, name: &str) -> Option<&mut T>;
253
}
254
255
impl<S: Struct> GetField for S {
256
fn get_field<T: Reflect>(&self, name: &str) -> Option<&T> {
257
self.field(name)
258
.and_then(|value| value.try_downcast_ref::<T>())
259
}
260
261
fn get_field_mut<T: Reflect>(&mut self, name: &str) -> Option<&mut T> {
262
self.field_mut(name)
263
.and_then(|value| value.try_downcast_mut::<T>())
264
}
265
}
266
267
impl GetField for dyn Struct {
268
fn get_field<T: Reflect>(&self, name: &str) -> Option<&T> {
269
self.field(name)
270
.and_then(|value| value.try_downcast_ref::<T>())
271
}
272
273
fn get_field_mut<T: Reflect>(&mut self, name: &str) -> Option<&mut T> {
274
self.field_mut(name)
275
.and_then(|value| value.try_downcast_mut::<T>())
276
}
277
}
278
279
/// A struct type which allows fields to be added at runtime.
280
#[derive(Default)]
281
pub struct DynamicStruct {
282
represented_type: Option<&'static TypeInfo>,
283
fields: Vec<Box<dyn PartialReflect>>,
284
field_names: Vec<Cow<'static, str>>,
285
field_indices: HashMap<Cow<'static, str>, usize>,
286
}
287
288
impl DynamicStruct {
289
/// Sets the [type] to be represented by this `DynamicStruct`.
290
///
291
/// # Panics
292
///
293
/// Panics if the given [type] is not a [`TypeInfo::Struct`].
294
///
295
/// [type]: TypeInfo
296
pub fn set_represented_type(&mut self, represented_type: Option<&'static TypeInfo>) {
297
if let Some(represented_type) = represented_type {
298
assert!(
299
matches!(represented_type, TypeInfo::Struct(_)),
300
"expected TypeInfo::Struct but received: {represented_type:?}"
301
);
302
}
303
304
self.represented_type = represented_type;
305
}
306
307
/// Inserts a field named `name` with value `value` into the struct.
308
///
309
/// If the field already exists, it is overwritten.
310
pub fn insert_boxed<'a>(
311
&mut self,
312
name: impl Into<Cow<'a, str>>,
313
value: Box<dyn PartialReflect>,
314
) {
315
let name: Cow<str> = name.into();
316
if let Some(index) = self.field_indices.get(&name) {
317
self.fields[*index] = value;
318
} else {
319
self.fields.push(value);
320
self.field_indices
321
.insert(Cow::Owned(name.clone().into_owned()), self.fields.len() - 1);
322
self.field_names.push(Cow::Owned(name.into_owned()));
323
}
324
}
325
326
/// Inserts a field named `name` with the typed value `value` into the struct.
327
///
328
/// If the field already exists, it is overwritten.
329
pub fn insert<'a, T: PartialReflect>(&mut self, name: impl Into<Cow<'a, str>>, value: T) {
330
self.insert_boxed(name, Box::new(value));
331
}
332
333
/// Removes a field at `index`.
334
pub fn remove_at(
335
&mut self,
336
index: usize,
337
) -> Option<(Cow<'static, str>, Box<dyn PartialReflect>)> {
338
let mut i: usize = 0;
339
let mut extract = self.field_names.extract_if(0..self.field_names.len(), |n| {
340
let mut result = false;
341
if i == index {
342
self.field_indices
343
.remove(n)
344
.expect("Invalid name for `field_indices.remove(name)`");
345
result = true;
346
} else if i > index {
347
*self
348
.field_indices
349
.get_mut(n)
350
.expect("Invalid name for `field_indices.get_mut(name)`") -= 1;
351
}
352
i += 1;
353
result
354
});
355
356
let name = extract
357
.nth(0)
358
.expect("Invalid index for `extract.nth(index)`");
359
extract.for_each(drop); // Fully evaluate the rest of the iterator, so we don't short-circuit the extract.
360
361
Some((name, self.fields.remove(index)))
362
}
363
364
/// Removes the first field that satisfies the given predicate, `f`.
365
pub fn remove_if<F>(&mut self, mut f: F) -> Option<(Cow<'static, str>, Box<dyn PartialReflect>)>
366
where
367
F: FnMut((&str, &dyn PartialReflect)) -> bool,
368
{
369
if let Some(index) = self
370
.field_names
371
.iter()
372
.zip(self.fields.iter())
373
.position(|(name, field)| f((name.as_ref(), field.as_ref())))
374
{
375
self.remove_at(index)
376
} else {
377
None
378
}
379
}
380
381
/// Removes a field by `name`.
382
pub fn remove_by_name(
383
&mut self,
384
name: &str,
385
) -> Option<(Cow<'static, str>, Box<dyn PartialReflect>)> {
386
if let Some(index) = self.index_of(name) {
387
self.remove_at(index)
388
} else {
389
None
390
}
391
}
392
393
/// Gets the index of the field with the given name.
394
pub fn index_of(&self, name: &str) -> Option<usize> {
395
self.field_indices.get(name).copied()
396
}
397
}
398
399
impl Struct for DynamicStruct {
400
#[inline]
401
fn field(&self, name: &str) -> Option<&dyn PartialReflect> {
402
self.field_indices
403
.get(name)
404
.map(|index| &*self.fields[*index])
405
}
406
407
#[inline]
408
fn field_mut(&mut self, name: &str) -> Option<&mut dyn PartialReflect> {
409
if let Some(index) = self.field_indices.get(name) {
410
Some(&mut *self.fields[*index])
411
} else {
412
None
413
}
414
}
415
416
#[inline]
417
fn field_at(&self, index: usize) -> Option<&dyn PartialReflect> {
418
self.fields.get(index).map(|value| &**value)
419
}
420
421
#[inline]
422
fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> {
423
self.fields.get_mut(index).map(|value| &mut **value)
424
}
425
426
#[inline]
427
fn name_at(&self, index: usize) -> Option<&str> {
428
self.field_names.get(index).map(AsRef::as_ref)
429
}
430
431
#[inline]
432
fn field_len(&self) -> usize {
433
self.fields.len()
434
}
435
436
#[inline]
437
fn iter_fields(&self) -> FieldIter<'_> {
438
FieldIter {
439
struct_val: self,
440
index: 0,
441
}
442
}
443
}
444
445
impl PartialReflect for DynamicStruct {
446
#[inline]
447
fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
448
self.represented_type
449
}
450
451
#[inline]
452
fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
453
self
454
}
455
456
#[inline]
457
fn as_partial_reflect(&self) -> &dyn PartialReflect {
458
self
459
}
460
461
#[inline]
462
fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
463
self
464
}
465
466
fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
467
Err(self)
468
}
469
fn try_as_reflect(&self) -> Option<&dyn Reflect> {
470
None
471
}
472
fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
473
None
474
}
475
476
fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
477
let struct_value = value.reflect_ref().as_struct()?;
478
479
for (i, value) in struct_value.iter_fields().enumerate() {
480
let name = struct_value.name_at(i).unwrap();
481
if let Some(v) = self.field_mut(name) {
482
v.try_apply(value)?;
483
}
484
}
485
486
Ok(())
487
}
488
489
#[inline]
490
fn reflect_kind(&self) -> ReflectKind {
491
ReflectKind::Struct
492
}
493
494
#[inline]
495
fn reflect_ref(&self) -> ReflectRef<'_> {
496
ReflectRef::Struct(self)
497
}
498
499
#[inline]
500
fn reflect_mut(&mut self) -> ReflectMut<'_> {
501
ReflectMut::Struct(self)
502
}
503
504
#[inline]
505
fn reflect_owned(self: Box<Self>) -> ReflectOwned {
506
ReflectOwned::Struct(self)
507
}
508
509
fn reflect_partial_eq(&self, value: &dyn PartialReflect) -> Option<bool> {
510
struct_partial_eq(self, value)
511
}
512
513
fn reflect_partial_cmp(&self, value: &dyn PartialReflect) -> Option<::core::cmp::Ordering> {
514
struct_partial_cmp(self, value)
515
}
516
517
fn debug(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
518
write!(f, "DynamicStruct(")?;
519
struct_debug(self, f)?;
520
write!(f, ")")
521
}
522
523
#[inline]
524
fn is_dynamic(&self) -> bool {
525
true
526
}
527
}
528
529
impl_type_path!((in bevy_reflect) DynamicStruct);
530
531
impl Debug for DynamicStruct {
532
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
533
self.debug(f)
534
}
535
}
536
537
impl<'a, N> FromIterator<(N, Box<dyn PartialReflect>)> for DynamicStruct
538
where
539
N: Into<Cow<'a, str>>,
540
{
541
/// Create a dynamic struct that doesn't represent a type from the
542
/// field name, field value pairs.
543
fn from_iter<I: IntoIterator<Item = (N, Box<dyn PartialReflect>)>>(fields: I) -> Self {
544
let mut dynamic_struct = Self::default();
545
for (name, value) in fields.into_iter() {
546
dynamic_struct.insert_boxed(name, value);
547
}
548
dynamic_struct
549
}
550
}
551
552
impl IntoIterator for DynamicStruct {
553
type Item = Box<dyn PartialReflect>;
554
type IntoIter = alloc::vec::IntoIter<Self::Item>;
555
556
fn into_iter(self) -> Self::IntoIter {
557
self.fields.into_iter()
558
}
559
}
560
561
impl<'a> IntoIterator for &'a DynamicStruct {
562
type Item = &'a dyn PartialReflect;
563
type IntoIter = FieldIter<'a>;
564
565
fn into_iter(self) -> Self::IntoIter {
566
self.iter_fields()
567
}
568
}
569
570
/// Compares a [`Struct`] with a [`PartialReflect`] value.
571
///
572
/// Returns true if and only if all of the following are true:
573
/// - `b` is a struct;
574
/// - For each field in `a`, `b` contains a field with the same name and
575
/// [`PartialReflect::reflect_partial_eq`] returns `Some(true)` for the two field
576
/// values.
577
///
578
/// Returns [`None`] if the comparison couldn't even be performed.
579
#[inline(never)]
580
pub fn struct_partial_eq(a: &dyn Struct, b: &dyn PartialReflect) -> Option<bool> {
581
let ReflectRef::Struct(struct_value) = b.reflect_ref() else {
582
return Some(false);
583
};
584
585
if a.field_len() != struct_value.field_len() {
586
return Some(false);
587
}
588
589
for (i, value) in struct_value.iter_fields().enumerate() {
590
let name = struct_value.name_at(i).unwrap();
591
if let Some(field_value) = a.field(name) {
592
let eq_result = field_value.reflect_partial_eq(value);
593
if let failed @ (Some(false) | None) = eq_result {
594
return failed;
595
}
596
} else {
597
return Some(false);
598
}
599
}
600
601
Some(true)
602
}
603
604
/// Lexicographically compares two [`Struct`] values and returns their ordering.
605
///
606
/// Returns [`None`] if the comparison couldn't be performed (e.g., kinds mismatch
607
/// or an element comparison returns `None`).
608
#[inline(never)]
609
pub fn struct_partial_cmp(a: &dyn Struct, b: &dyn PartialReflect) -> Option<::core::cmp::Ordering> {
610
let ReflectRef::Struct(struct_value) = b.reflect_ref() else {
611
return None;
612
};
613
614
if a.field_len() != struct_value.field_len() {
615
return None;
616
}
617
618
// Delegate detailed field-name-aware comparison to shared helper
619
partial_cmp_by_field_names(
620
a.field_len(),
621
|i| a.name_at(i),
622
|i| a.field_at(i),
623
|i| struct_value.name_at(i),
624
|i| struct_value.field_at(i),
625
|name| struct_value.field(name),
626
)
627
}
628
629
/// Compare two sets of named fields. `field_len` should be equal.
630
///
631
/// Tries best to:
632
/// 1. when used on concrete types of actually same type, should be compatible
633
/// with derived `PartialOrd` implementations.
634
/// 2. compatible with `reflect_partial_eq`: when `reflect_partial_eq(a, b) = Some(true)`,
635
/// then `partial_cmp(a, b) = Some(Ordering::Equal)`.
636
/// 3. when used on dynamic types, provide a consistent ordering:
637
/// see example `crate::tests:reflect_partial_cmp_struct_named_field_reorder`
638
pub(crate) fn partial_cmp_by_field_names<'a, NA, FA, NB, FB, FBY>(
639
field_len: usize,
640
name_at_a: NA,
641
field_at_a: FA,
642
name_at_b: NB,
643
field_at_b_index: FB,
644
field_b_by_name: FBY,
645
) -> Option<::core::cmp::Ordering>
646
where
647
NA: Fn(usize) -> Option<&'a str>,
648
FA: Fn(usize) -> Option<&'a dyn PartialReflect>,
649
NB: Fn(usize) -> Option<&'a str>,
650
FB: Fn(usize) -> Option<&'a dyn PartialReflect>,
651
FBY: Fn(&str) -> Option<&'a dyn PartialReflect>,
652
{
653
use ::core::cmp::Ordering;
654
655
let mut same_field_order = true;
656
for i in 0..field_len {
657
if name_at_a(i) != name_at_b(i) {
658
same_field_order = false;
659
break;
660
}
661
}
662
663
if same_field_order {
664
for i in 0..field_len {
665
let a_val = field_at_a(i).unwrap();
666
let b_val = field_at_b_index(i).unwrap();
667
match a_val.reflect_partial_cmp(b_val) {
668
None => return None,
669
Some(Ordering::Equal) => continue,
670
Some(ord) => return Some(ord),
671
}
672
}
673
return Some(Ordering::Equal);
674
}
675
676
let mut all_less_equal = true;
677
let mut all_greater_equal = true;
678
let mut all_equal = true;
679
680
for i in 0..field_len {
681
let field_name = name_at_a(i).unwrap();
682
let a_val = field_at_a(i).unwrap();
683
let b_val = field_b_by_name(field_name)?;
684
match a_val.reflect_partial_cmp(b_val) {
685
None => return None,
686
Some(::core::cmp::Ordering::Less) => {
687
all_greater_equal = false;
688
all_equal = false;
689
}
690
Some(::core::cmp::Ordering::Greater) => {
691
all_less_equal = false;
692
all_equal = false;
693
}
694
Some(::core::cmp::Ordering::Equal) => {}
695
}
696
}
697
698
if all_equal {
699
Some(::core::cmp::Ordering::Equal)
700
} else if all_less_equal {
701
Some(::core::cmp::Ordering::Less)
702
} else if all_greater_equal {
703
Some(::core::cmp::Ordering::Greater)
704
} else {
705
None
706
}
707
}
708
709
/// The default debug formatter for [`Struct`] types.
710
///
711
/// # Example
712
/// ```
713
/// use bevy_reflect::Reflect;
714
/// #[derive(Reflect)]
715
/// struct MyStruct {
716
/// foo: usize
717
/// }
718
///
719
/// let my_struct: &dyn Reflect = &MyStruct { foo: 123 };
720
/// println!("{:#?}", my_struct);
721
///
722
/// // Output:
723
///
724
/// // MyStruct {
725
/// // foo: 123,
726
/// // }
727
/// ```
728
#[inline]
729
pub fn struct_debug(dyn_struct: &dyn Struct, f: &mut Formatter<'_>) -> core::fmt::Result {
730
let mut debug = f.debug_struct(
731
dyn_struct
732
.get_represented_type_info()
733
.map(TypeInfo::type_path)
734
.unwrap_or("_"),
735
);
736
for field_index in 0..dyn_struct.field_len() {
737
let field = dyn_struct.field_at(field_index).unwrap();
738
debug.field(
739
dyn_struct.name_at(field_index).unwrap(),
740
&field as &dyn Debug,
741
);
742
}
743
debug.finish()
744
}
745
746
#[cfg(test)]
747
mod tests {
748
use crate::{structs::*, *};
749
use alloc::borrow::ToOwned;
750
#[derive(Reflect, Default)]
751
struct MyStruct {
752
a: (),
753
b: (),
754
c: (),
755
}
756
757
#[test]
758
fn dynamic_struct_remove_at() {
759
let mut my_struct = MyStruct::default().to_dynamic_struct();
760
761
assert_eq!(my_struct.field_len(), 3);
762
763
let field_2 = my_struct
764
.remove_at(1)
765
.expect("Invalid index for `my_struct.remove_at(index)`");
766
767
assert_eq!(my_struct.field_len(), 2);
768
assert_eq!(field_2.0, "b");
769
770
let field_3 = my_struct
771
.remove_at(0)
772
.expect("Invalid index for `my_struct.remove_at(index)`");
773
774
assert_eq!(my_struct.field_len(), 1);
775
assert_eq!(field_3.0, "a");
776
777
let field_1 = my_struct
778
.remove_at(0)
779
.expect("Invalid index for `my_struct.remove_at(index)`");
780
781
assert_eq!(my_struct.field_len(), 0);
782
assert_eq!(field_1.0, "c");
783
}
784
785
#[test]
786
fn dynamic_struct_remove_by_name() {
787
let mut my_struct = MyStruct::default().to_dynamic_struct();
788
789
assert_eq!(my_struct.field_len(), 3);
790
791
let field_3 = my_struct
792
.remove_by_name("b")
793
.expect("Invalid name for `my_struct.remove_by_name(name)`");
794
795
assert_eq!(my_struct.field_len(), 2);
796
assert_eq!(field_3.0, "b");
797
798
let field_2 = my_struct
799
.remove_by_name("c")
800
.expect("Invalid name for `my_struct.remove_by_name(name)`");
801
802
assert_eq!(my_struct.field_len(), 1);
803
assert_eq!(field_2.0, "c");
804
805
let field_1 = my_struct
806
.remove_by_name("a")
807
.expect("Invalid name for `my_struct.remove_by_name(name)`");
808
809
assert_eq!(my_struct.field_len(), 0);
810
assert_eq!(field_1.0, "a");
811
}
812
813
#[test]
814
fn dynamic_struct_remove_if() {
815
let mut my_struct = MyStruct::default().to_dynamic_struct();
816
817
assert_eq!(my_struct.field_len(), 3);
818
819
let field_3_name = "c";
820
let field_3 = my_struct
821
.remove_if(|(name, _field)| name == field_3_name)
822
.expect("No valid name/field found for `my_struct.remove_with(|(name, field)|{})");
823
824
assert_eq!(my_struct.field_len(), 2);
825
assert_eq!(field_3.0, "c");
826
}
827
828
#[test]
829
fn dynamic_struct_remove_combo() {
830
let mut my_struct = MyStruct::default().to_dynamic_struct();
831
832
assert_eq!(my_struct.field_len(), 3);
833
834
let field_2 = my_struct
835
.remove_at(
836
my_struct
837
.index_of("b")
838
.expect("Invalid field for `my_struct.index_of(field)`"),
839
)
840
.expect("Invalid index for `my_struct.remove_at(index)`");
841
842
assert_eq!(my_struct.field_len(), 2);
843
assert_eq!(field_2.0, "b");
844
845
let field_3_name = my_struct
846
.name_at(1)
847
.expect("Invalid field for `my_struct.name_of(field)`")
848
.to_owned();
849
let field_3 = my_struct
850
.remove_by_name(field_3_name.as_ref())
851
.expect("Invalid name for `my_struct.remove_by_name(name)`");
852
853
assert_eq!(my_struct.field_len(), 1);
854
assert_eq!(field_3.0, "c");
855
856
let field_1_name = my_struct
857
.name_at(0)
858
.expect("Invalid name for `my_struct.name_at(name)`")
859
.to_owned();
860
let field_1 = my_struct
861
.remove_if(|(name, _field)| name == field_1_name)
862
.expect("No valid name/field found for `my_struct.remove_with(|(name, field)|{})`");
863
864
assert_eq!(my_struct.field_len(), 0);
865
assert_eq!(field_1.0, "a");
866
}
867
868
#[test]
869
fn next_index_increment() {
870
let my_struct = MyStruct::default();
871
let mut iter = my_struct.iter_fields();
872
iter.index = iter.len() - 1;
873
let prev_index = iter.index;
874
assert!(iter.next().is_some());
875
assert_eq!(prev_index, iter.index - 1);
876
877
// When None we should no longer increase index
878
let prev_index = iter.index;
879
assert!(iter.next().is_none());
880
assert_eq!(prev_index, iter.index);
881
assert!(iter.next().is_none());
882
assert_eq!(prev_index, iter.index);
883
}
884
}
885
886