Skip to content
Closed
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
72 changes: 72 additions & 0 deletions crates/core_simd/src/permute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,78 @@ macro_rules! impl_shuffle_lane {
self.shuffle::<{ idx() }>(self)
}

/// Rotate a vector to the left `N` times.
///
/// # Examples
///
/// ```
/// # use core_simd::SimdU32;
/// let a = SimdU32::from_array([0, 1, 2, 3, 4]);
/// let b = SimdU32::from_array([2, 3, 4, 0, 1]);
/// assert_eq!(a.rotate_left::<{2}>(), b);
/// ```
#[inline]
pub fn rotate_left<const N: u32>(self) -> Self {
const fn idx() -> [u32; $n] {
let mut base = [0u32; $n];
let mut i = 0;
while i < $n {
base[i] = i as u32;
i += 1;
}
let mut i = 0;
while i < N {
let temp = base[0];
let mut j = 0;
while j < $n - 1 {
base[j] = base[j + 1];
j += 1;
}
base[$n - 1] = temp;
i += 1;
}
base
}

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

/// Rotate a vector to the right `N` times.
///
/// # Examples
///
/// ```
/// # use core_simd::SimdU32;
/// let a = SimdU32::from_array([0, 1, 2, 3, 4]);
/// let b = SimdU32::from_array([3, 4, 0, 1, 2]);
/// assert_eq!(a.rotate_left::<{2}>(), b);
/// ```
#[inline]
pub fn rotate_right<const N: u32>(self) -> Self {
const fn idx() -> [u32; $n] {
let mut base = [0u32; $n];
let mut i = 0;
while i < $n {
base[i] = i as u32;
i += 1;
}
let mut i = 0;
while i < N {
let last = base[$n - 1];
let mut j = ($n - 2) as i32;
while j >= 0 {
base[(j + 1) as usize] = base[j as usize];
j -= 1;
}
base[0] = last;
i += 1;
}
base
}

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

/// Interleave two vectors.
///
/// Produces two vectors with lanes taken alternately from `self` and `other`.
Expand Down
24 changes: 24 additions & 0 deletions crates/core_simd/tests/permute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,27 @@ fn interleave() {
assert_eq!(even, a);
assert_eq!(odd, b);
}

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

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