1use crate::{
2 Array, Enum, List, Map, Reflect, ReflectRef, ReflectSerialize, Struct, Tuple, TupleStruct,
3 TypeInfo, TypeRegistry, VariantInfo, VariantType,
4};
5use serde::ser::{
6 Error, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct,
7 SerializeTupleVariant,
8};
9use serde::{
10 ser::{SerializeMap, SerializeSeq},
11 Serialize,
12};
13
14use super::SerializationData;
15
16pub enum Serializable<'a> {
17 Owned(Box<dyn erased_serde::Serialize + 'a>),
18 Borrowed(&'a dyn erased_serde::Serialize),
19}
20
21impl<'a> Serializable<'a> {
22 #[allow(clippy::should_implement_trait)]
23 pub fn borrow(&self) -> &dyn erased_serde::Serialize {
24 match self {
25 Serializable::Borrowed(serialize) => serialize,
26 Serializable::Owned(serialize) => serialize,
27 }
28 }
29}
30
31fn get_serializable<'a, E: Error>(
32 reflect_value: &'a dyn Reflect,
33 type_registry: &TypeRegistry,
34) -> Result<Serializable<'a>, E> {
35 let info = reflect_value.get_represented_type_info().ok_or_else(|| {
36 Error::custom(format_args!(
37 "Type '{}' does not represent any type",
38 reflect_value.reflect_type_path(),
39 ))
40 })?;
41
42 let reflect_serialize = type_registry
43 .get_type_data::<ReflectSerialize>(info.type_id())
44 .ok_or_else(|| {
45 Error::custom(format_args!(
46 "Type '{}' did not register ReflectSerialize",
47 info.type_path(),
48 ))
49 })?;
50 Ok(reflect_serialize.get_serializable(reflect_value))
51}
52
53pub struct ReflectSerializer<'a> {
90 pub value: &'a dyn Reflect,
91 pub registry: &'a TypeRegistry,
92}
93
94impl<'a> ReflectSerializer<'a> {
95 pub fn new(value: &'a dyn Reflect, registry: &'a TypeRegistry) -> Self {
96 ReflectSerializer { value, registry }
97 }
98}
99
100impl<'a> Serialize for ReflectSerializer<'a> {
101 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
102 where
103 S: serde::Serializer,
104 {
105 let mut state = serializer.serialize_map(Some(1))?;
106 state.serialize_entry(
107 self.value
108 .get_represented_type_info()
109 .ok_or_else(|| {
110 if self.value.is_dynamic() {
111 Error::custom(format_args!(
112 "cannot serialize dynamic value without represented type: {}",
113 self.value.reflect_type_path()
114 ))
115 } else {
116 Error::custom(format_args!(
117 "cannot get type info for {}",
118 self.value.reflect_type_path()
119 ))
120 }
121 })?
122 .type_path(),
123 &TypedReflectSerializer::new(self.value, self.registry),
124 )?;
125 state.end()
126 }
127}
128
129pub struct TypedReflectSerializer<'a> {
168 pub value: &'a dyn Reflect,
169 pub registry: &'a TypeRegistry,
170}
171
172impl<'a> TypedReflectSerializer<'a> {
173 pub fn new(value: &'a dyn Reflect, registry: &'a TypeRegistry) -> Self {
174 TypedReflectSerializer { value, registry }
175 }
176}
177
178impl<'a> Serialize for TypedReflectSerializer<'a> {
179 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
180 where
181 S: serde::Serializer,
182 {
183 let serializable = get_serializable::<S::Error>(self.value, self.registry);
185 if let Ok(serializable) = serializable {
186 return serializable.borrow().serialize(serializer);
187 }
188
189 match self.value.reflect_ref() {
190 ReflectRef::Struct(value) => StructSerializer {
191 struct_value: value,
192 registry: self.registry,
193 }
194 .serialize(serializer),
195 ReflectRef::TupleStruct(value) => TupleStructSerializer {
196 tuple_struct: value,
197 registry: self.registry,
198 }
199 .serialize(serializer),
200 ReflectRef::Tuple(value) => TupleSerializer {
201 tuple: value,
202 registry: self.registry,
203 }
204 .serialize(serializer),
205 ReflectRef::List(value) => ListSerializer {
206 list: value,
207 registry: self.registry,
208 }
209 .serialize(serializer),
210 ReflectRef::Array(value) => ArraySerializer {
211 array: value,
212 registry: self.registry,
213 }
214 .serialize(serializer),
215 ReflectRef::Map(value) => MapSerializer {
216 map: value,
217 registry: self.registry,
218 }
219 .serialize(serializer),
220 ReflectRef::Enum(value) => EnumSerializer {
221 enum_value: value,
222 registry: self.registry,
223 }
224 .serialize(serializer),
225 ReflectRef::Value(_) => Err(serializable.err().unwrap()),
226 }
227 }
228}
229
230pub struct ReflectValueSerializer<'a> {
231 pub registry: &'a TypeRegistry,
232 pub value: &'a dyn Reflect,
233}
234
235impl<'a> Serialize for ReflectValueSerializer<'a> {
236 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
237 where
238 S: serde::Serializer,
239 {
240 get_serializable::<S::Error>(self.value, self.registry)?
241 .borrow()
242 .serialize(serializer)
243 }
244}
245
246pub struct StructSerializer<'a> {
247 pub struct_value: &'a dyn Struct,
248 pub registry: &'a TypeRegistry,
249}
250
251impl<'a> Serialize for StructSerializer<'a> {
252 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
253 where
254 S: serde::Serializer,
255 {
256 let type_info = self
257 .struct_value
258 .get_represented_type_info()
259 .ok_or_else(|| {
260 Error::custom(format_args!(
261 "cannot get type info for {}",
262 self.struct_value.reflect_type_path()
263 ))
264 })?;
265
266 let struct_info = match type_info {
267 TypeInfo::Struct(struct_info) => struct_info,
268 info => {
269 return Err(Error::custom(format_args!(
270 "expected struct type but received {info:?}"
271 )));
272 }
273 };
274
275 let serialization_data = self
276 .registry
277 .get(type_info.type_id())
278 .and_then(|registration| registration.data::<SerializationData>());
279 let ignored_len = serialization_data.map(|data| data.len()).unwrap_or(0);
280 let mut state = serializer.serialize_struct(
281 struct_info.type_path_table().ident().unwrap(),
282 self.struct_value.field_len() - ignored_len,
283 )?;
284
285 for (index, value) in self.struct_value.iter_fields().enumerate() {
286 if serialization_data
287 .map(|data| data.is_field_skipped(index))
288 .unwrap_or(false)
289 {
290 continue;
291 }
292 let key = struct_info.field_at(index).unwrap().name();
293 state.serialize_field(key, &TypedReflectSerializer::new(value, self.registry))?;
294 }
295 state.end()
296 }
297}
298
299pub struct TupleStructSerializer<'a> {
300 pub tuple_struct: &'a dyn TupleStruct,
301 pub registry: &'a TypeRegistry,
302}
303
304impl<'a> Serialize for TupleStructSerializer<'a> {
305 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
306 where
307 S: serde::Serializer,
308 {
309 let type_info = self
310 .tuple_struct
311 .get_represented_type_info()
312 .ok_or_else(|| {
313 Error::custom(format_args!(
314 "cannot get type info for {}",
315 self.tuple_struct.reflect_type_path()
316 ))
317 })?;
318
319 let tuple_struct_info = match type_info {
320 TypeInfo::TupleStruct(tuple_struct_info) => tuple_struct_info,
321 info => {
322 return Err(Error::custom(format_args!(
323 "expected tuple struct type but received {info:?}"
324 )));
325 }
326 };
327
328 let serialization_data = self
329 .registry
330 .get(type_info.type_id())
331 .and_then(|registration| registration.data::<SerializationData>());
332 let ignored_len = serialization_data.map(|data| data.len()).unwrap_or(0);
333 let mut state = serializer.serialize_tuple_struct(
334 tuple_struct_info.type_path_table().ident().unwrap(),
335 self.tuple_struct.field_len() - ignored_len,
336 )?;
337
338 for (index, value) in self.tuple_struct.iter_fields().enumerate() {
339 if serialization_data
340 .map(|data| data.is_field_skipped(index))
341 .unwrap_or(false)
342 {
343 continue;
344 }
345 state.serialize_field(&TypedReflectSerializer::new(value, self.registry))?;
346 }
347 state.end()
348 }
349}
350
351pub struct EnumSerializer<'a> {
352 pub enum_value: &'a dyn Enum,
353 pub registry: &'a TypeRegistry,
354}
355
356impl<'a> Serialize for EnumSerializer<'a> {
357 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
358 where
359 S: serde::Serializer,
360 {
361 let type_info = self.enum_value.get_represented_type_info().ok_or_else(|| {
362 Error::custom(format_args!(
363 "cannot get type info for {}",
364 self.enum_value.reflect_type_path()
365 ))
366 })?;
367
368 let enum_info = match type_info {
369 TypeInfo::Enum(enum_info) => enum_info,
370 info => {
371 return Err(Error::custom(format_args!(
372 "expected enum type but received {info:?}"
373 )));
374 }
375 };
376
377 let enum_name = enum_info.type_path_table().ident().unwrap();
378 let variant_index = self.enum_value.variant_index() as u32;
379 let variant_info = enum_info
380 .variant_at(variant_index as usize)
381 .ok_or_else(|| {
382 Error::custom(format_args!(
383 "variant at index `{variant_index}` does not exist",
384 ))
385 })?;
386 let variant_name = variant_info.name();
387 let variant_type = self.enum_value.variant_type();
388 let field_len = self.enum_value.field_len();
389
390 match variant_type {
391 VariantType::Unit => {
392 if type_info.type_path_table().module_path() == Some("core::option")
393 && type_info.type_path_table().ident() == Some("Option")
394 {
395 serializer.serialize_none()
396 } else {
397 serializer.serialize_unit_variant(enum_name, variant_index, variant_name)
398 }
399 }
400 VariantType::Struct => {
401 let struct_info = match variant_info {
402 VariantInfo::Struct(struct_info) => struct_info,
403 info => {
404 return Err(Error::custom(format_args!(
405 "expected struct variant type but received {info:?}",
406 )));
407 }
408 };
409
410 let mut state = serializer.serialize_struct_variant(
411 enum_name,
412 variant_index,
413 variant_name,
414 field_len,
415 )?;
416 for (index, field) in self.enum_value.iter_fields().enumerate() {
417 let field_info = struct_info.field_at(index).unwrap();
418 state.serialize_field(
419 field_info.name(),
420 &TypedReflectSerializer::new(field.value(), self.registry),
421 )?;
422 }
423 state.end()
424 }
425 VariantType::Tuple if field_len == 1 => {
426 let field = self.enum_value.field_at(0).unwrap();
427
428 if type_info.type_path_table().module_path() == Some("core::option")
429 && type_info.type_path_table().ident() == Some("Option")
430 {
431 serializer.serialize_some(&TypedReflectSerializer::new(field, self.registry))
432 } else {
433 serializer.serialize_newtype_variant(
434 enum_name,
435 variant_index,
436 variant_name,
437 &TypedReflectSerializer::new(field, self.registry),
438 )
439 }
440 }
441 VariantType::Tuple => {
442 let mut state = serializer.serialize_tuple_variant(
443 enum_name,
444 variant_index,
445 variant_name,
446 field_len,
447 )?;
448 for field in self.enum_value.iter_fields() {
449 state.serialize_field(&TypedReflectSerializer::new(
450 field.value(),
451 self.registry,
452 ))?;
453 }
454 state.end()
455 }
456 }
457 }
458}
459
460pub struct TupleSerializer<'a> {
461 pub tuple: &'a dyn Tuple,
462 pub registry: &'a TypeRegistry,
463}
464
465impl<'a> Serialize for TupleSerializer<'a> {
466 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
467 where
468 S: serde::Serializer,
469 {
470 let mut state = serializer.serialize_tuple(self.tuple.field_len())?;
471
472 for value in self.tuple.iter_fields() {
473 state.serialize_element(&TypedReflectSerializer::new(value, self.registry))?;
474 }
475 state.end()
476 }
477}
478
479pub struct MapSerializer<'a> {
480 pub map: &'a dyn Map,
481 pub registry: &'a TypeRegistry,
482}
483
484impl<'a> Serialize for MapSerializer<'a> {
485 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
486 where
487 S: serde::Serializer,
488 {
489 let mut state = serializer.serialize_map(Some(self.map.len()))?;
490 for (key, value) in self.map.iter() {
491 state.serialize_entry(
492 &TypedReflectSerializer::new(key, self.registry),
493 &TypedReflectSerializer::new(value, self.registry),
494 )?;
495 }
496 state.end()
497 }
498}
499
500pub struct ListSerializer<'a> {
501 pub list: &'a dyn List,
502 pub registry: &'a TypeRegistry,
503}
504
505impl<'a> Serialize for ListSerializer<'a> {
506 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
507 where
508 S: serde::Serializer,
509 {
510 let mut state = serializer.serialize_seq(Some(self.list.len()))?;
511 for value in self.list.iter() {
512 state.serialize_element(&TypedReflectSerializer::new(value, self.registry))?;
513 }
514 state.end()
515 }
516}
517
518pub struct ArraySerializer<'a> {
519 pub array: &'a dyn Array,
520 pub registry: &'a TypeRegistry,
521}
522
523impl<'a> Serialize for ArraySerializer<'a> {
524 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
525 where
526 S: serde::Serializer,
527 {
528 let mut state = serializer.serialize_tuple(self.array.len())?;
529 for value in self.array.iter() {
530 state.serialize_element(&TypedReflectSerializer::new(value, self.registry))?;
531 }
532 state.end()
533 }
534}
535
536#[cfg(test)]
537mod tests {
538 use crate::serde::ReflectSerializer;
539 use crate::{self as bevy_reflect, Struct};
540 use crate::{Reflect, ReflectSerialize, TypeRegistry};
541 use bevy_utils::HashMap;
542 use ron::extensions::Extensions;
543 use ron::ser::PrettyConfig;
544 use serde::Serialize;
545 use std::f32::consts::PI;
546
547 #[derive(Reflect, Debug, PartialEq)]
548 struct MyStruct {
549 primitive_value: i8,
550 option_value: Option<String>,
551 option_value_complex: Option<SomeStruct>,
552 tuple_value: (f32, usize),
553 list_value: Vec<i32>,
554 array_value: [i32; 5],
555 map_value: HashMap<u8, usize>,
556 struct_value: SomeStruct,
557 tuple_struct_value: SomeTupleStruct,
558 unit_struct: SomeUnitStruct,
559 unit_enum: SomeEnum,
560 newtype_enum: SomeEnum,
561 tuple_enum: SomeEnum,
562 struct_enum: SomeEnum,
563 ignored_struct: SomeIgnoredStruct,
564 ignored_tuple_struct: SomeIgnoredTupleStruct,
565 ignored_struct_variant: SomeIgnoredEnum,
566 ignored_tuple_variant: SomeIgnoredEnum,
567 custom_serialize: CustomSerialize,
568 }
569
570 #[derive(Reflect, Debug, PartialEq)]
571 struct SomeStruct {
572 foo: i64,
573 }
574
575 #[derive(Reflect, Debug, PartialEq)]
576 struct SomeTupleStruct(String);
577
578 #[derive(Reflect, Debug, PartialEq)]
579 struct SomeUnitStruct;
580
581 #[derive(Reflect, Debug, PartialEq)]
582 struct SomeIgnoredStruct {
583 #[reflect(ignore)]
584 ignored: i32,
585 }
586
587 #[derive(Reflect, Debug, PartialEq)]
588 struct SomeIgnoredTupleStruct(#[reflect(ignore)] i32);
589
590 #[derive(Reflect, Debug, PartialEq)]
591 enum SomeEnum {
592 Unit,
593 NewType(usize),
594 Tuple(f32, f32),
595 Struct { foo: String },
596 }
597
598 #[derive(Reflect, Debug, PartialEq)]
599 enum SomeIgnoredEnum {
600 Tuple(#[reflect(ignore)] f32, #[reflect(ignore)] f32),
601 Struct {
602 #[reflect(ignore)]
603 foo: String,
604 },
605 }
606
607 #[derive(Reflect, Debug, PartialEq, Serialize)]
608 struct SomeSerializableStruct {
609 foo: i64,
610 }
611
612 #[derive(Reflect, Debug, PartialEq, Serialize)]
616 #[reflect(Serialize)]
617 struct CustomSerialize {
618 value: usize,
619 #[serde(rename = "renamed")]
620 inner_struct: SomeSerializableStruct,
621 }
622
623 fn get_registry() -> TypeRegistry {
624 let mut registry = TypeRegistry::default();
625 registry.register::<MyStruct>();
626 registry.register::<SomeStruct>();
627 registry.register::<SomeTupleStruct>();
628 registry.register::<SomeUnitStruct>();
629 registry.register::<SomeIgnoredStruct>();
630 registry.register::<SomeIgnoredTupleStruct>();
631 registry.register::<SomeIgnoredEnum>();
632 registry.register::<CustomSerialize>();
633 registry.register::<SomeEnum>();
634 registry.register::<SomeSerializableStruct>();
635 registry.register_type_data::<SomeSerializableStruct, ReflectSerialize>();
636 registry.register::<String>();
637 registry.register::<Option<String>>();
638 registry.register_type_data::<Option<String>, ReflectSerialize>();
639 registry
640 }
641
642 fn get_my_struct() -> MyStruct {
643 let mut map = HashMap::new();
644 map.insert(64, 32);
645 MyStruct {
646 primitive_value: 123,
647 option_value: Some(String::from("Hello world!")),
648 option_value_complex: Some(SomeStruct { foo: 123 }),
649 tuple_value: (PI, 1337),
650 list_value: vec![-2, -1, 0, 1, 2],
651 array_value: [-2, -1, 0, 1, 2],
652 map_value: map,
653 struct_value: SomeStruct { foo: 999999999 },
654 tuple_struct_value: SomeTupleStruct(String::from("Tuple Struct")),
655 unit_struct: SomeUnitStruct,
656 unit_enum: SomeEnum::Unit,
657 newtype_enum: SomeEnum::NewType(123),
658 tuple_enum: SomeEnum::Tuple(1.23, 3.21),
659 struct_enum: SomeEnum::Struct {
660 foo: String::from("Struct variant value"),
661 },
662 ignored_struct: SomeIgnoredStruct { ignored: 123 },
663 ignored_tuple_struct: SomeIgnoredTupleStruct(123),
664 ignored_struct_variant: SomeIgnoredEnum::Struct {
665 foo: String::from("Struct Variant"),
666 },
667 ignored_tuple_variant: SomeIgnoredEnum::Tuple(1.23, 3.45),
668 custom_serialize: CustomSerialize {
669 value: 100,
670 inner_struct: SomeSerializableStruct { foo: 101 },
671 },
672 }
673 }
674
675 #[test]
676 fn should_serialize() {
677 let input = get_my_struct();
678 let registry = get_registry();
679
680 let serializer = ReflectSerializer::new(&input, ®istry);
681
682 let config = PrettyConfig::default()
683 .new_line(String::from("\n"))
684 .indentor(String::from(" "));
685
686 let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
687 let expected = r#"{
688 "bevy_reflect::serde::ser::tests::MyStruct": (
689 primitive_value: 123,
690 option_value: Some("Hello world!"),
691 option_value_complex: Some((
692 foo: 123,
693 )),
694 tuple_value: (3.1415927, 1337),
695 list_value: [
696 -2,
697 -1,
698 0,
699 1,
700 2,
701 ],
702 array_value: (-2, -1, 0, 1, 2),
703 map_value: {
704 64: 32,
705 },
706 struct_value: (
707 foo: 999999999,
708 ),
709 tuple_struct_value: ("Tuple Struct"),
710 unit_struct: (),
711 unit_enum: Unit,
712 newtype_enum: NewType(123),
713 tuple_enum: Tuple(1.23, 3.21),
714 struct_enum: Struct(
715 foo: "Struct variant value",
716 ),
717 ignored_struct: (),
718 ignored_tuple_struct: (),
719 ignored_struct_variant: Struct(),
720 ignored_tuple_variant: Tuple(),
721 custom_serialize: (
722 value: 100,
723 renamed: (
724 foo: 101,
725 ),
726 ),
727 ),
728}"#;
729 assert_eq!(expected, output);
730 }
731
732 #[test]
733 fn should_serialize_option() {
734 #[derive(Reflect, Debug, PartialEq)]
735 struct OptionTest {
736 none: Option<()>,
737 simple: Option<String>,
738 complex: Option<SomeStruct>,
739 }
740
741 let value = OptionTest {
742 none: None,
743 simple: Some(String::from("Hello world!")),
744 complex: Some(SomeStruct { foo: 123 }),
745 };
746
747 let registry = get_registry();
748 let serializer = ReflectSerializer::new(&value, ®istry);
749
750 let config = PrettyConfig::default()
752 .new_line(String::from("\n"))
753 .indentor(String::from(" "));
754
755 let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
756 let expected = r#"{
757 "bevy_reflect::serde::ser::tests::OptionTest": (
758 none: None,
759 simple: Some("Hello world!"),
760 complex: Some((
761 foo: 123,
762 )),
763 ),
764}"#;
765
766 assert_eq!(expected, output);
767
768 let config = PrettyConfig::default()
770 .new_line(String::from("\n"))
771 .extensions(Extensions::IMPLICIT_SOME)
772 .indentor(String::from(" "));
773
774 let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
775 let expected = r#"#![enable(implicit_some)]
776{
777 "bevy_reflect::serde::ser::tests::OptionTest": (
778 none: None,
779 simple: "Hello world!",
780 complex: (
781 foo: 123,
782 ),
783 ),
784}"#;
785
786 assert_eq!(expected, output);
787 }
788
789 #[test]
790 fn enum_should_serialize() {
791 #[derive(Reflect)]
792 enum MyEnum {
793 Unit,
794 NewType(usize),
795 Tuple(f32, f32),
796 Struct { value: String },
797 }
798
799 let mut registry = get_registry();
800 registry.register::<MyEnum>();
801
802 let config = PrettyConfig::default().new_line(String::from("\n"));
803
804 let value = MyEnum::Unit;
806 let serializer = ReflectSerializer::new(&value, ®istry);
807 let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap();
808 let expected = r#"{
809 "bevy_reflect::serde::ser::tests::MyEnum": Unit,
810}"#;
811 assert_eq!(expected, output);
812
813 let value = MyEnum::NewType(123);
815 let serializer = ReflectSerializer::new(&value, ®istry);
816 let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap();
817 let expected = r#"{
818 "bevy_reflect::serde::ser::tests::MyEnum": NewType(123),
819}"#;
820 assert_eq!(expected, output);
821
822 let value = MyEnum::Tuple(1.23, 3.21);
824 let serializer = ReflectSerializer::new(&value, ®istry);
825 let output = ron::ser::to_string_pretty(&serializer, config.clone()).unwrap();
826 let expected = r#"{
827 "bevy_reflect::serde::ser::tests::MyEnum": Tuple(1.23, 3.21),
828}"#;
829 assert_eq!(expected, output);
830
831 let value = MyEnum::Struct {
833 value: String::from("I <3 Enums"),
834 };
835 let serializer = ReflectSerializer::new(&value, ®istry);
836 let output = ron::ser::to_string_pretty(&serializer, config).unwrap();
837 let expected = r#"{
838 "bevy_reflect::serde::ser::tests::MyEnum": Struct(
839 value: "I <3 Enums",
840 ),
841}"#;
842 assert_eq!(expected, output);
843 }
844
845 #[test]
846 fn should_serialize_non_self_describing_binary() {
847 let input = get_my_struct();
848 let registry = get_registry();
849
850 let serializer = ReflectSerializer::new(&input, ®istry);
851 let bytes = bincode::serialize(&serializer).unwrap();
852
853 let expected: Vec<u8> = vec![
854 1, 0, 0, 0, 0, 0, 0, 0, 41, 0, 0, 0, 0, 0, 0, 0, 98, 101, 118, 121, 95, 114, 101, 102,
855 108, 101, 99, 116, 58, 58, 115, 101, 114, 100, 101, 58, 58, 115, 101, 114, 58, 58, 116,
856 101, 115, 116, 115, 58, 58, 77, 121, 83, 116, 114, 117, 99, 116, 123, 1, 12, 0, 0, 0,
857 0, 0, 0, 0, 72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33, 1, 123, 0, 0, 0,
858 0, 0, 0, 0, 219, 15, 73, 64, 57, 5, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 254, 255,
859 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 254, 255, 255, 255,
860 255, 255, 255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 64, 32,
861 0, 0, 0, 0, 0, 0, 0, 255, 201, 154, 59, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 84, 117,
862 112, 108, 101, 32, 83, 116, 114, 117, 99, 116, 0, 0, 0, 0, 1, 0, 0, 0, 123, 0, 0, 0, 0,
863 0, 0, 0, 2, 0, 0, 0, 164, 112, 157, 63, 164, 112, 77, 64, 3, 0, 0, 0, 20, 0, 0, 0, 0,
864 0, 0, 0, 83, 116, 114, 117, 99, 116, 32, 118, 97, 114, 105, 97, 110, 116, 32, 118, 97,
865 108, 117, 101, 1, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 101, 0, 0, 0, 0, 0, 0,
866 0,
867 ];
868
869 assert_eq!(expected, bytes);
870 }
871
872 #[test]
873 fn should_serialize_self_describing_binary() {
874 let input = get_my_struct();
875 let registry = get_registry();
876
877 let serializer = ReflectSerializer::new(&input, ®istry);
878 let bytes: Vec<u8> = rmp_serde::to_vec(&serializer).unwrap();
879
880 let expected: Vec<u8> = vec![
881 129, 217, 41, 98, 101, 118, 121, 95, 114, 101, 102, 108, 101, 99, 116, 58, 58, 115,
882 101, 114, 100, 101, 58, 58, 115, 101, 114, 58, 58, 116, 101, 115, 116, 115, 58, 58, 77,
883 121, 83, 116, 114, 117, 99, 116, 220, 0, 19, 123, 172, 72, 101, 108, 108, 111, 32, 119,
884 111, 114, 108, 100, 33, 145, 123, 146, 202, 64, 73, 15, 219, 205, 5, 57, 149, 254, 255,
885 0, 1, 2, 149, 254, 255, 0, 1, 2, 129, 64, 32, 145, 206, 59, 154, 201, 255, 145, 172,
886 84, 117, 112, 108, 101, 32, 83, 116, 114, 117, 99, 116, 144, 164, 85, 110, 105, 116,
887 129, 167, 78, 101, 119, 84, 121, 112, 101, 123, 129, 165, 84, 117, 112, 108, 101, 146,
888 202, 63, 157, 112, 164, 202, 64, 77, 112, 164, 129, 166, 83, 116, 114, 117, 99, 116,
889 145, 180, 83, 116, 114, 117, 99, 116, 32, 118, 97, 114, 105, 97, 110, 116, 32, 118, 97,
890 108, 117, 101, 144, 144, 129, 166, 83, 116, 114, 117, 99, 116, 144, 129, 165, 84, 117,
891 112, 108, 101, 144, 146, 100, 145, 101,
892 ];
893
894 assert_eq!(expected, bytes);
895 }
896
897 #[test]
898 fn should_serialize_dynamic_option() {
899 #[derive(Default, Reflect)]
900 struct OtherStruct {
901 some: Option<SomeStruct>,
902 none: Option<SomeStruct>,
903 }
904
905 let value = OtherStruct {
906 some: Some(SomeStruct { foo: 999999999 }),
907 none: None,
908 };
909 let dynamic = value.clone_dynamic();
910 let reflect = dynamic.as_reflect();
911
912 let registry = get_registry();
913
914 let serializer = ReflectSerializer::new(reflect, ®istry);
915
916 let mut buf = Vec::new();
917
918 let format = serde_json::ser::PrettyFormatter::with_indent(b" ");
919 let mut ser = serde_json::Serializer::with_formatter(&mut buf, format);
920
921 serializer.serialize(&mut ser).unwrap();
922
923 let output = std::str::from_utf8(&buf).unwrap();
924 let expected = r#"{
925 "bevy_reflect::serde::ser::tests::OtherStruct": {
926 "some": {
927 "foo": 999999999
928 },
929 "none": null
930 }
931}"#;
932
933 assert_eq!(expected, output);
934 }
935}