Skip to content

Commit 29d0ef6

Browse files
authored
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` .
1 parent bdf60d6 commit 29d0ef6

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

crates/bevy_ecs/src/change_detection.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,20 @@ macro_rules! impl_methods {
494494
})
495495
}
496496

497+
/// Optionally maps to an inner value by applying a function to the contained reference, returns an error on failure.
498+
/// This is useful in a situation where you need to convert a `Mut<T>` to a `Mut<U>`, but only if `T` contains `U`.
499+
///
500+
/// As with `map_unchanged`, you should never modify the argument passed to the closure.
501+
pub fn try_map_unchanged<U: ?Sized, E>(self, f: impl FnOnce(&mut $target) -> Result<&mut U, E>) -> Result<Mut<'w, U>, E> {
502+
let value = f(self.value);
503+
value.map(|value| Mut {
504+
value,
505+
ticks: self.ticks,
506+
#[cfg(feature = "track_location")]
507+
changed_by: self.changed_by,
508+
})
509+
}
510+
497511
/// Allows you access to the dereferenced value of this pointer without immediately
498512
/// triggering change detection.
499513
pub fn as_deref_mut(&mut self) -> Mut<'_, <$target as Deref>::Target>

0 commit comments

Comments
 (0)