Skip to content

Commit

Permalink
Try #7222:
Browse files Browse the repository at this point in the history
  • Loading branch information
bors[bot] authored Jan 16, 2023
2 parents c56bbcb + 50538bf commit d573344
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
16 changes: 13 additions & 3 deletions crates/bevy_ecs/src/world/entity_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,13 @@ pub struct EntityRef<'w> {
}

impl<'w> EntityRef<'w> {
/// # Safety
///
/// Entity and location _must_ be valid for the provided world.
#[inline]
pub(crate) fn new(world: &'w World, entity: Entity, location: EntityLocation) -> Self {
pub(crate) unsafe fn new(world: &'w World, entity: Entity, location: EntityLocation) -> Self {
debug_assert!(world.entities().contains(entity));

Self {
world,
entity,
Expand Down Expand Up @@ -193,7 +198,9 @@ impl<'w> EntityRef<'w> {

impl<'w> From<EntityMut<'w>> for EntityRef<'w> {
fn from(entity_mut: EntityMut<'w>) -> EntityRef<'w> {
EntityRef::new(entity_mut.world, entity_mut.entity, entity_mut.location)
// SAFETY: the safety invariants on EntityMut and EntityRef are identical
// and EntityMut is promised to be valid by construction.
unsafe { EntityRef::new(entity_mut.world, entity_mut.entity, entity_mut.location) }
}
}

Expand All @@ -206,13 +213,16 @@ pub struct EntityMut<'w> {

impl<'w> EntityMut<'w> {
/// # Safety
/// entity and location _must_ be valid
///
/// Entity and location _must_ be valid for the provided world.
#[inline]
pub(crate) unsafe fn new(
world: &'w mut World,
entity: Entity,
location: EntityLocation,
) -> Self {
debug_assert!(world.entities().contains(entity));

EntityMut {
world,
entity,
Expand Down
5 changes: 4 additions & 1 deletion crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,10 @@ impl World {
#[inline]
pub fn get_entity(&self, entity: Entity) -> Option<EntityRef> {
let location = self.entities.get(entity)?;
Some(EntityRef::new(self, entity, location))
// SAFETY: if the Entity is invalid, the function returns early.
// Additionally, Entities::get(entity) returns the correct EntityLocation if the entity exists.
let entity_ref = unsafe { EntityRef::new(self, entity, location) };
Some(entity_ref)
}

/// Returns an [`Entity`] iterator of current entities.
Expand Down

0 comments on commit d573344

Please sign in to comment.