Skip to content

Commit d7425d3

Browse files
committed
[bevy_core/bytes] Fix UB with accessing memory with incorrect alignment
1 parent 20673db commit d7425d3

File tree

1 file changed

+3
-9
lines changed

1 file changed

+3
-9
lines changed

crates/bevy_core/src/bytes.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,7 @@ where
4949
T: Byteable + Clone,
5050
{
5151
fn from_bytes(bytes: &[u8]) -> Self {
52-
unsafe {
53-
let byte_ptr = bytes.as_ptr();
54-
let ptr = byte_ptr as *const Self;
55-
(*ptr).clone()
56-
}
52+
unsafe { bytes.as_ptr().cast::<Self>().read_unaligned() }
5753
}
5854
}
5955

@@ -170,10 +166,8 @@ where
170166
{
171167
fn from_bytes(bytes: &[u8]) -> Self {
172168
unsafe {
173-
let byte_ptr = bytes.as_ptr() as *const T;
174-
let len = bytes.len() / std::mem::size_of::<T>();
175-
let slice = core::slice::from_raw_parts::<T>(byte_ptr, len);
176-
slice.to_vec()
169+
let (_, body, _) = bytes.align_to::<T>();
170+
body.to_vec()
177171
}
178172
}
179173
}

0 commit comments

Comments
 (0)