Skip to content

Commit

Permalink
Added try_map_unchanged. (#17653)
Browse files Browse the repository at this point in the history
# 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` .
  • Loading branch information
mintlu8 authored Feb 3, 2025
1 parent bdf60d6 commit 29d0ef6
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions crates/bevy_ecs/src/change_detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>` to a `Mut<U>`, 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<U: ?Sized, E>(self, f: impl FnOnce(&mut $target) -> Result<&mut U, E>) -> Result<Mut<'w, U>, 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>
Expand Down

0 comments on commit 29d0ef6

Please sign in to comment.