Skip to content

Commit

Permalink
Use ManuallyDrop instead of forget in insert_resource_with_id (#2947)
Browse files Browse the repository at this point in the history
# Objective

Calling forget would invalidate the data pointer before it is used.

## Solution

Use `ManuallyDrop` to prevent the value from being dropped without moving it.
  • Loading branch information
bjorn3 committed Feb 3, 2022
1 parent 6ac9d68 commit af22cc1
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::{
use std::{
any::TypeId,
fmt,
mem::ManuallyDrop,
sync::atomic::{AtomicU32, Ordering},
};

Expand Down Expand Up @@ -1003,13 +1004,13 @@ impl World {
/// # Safety
/// `component_id` must be valid and correspond to a resource component of type T
#[inline]
unsafe fn insert_resource_with_id<T>(&mut self, component_id: ComponentId, mut value: T) {
unsafe fn insert_resource_with_id<T>(&mut self, component_id: ComponentId, value: T) {
let change_tick = self.change_tick();
let column = self.initialize_resource_internal(component_id);
if column.is_empty() {
let mut value = ManuallyDrop::new(value);
// SAFE: column is of type T and has been allocated above
let data = (&mut value as *mut T).cast::<u8>();
std::mem::forget(value);
let data = (&mut *value as *mut T).cast::<u8>();
column.push(data, ComponentTicks::new(change_tick));
} else {
// SAFE: column is of type T and has already been allocated
Expand Down

0 comments on commit af22cc1

Please sign in to comment.