Skip to content

Commit f62f291

Browse files
add get_resource_unchecked_mut_by_id
1 parent dfb80ee commit f62f291

File tree

1 file changed

+22
-3
lines changed
  • crates/bevy_ecs/src/world

1 file changed

+22
-3
lines changed

crates/bevy_ecs/src/world/mod.rs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,6 +1450,25 @@ impl World {
14501450
/// use this in cases where the actual types are not known at compile time.**
14511451
#[inline]
14521452
pub fn get_resource_mut_by_id(&mut self, component_id: ComponentId) -> Option<MutUntyped<'_>> {
1453+
// SAFETY: unique world access
1454+
unsafe { self.get_resource_unchecked_mut_by_id(component_id) }
1455+
}
1456+
1457+
/// Gets a resource to the resource with the id [`ComponentId`] if it exists.
1458+
/// The returned pointer may be used to modify the resource, as long as the mutable borrow
1459+
/// of the [`World`] is still valid.
1460+
///
1461+
/// **You should prefer to use the typed API [`World::get_resource_mut`] where possible and only
1462+
/// use this in cases where the actual types are not known at compile time.**
1463+
///
1464+
/// # Safety
1465+
/// This will allow aliased mutable access to the given resource type. The caller must ensure
1466+
/// that there is either only one mutable access or multiple immutable accesses at a time.
1467+
#[inline]
1468+
pub unsafe fn get_resource_unchecked_mut_by_id(
1469+
&self,
1470+
component_id: ComponentId,
1471+
) -> Option<MutUntyped<'_>> {
14531472
let info = self.components.get_info(component_id)?;
14541473
if !info.is_send_and_sync() {
14551474
self.validate_non_send_access_untyped(info.name());
@@ -1462,14 +1481,14 @@ impl World {
14621481
// SAFETY:
14631482
// - index is in-bounds because the column is initialized and non-empty
14641483
// - no other reference to the ticks of the same row can exist at the same time
1465-
component_ticks: unsafe { ticks.deref_mut() },
1484+
component_ticks: ticks.deref_mut(),
14661485
last_change_tick: self.last_change_tick(),
14671486
change_tick: self.read_change_tick(),
14681487
};
14691488

14701489
Some(MutUntyped {
14711490
// SAFETY: This function has exclusive access to the world so nothing aliases `ptr`.
1472-
value: unsafe { ptr.assert_unique() },
1491+
value: ptr.assert_unique(),
14731492
ticks,
14741493
})
14751494
}
@@ -1524,7 +1543,7 @@ impl World {
15241543
component_id: ComponentId,
15251544
) -> Option<MutUntyped<'_>> {
15261545
self.components().get_info(component_id)?;
1527-
// SAFETY: entity_location is valid, component_id is valid as checked by the line above
1546+
// SAFETY: entity_location is valid, component_id is valid as checked by the line above, world access is unique
15281547
unsafe {
15291548
get_mut_by_id(
15301549
self,

0 commit comments

Comments
 (0)