From e4b740840f17d0ff3fa15d979d0ed2c65fa693c2 Mon Sep 17 00:00:00 2001 From: Thomas Alban <98399119+ThomasAlban@users.noreply.github.com> Date: Thu, 22 Aug 2024 18:51:21 +0100 Subject: [PATCH] Add `filter_map_unchanged` to `Mut` (#14837) Closes #14836. `filter_map_unchanged` optionally maps to an inner value by applying a function to the contained reference. This is useful in a situation where you need to convert a `Mut` to a `Mut`, but only if `T` contains `U`. --------- Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com> --- 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 c04886a0c9..b91bb9ea16 100644 --- a/crates/bevy_ecs/src/change_detection.rs +++ b/crates/bevy_ecs/src/change_detection.rs @@ -428,6 +428,20 @@ macro_rules! impl_methods { } } + /// Optionally maps to an inner value by applying a function to the contained reference. + /// 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 filter_map_unchanged(self, f: impl FnOnce(&mut $target) -> Option<&mut U>) -> Option> { + let value = f(self.value); + value.map(|value| Mut { + value, + ticks: self.ticks, + #[cfg(feature = "track_change_detection")] + 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>