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` .
This commit is contained in:
Mincong Lu 2025-02-04 06:03:39 +08:00 committed by GitHub
parent bdf60d6933
commit 29d0ef6f3a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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>