Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't use direct field access in Simd functions #339

Merged
merged 3 commits into from
Apr 23, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/core_simd/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#![no_std]
#![feature(
const_ptr_read,
const_refs_to_cell,
const_transmute_copy,
convert_float_to_int,
decl_macro,
intra_doc_pointers,
Expand Down
26 changes: 18 additions & 8 deletions crates/core_simd/src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,22 +135,32 @@ where
/// assert_eq!(v.as_array(), &[0, 1, 2, 3]);
/// ```
pub const fn as_array(&self) -> &[T; LANES] {
&self.0
// SAFETY: Transmuting between `Simd<T, LANES>` and `[T; LANES]`
// is always valid and `Simd<T, LANES>` never has a lower alignment
// than `[T; LANES]`.
unsafe { &*(self as *const Self as *const [T; LANES]) }
}

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

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

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

/// Converts a slice to a SIMD vector containing `slice[..LANES]`.
Expand Down Expand Up @@ -735,7 +745,7 @@ where
{
#[inline]
fn as_ref(&self) -> &[T; LANES] {
&self.0
self.as_array()
}
}

Expand All @@ -746,7 +756,7 @@ where
{
#[inline]
fn as_mut(&mut self) -> &mut [T; LANES] {
&mut self.0
self.as_mut_array()
}
}

Expand All @@ -758,7 +768,7 @@ where
{
#[inline]
fn as_ref(&self) -> &[T] {
&self.0
self.as_array()
}
}

Expand All @@ -769,7 +779,7 @@ where
{
#[inline]
fn as_mut(&mut self) -> &mut [T] {
&mut self.0
self.as_mut_array()
}
}

Expand Down