Skip to content

Commit

Permalink
Sorts the scene entries by path before serializing. (#15047)
Browse files Browse the repository at this point in the history
# Objective

Fixes: #14515

## Solution

Sorts the iterator with itertools' sorted_by function. This is required
given that 'self.entries' is an immutable &[Box<dyn PartialReflect]
which also doesn't implement Clone or Copy.

## Testing

The modifications passed the unit testing only after they were edited to
ensure that the items were in alphabetical order.
I haven't checked for performance implications.
  • Loading branch information
Wiwip authored Sep 9, 2024
1 parent 5eca832 commit fab0e5d
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions crates/bevy_scene/src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ impl<'a> Serialize for EntitySerializer<'a> {
/// Used to serialize scene resources in [`SceneSerializer`] and entity components in [`EntitySerializer`].
/// Note that having several entries of the same type in `entries` will lead to an error when using the RON format and
/// deserializing through [`SceneMapDeserializer`].
///
/// Note: The entries are sorted by type path before they're serialized.
pub struct SceneMapSerializer<'a> {
/// List of boxed values of unique type to serialize.
pub entries: &'a [Box<dyn PartialReflect>],
Expand All @@ -167,10 +169,25 @@ impl<'a> Serialize for SceneMapSerializer<'a> {
S: Serializer,
{
let mut state = serializer.serialize_map(Some(self.entries.len()))?;
for reflect in self.entries {
let sorted_entries = {
let mut entries = self
.entries
.iter()
.map(|entry| {
(
entry.get_represented_type_info().unwrap().type_path(),
entry.as_partial_reflect(),
)
})
.collect::<Vec<_>>();
entries.sort_by_key(|(type_path, _partial_reflect)| *type_path);
entries
};

for (type_path, partial_reflect) in sorted_entries {
state.serialize_entry(
reflect.get_represented_type_info().unwrap().type_path(),
&TypedReflectSerializer::new(reflect.as_partial_reflect(), self.registry),
type_path,
&TypedReflectSerializer::new(partial_reflect, self.registry),
)?;
}
state.end()
Expand Down Expand Up @@ -598,15 +615,15 @@ mod tests {
),
4294967297: (
components: {
"bevy_scene::serde::tests::Foo": (123),
"bevy_scene::serde::tests::Bar": (345),
"bevy_scene::serde::tests::Foo": (123),
},
),
4294967298: (
components: {
"bevy_scene::serde::tests::Foo": (123),
"bevy_scene::serde::tests::Bar": (345),
"bevy_scene::serde::tests::Baz": (789),
"bevy_scene::serde::tests::Foo": (123),
},
),
},
Expand Down

0 comments on commit fab0e5d

Please sign in to comment.