Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
52 changes: 52 additions & 0 deletions crates/core_simd/src/permute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,58 @@ macro_rules! impl_shuffle_lane {
}
(self.shuffle::<{ even() }>(other), self.shuffle::<{ odd() }>(other))
}

/// Shift a vector `N` times to the left and fill the rest with zeroes.
///
/// # Examples
///
/// ```
/// # use core_simd::SimdU32;
/// let a = SimdU32::from_array([0, 1, 2, 3]);
/// let b = SimdU32::from_array([2, 3, 0, 0]);
/// assert_eq!(a.shift_left::<{2}>(), b);
/// ```
#[inline]
pub fn shift_left<const N: u32>(self) -> Self {
const fn idx() -> [u32; $n] {
let mut base = [$n; $n];
let mut i = N;
while i < $n {
base[i - 2] += N;
i += 1;
}
base
}
let zeroed = Self::default();

self.shuffle::<{ idx() }>(zeroed)
}

/// Shift a vector `N` times to the right and fill the rest with zeroes.
///
/// # Examples
///
/// ```
/// # use core_simd::SimdU32;
/// let a = SimdU32::from_array([0, 1, 2, 3]);
/// let b = SimdU32::from_array([0, 0, 0, 1]);
/// assert_eq!(a.shift_right::<{2}>(), b);
/// ```
#[inline]
pub fn shift_right<const N: u32>(self) -> Self {
const fn idx() -> [u32; $n] {
let mut base = [$n; $n];
let mut i = N;
while i < $n {
base[i] += N;
i += 1;
}
base
}
let zeroed = Self::default();

self.shuffle::<{ idx() }>(zeroed)
}
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions crates/core_simd/tests/permute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,25 @@ fn interleave() {
assert_eq!(even, a);
assert_eq!(odd, b);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn shift_left() {
let a = SimdU32::from_array([0, 1, 2, 3]);
let b = SimdU32::from_array([2, 3, 0, 0]);
assert_eq!(a.shift_left::<{ 2 }>(), b);
let b = SimdU32::from_array([0, 0, 0, 0]);
assert_eq!(a.shift_left::<{ 5 }>(), b);
assert_eq!(a.shift_left::<{ 0 }>(), a);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn shift_right() {
let a = SimdU32::from_array([0, 1, 2, 3]);
let b = SimdU32::from_array([0, 0, 0, 1]);
assert_eq!(a.shift_right::<{ 2 }>(), b);
let b = SimdU32::from_array([0, 0, 0, 0]);
assert_eq!(a.shift_right::<{ 5 }>(), b);
assert_eq!(a.shift_right::<{ 0 }>(), a);
}