Skip to content

Commit 7166a28

Browse files
authored
Enable dynamic mutable access to component data (#1284)
* Enable dynamic mutable access to component data * Add clippy allowance, more documentation
1 parent ebcab36 commit 7166a28

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

crates/bevy_ecs/src/core/archetype.rs

+1-6
Original file line numberDiff line numberDiff line change
@@ -223,12 +223,7 @@ impl Archetype {
223223

224224
/// # Safety
225225
/// `index` must be in-bounds
226-
pub(crate) unsafe fn get_dynamic(
227-
&self,
228-
ty: TypeId,
229-
size: usize,
230-
index: usize,
231-
) -> Option<NonNull<u8>> {
226+
pub unsafe fn get_dynamic(&self, ty: TypeId, size: usize, index: usize) -> Option<NonNull<u8>> {
232227
debug_assert!(index < self.len);
233228
Some(NonNull::new_unchecked(
234229
(*self.data.get())

crates/bevy_reflect/src/impls/bevy_ecs.rs

+22
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ pub struct ReflectComponent {
1010
add_component: fn(&mut World, resources: &Resources, Entity, &dyn Reflect),
1111
apply_component: fn(&mut World, Entity, &dyn Reflect),
1212
reflect_component: unsafe fn(&Archetype, usize) -> &dyn Reflect,
13+
reflect_component_mut: unsafe fn(&Archetype, usize) -> &mut dyn Reflect,
1314
copy_component: fn(&World, &mut World, &Resources, Entity, Entity),
1415
}
1516

@@ -38,6 +39,20 @@ impl ReflectComponent {
3839
(self.reflect_component)(archetype, entity_index)
3940
}
4041

42+
/// # Safety
43+
/// This does not do bound checks on entity_index. You must make sure entity_index is within bounds before calling.
44+
/// This method does not prevent you from having two mutable pointers to the same data, violating Rust's aliasing rules. To avoid this:
45+
/// * Only call this method in a thread-local system to avoid sharing across threads.
46+
/// * Don't call this method more than once in the same scope for a given component.
47+
#[allow(clippy::mut_from_ref)]
48+
pub unsafe fn reflect_component_mut<'a>(
49+
&self,
50+
archetype: &'a Archetype,
51+
entity_index: usize,
52+
) -> &'a mut dyn Reflect {
53+
(self.reflect_component_mut)(archetype, entity_index)
54+
}
55+
4156
pub fn copy_component(
4257
&self,
4358
source_world: &World,
@@ -87,6 +102,13 @@ impl<C: Component + Reflect + FromResources> FromType<C> for ReflectComponent {
87102
ptr.as_ref().unwrap()
88103
}
89104
},
105+
reflect_component_mut: |archetype, index| {
106+
unsafe {
107+
// the type has been looked up by the caller, so this is safe
108+
let ptr = archetype.get::<C>().unwrap().as_ptr().add(index);
109+
&mut *ptr
110+
}
111+
},
90112
}
91113
}
92114
}

0 commit comments

Comments
 (0)