From 29d0ef6f3a309d559a1c4ef3f78381a5cb7fcb94 Mon Sep 17 00:00:00 2001 From: Mincong Lu <139340600+mintlu8@users.noreply.github.com> Date: Tue, 4 Feb 2025 06:03:39 +0800 Subject: [PATCH] Added `try_map_unchanged`. (#17653) # Objective Allow mapping `Mut` to another value while returning a custom error on failure. ## Solution Added `try_map_unchanged` to `Mut` which returns a `Result` instead of `Option` . --- crates/bevy_ecs/src/change_detection.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/bevy_ecs/src/change_detection.rs b/crates/bevy_ecs/src/change_detection.rs index 414faa8fde..0884fbd59e 100644 --- a/crates/bevy_ecs/src/change_detection.rs +++ b/crates/bevy_ecs/src/change_detection.rs @@ -494,6 +494,20 @@ macro_rules! impl_methods { }) } + /// Optionally maps to an inner value by applying a function to the contained reference, returns an error on failure. + /// This is useful in a situation where you need to convert a `Mut` to a `Mut`, but only if `T` contains `U`. + /// + /// As with `map_unchanged`, you should never modify the argument passed to the closure. + pub fn try_map_unchanged(self, f: impl FnOnce(&mut $target) -> Result<&mut U, E>) -> Result, E> { + let value = f(self.value); + value.map(|value| Mut { + value, + ticks: self.ticks, + #[cfg(feature = "track_location")] + changed_by: self.changed_by, + }) + } + /// Allows you access to the dereferenced value of this pointer without immediately /// triggering change detection. pub fn as_deref_mut(&mut self) -> Mut<'_, <$target as Deref>::Target>