Skip to content

Commit ccedb39

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

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

crates/core_simd/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
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,
79
platform_intrinsics,
10+
ptr_from_ref,
811
repr_simd,
912
simd_ffi,
1013
staged_api,

crates/core_simd/src/vector.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -135,22 +135,26 @@ 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: `[T; LANES]` and `Simd<T, LANES>` have the same layout.
139+
unsafe { &*core::ptr::from_ref(self).cast() }
139140
}
140141

141142
/// Returns a mutable array reference containing the entire SIMD vector.
142143
pub fn as_mut_array(&mut self) -> &mut [T; LANES] {
143-
&mut self.0
144+
// SAFETY: `[T; LANES]` and `Simd<T, LANES>` have the same layout.
145+
unsafe { &mut *core::ptr::from_mut(self).cast() }
144146
}
145147

146148
/// Converts an array to a SIMD vector.
147149
pub const fn from_array(array: [T; LANES]) -> Self {
148-
Self(array)
150+
// SAFETY: `[T; LANES]` and `Simd<T, LANES>` have the same layout.
151+
unsafe { core::mem::transmute_copy(&array) }
149152
}
150153

151154
/// Converts a SIMD vector to an array.
152155
pub const fn to_array(self) -> [T; LANES] {
153-
self.0
156+
// SAFETY: `[T; LANES]` and `Simd<T, LANES>` have the same layout.
157+
unsafe { core::mem::transmute_copy(&self) }
154158
}
155159

156160
/// Converts a slice to a SIMD vector containing `slice[..LANES]`.
@@ -735,7 +739,7 @@ where
735739
{
736740
#[inline]
737741
fn as_ref(&self) -> &[T; LANES] {
738-
&self.0
742+
self.as_array()
739743
}
740744
}
741745

@@ -746,7 +750,7 @@ where
746750
{
747751
#[inline]
748752
fn as_mut(&mut self) -> &mut [T; LANES] {
749-
&mut self.0
753+
self.as_mut_array()
750754
}
751755
}
752756

@@ -758,7 +762,7 @@ where
758762
{
759763
#[inline]
760764
fn as_ref(&self) -> &[T] {
761-
&self.0
765+
self.as_array()
762766
}
763767
}
764768

@@ -769,7 +773,7 @@ where
769773
{
770774
#[inline]
771775
fn as_mut(&mut self) -> &mut [T] {
772-
&mut self.0
776+
self.as_mut_array()
773777
}
774778
}
775779

0 commit comments

Comments
 (0)