Add filter_map_unchanged to Mut<T> (#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<T>` to a `Mut<U>`, but only if `T` contains
`U`.

---------

Co-authored-by: Chris Russell <8494645+chescock@users.noreply.github.com>
This commit is contained in:
Thomas Alban 2024-08-22 18:51:21 +01:00 committed by GitHub
parent b922896080
commit e4b740840f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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<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 filter_map_unchanged<U: ?Sized>(self, f: impl FnOnce(&mut $target) -> Option<&mut U>) -> Option<Mut<'w, U>> {
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>