From ccedb39efd0410878295cad26dfbc54342d302c3 Mon Sep 17 00:00:00 2001 From: Markus Everling Date: Sat, 22 Apr 2023 21:12:35 +0000 Subject: [PATCH] Don't use direct field access in `Simd` functions --- crates/core_simd/src/lib.rs | 3 +++ crates/core_simd/src/vector.rs | 20 ++++++++++++-------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/core_simd/src/lib.rs b/crates/core_simd/src/lib.rs index 927b1654f8e..4fff9b8c921 100644 --- a/crates/core_simd/src/lib.rs +++ b/crates/core_simd/src/lib.rs @@ -1,10 +1,13 @@ #![no_std] #![feature( const_ptr_read, + const_refs_to_cell, + const_transmute_copy, convert_float_to_int, decl_macro, intra_doc_pointers, platform_intrinsics, + ptr_from_ref, repr_simd, simd_ffi, staged_api, diff --git a/crates/core_simd/src/vector.rs b/crates/core_simd/src/vector.rs index 3e39f1d623c..341c3ac3dbf 100644 --- a/crates/core_simd/src/vector.rs +++ b/crates/core_simd/src/vector.rs @@ -135,22 +135,26 @@ where /// assert_eq!(v.as_array(), &[0, 1, 2, 3]); /// ``` pub const fn as_array(&self) -> &[T; LANES] { - &self.0 + // SAFETY: `[T; LANES]` and `Simd` have the same layout. + unsafe { &*core::ptr::from_ref(self).cast() } } /// Returns a mutable array reference containing the entire SIMD vector. pub fn as_mut_array(&mut self) -> &mut [T; LANES] { - &mut self.0 + // SAFETY: `[T; LANES]` and `Simd` have the same layout. + unsafe { &mut *core::ptr::from_mut(self).cast() } } /// Converts an array to a SIMD vector. pub const fn from_array(array: [T; LANES]) -> Self { - Self(array) + // SAFETY: `[T; LANES]` and `Simd` have the same layout. + unsafe { core::mem::transmute_copy(&array) } } /// Converts a SIMD vector to an array. pub const fn to_array(self) -> [T; LANES] { - self.0 + // SAFETY: `[T; LANES]` and `Simd` have the same layout. + unsafe { core::mem::transmute_copy(&self) } } /// Converts a slice to a SIMD vector containing `slice[..LANES]`. @@ -735,7 +739,7 @@ where { #[inline] fn as_ref(&self) -> &[T; LANES] { - &self.0 + self.as_array() } } @@ -746,7 +750,7 @@ where { #[inline] fn as_mut(&mut self) -> &mut [T; LANES] { - &mut self.0 + self.as_mut_array() } } @@ -758,7 +762,7 @@ where { #[inline] fn as_ref(&self) -> &[T] { - &self.0 + self.as_array() } } @@ -769,7 +773,7 @@ where { #[inline] fn as_mut(&mut self) -> &mut [T] { - &mut self.0 + self.as_mut_array() } }