Skip to content

Commit afad9c3

Browse files
committed
Don't use direct field access in Simd functions
1 parent ceb2611 commit afad9c3

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

crates/core_simd/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#![no_std]
22
#![feature(
33
const_ptr_read,
4+
const_refs_to_cell,
5+
const_transmute_copy,
46
convert_float_to_int,
57
decl_macro,
68
intra_doc_pointers,

crates/core_simd/src/vector.rs

+18-8
Original file line numberDiff line numberDiff line change
@@ -135,22 +135,32 @@ where
135135
/// assert_eq!(v.as_array(), &[0, 1, 2, 3]);
136136
/// ```
137137
pub const fn as_array(&self) -> &[T; LANES] {
138-
&self.0
138+
// SAFETY: Transmuting between `Simd<T, LANES>` and `[T; LANES]`
139+
// is always valid and `Simd<T, LANES>` never has a lower alignment
140+
// than `[T; LANES]`.
141+
unsafe { &*(self as *const Self as *const [T; LANES]) }
139142
}
140143

141144
/// Returns a mutable array reference containing the entire SIMD vector.
142145
pub fn as_mut_array(&mut self) -> &mut [T; LANES] {
143-
&mut self.0
146+
// SAFETY: Transmuting between `Simd<T, LANES>` and `[T; LANES]`
147+
// is always valid and `Simd<T, LANES>` never has a lower alignment
148+
// than `[T; LANES]`.
149+
unsafe { &mut *(self as *mut Self as *mut [T; LANES]) }
144150
}
145151

146152
/// Converts an array to a SIMD vector.
147153
pub const fn from_array(array: [T; LANES]) -> Self {
148-
Self(array)
154+
// SAFETY: Transmuting between `Simd<T, LANES>` and `[T; LANES]`
155+
// is always valid.
156+
unsafe { core::mem::transmute_copy(&array) }
149157
}
150158

151159
/// Converts a SIMD vector to an array.
152160
pub const fn to_array(self) -> [T; LANES] {
153-
self.0
161+
// SAFETY: Transmuting between `Simd<T, LANES>` and `[T; LANES]`
162+
// is always valid.
163+
unsafe { core::mem::transmute_copy(&self) }
154164
}
155165

156166
/// Converts a slice to a SIMD vector containing `slice[..LANES]`.
@@ -735,7 +745,7 @@ where
735745
{
736746
#[inline]
737747
fn as_ref(&self) -> &[T; LANES] {
738-
&self.0
748+
self.as_array()
739749
}
740750
}
741751

@@ -746,7 +756,7 @@ where
746756
{
747757
#[inline]
748758
fn as_mut(&mut self) -> &mut [T; LANES] {
749-
&mut self.0
759+
self.as_mut_array()
750760
}
751761
}
752762

@@ -758,7 +768,7 @@ where
758768
{
759769
#[inline]
760770
fn as_ref(&self) -> &[T] {
761-
&self.0
771+
self.as_array()
762772
}
763773
}
764774

@@ -769,7 +779,7 @@ where
769779
{
770780
#[inline]
771781
fn as_mut(&mut self) -> &mut [T] {
772-
&mut self.0
782+
self.as_mut_array()
773783
}
774784
}
775785

0 commit comments

Comments
 (0)