Use map_unchanged in reflection instead of creating a Mut manually. (#14692)

# Objective

The code to create `ReflectComponent` and `ReflectResource` instances
manually constructs a `Mut<dyn Reflect>` by copying everything but
`value`. That can be done more concisely and better respecting
encapsulation by calling the `map_unchanged()` method.

## Solution

Use `map_unchanged` instead of creating a `Mut` manually.

---------

Co-authored-by: radiish <cb.setho@gmail.com>
This commit is contained in:
Chris Russell 2024-08-15 10:26:57 -04:00 committed by GitHub
parent d849941dac
commit 0ea46663b0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 7 additions and 22 deletions

View File

@ -293,24 +293,15 @@ impl<C: Component + Reflect + TypePath> FromType<C> for ReflectComponent {
},
reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),
reflect_mut: |entity| {
entity.into_mut::<C>().map(|c| Mut {
value: c.value as &mut dyn Reflect,
ticks: c.ticks,
#[cfg(feature = "track_change_detection")]
changed_by: c.changed_by,
})
entity
.into_mut::<C>()
.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
},
reflect_unchecked_mut: |entity| {
// SAFETY: reflect_unchecked_mut is an unsafe function pointer used by
// `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`
unsafe {
entity.get_mut::<C>().map(|c| Mut {
value: c.value as &mut dyn Reflect,
ticks: c.ticks,
#[cfg(feature = "track_change_detection")]
changed_by: c.changed_by,
})
}
let c = unsafe { entity.get_mut::<C>() };
c.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
},
})
}

View File

@ -208,14 +208,8 @@ impl<R: Resource + FromReflect + TypePath> FromType<R> for ReflectResource {
reflect_unchecked_mut: |world| {
// SAFETY: all usages of `reflect_unchecked_mut` guarantee that there is either a single mutable
// reference or multiple immutable ones alive at any given point
unsafe {
world.get_resource_mut::<R>().map(|res| Mut {
value: res.value as &mut dyn Reflect,
ticks: res.ticks,
#[cfg(feature = "track_change_detection")]
changed_by: res.changed_by,
})
}
let res = unsafe { world.get_resource_mut::<R>() };
res.map(|res| res.map_unchanged(|value| value as &mut dyn Reflect))
},
copy: |source_world, destination_world, registry| {
let source_resource = source_world.resource::<R>();