Skip to content

Commit

Permalink
Enable dynamic mutable access to component data (bevyengine#1284)
Browse files Browse the repository at this point in the history
* Enable dynamic mutable access to component data

* Add clippy allowance, more documentation
  • Loading branch information
willcrichton authored and rparrett committed Jan 27, 2021
1 parent cf12c60 commit 66d03a1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
7 changes: 1 addition & 6 deletions crates/bevy_ecs/src/core/archetype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,7 @@ impl Archetype {

/// # Safety
/// `index` must be in-bounds
pub(crate) unsafe fn get_dynamic(
&self,
ty: TypeId,
size: usize,
index: usize,
) -> Option<NonNull<u8>> {
pub unsafe fn get_dynamic(&self, ty: TypeId, size: usize, index: usize) -> Option<NonNull<u8>> {
debug_assert!(index < self.len);
Some(NonNull::new_unchecked(
(*self.data.get())
Expand Down
22 changes: 22 additions & 0 deletions crates/bevy_reflect/src/impls/bevy_ecs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub struct ReflectComponent {
add_component: fn(&mut World, resources: &Resources, Entity, &dyn Reflect),
apply_component: fn(&mut World, Entity, &dyn Reflect),
reflect_component: unsafe fn(&Archetype, usize) -> &dyn Reflect,
reflect_component_mut: unsafe fn(&Archetype, usize) -> &mut dyn Reflect,
copy_component: fn(&World, &mut World, &Resources, Entity, Entity),
}

Expand Down Expand Up @@ -38,6 +39,20 @@ impl ReflectComponent {
(self.reflect_component)(archetype, entity_index)
}

/// # Safety
/// This does not do bound checks on entity_index. You must make sure entity_index is within bounds before calling.
/// This method does not prevent you from having two mutable pointers to the same data, violating Rust's aliasing rules. To avoid this:
/// * Only call this method in a thread-local system to avoid sharing across threads.
/// * Don't call this method more than once in the same scope for a given component.
#[allow(clippy::mut_from_ref)]
pub unsafe fn reflect_component_mut<'a>(
&self,
archetype: &'a Archetype,
entity_index: usize,
) -> &'a mut dyn Reflect {
(self.reflect_component_mut)(archetype, entity_index)
}

pub fn copy_component(
&self,
source_world: &World,
Expand Down Expand Up @@ -87,6 +102,13 @@ impl<C: Component + Reflect + FromResources> FromType<C> for ReflectComponent {
ptr.as_ref().unwrap()
}
},
reflect_component_mut: |archetype, index| {
unsafe {
// the type has been looked up by the caller, so this is safe
let ptr = archetype.get::<C>().unwrap().as_ptr().add(index);
&mut *ptr
}
},
}
}
}
Expand Down

0 comments on commit 66d03a1

Please sign in to comment.