Skip to content

Commit f2ac32f

Browse files
Merge pull request #361 from rust-lang/wrapping-negation
Add wrapping negation for unsigned integers
2 parents b6e03e5 + 5c97c0d commit f2ac32f

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

crates/core_simd/src/elements/uint.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ pub trait SimdUint: Copy + Sealed {
1616
#[must_use]
1717
fn cast<T: SimdCast>(self) -> Self::Cast<T>;
1818

19+
/// Wrapping negation.
20+
///
21+
/// Like [`u32::wrapping_neg`], all applications of this function will wrap, with the exception
22+
/// of `-0`.
23+
fn wrapping_neg(self) -> Self;
24+
1925
/// Lanewise saturating add.
2026
///
2127
/// # Examples
@@ -74,7 +80,7 @@ pub trait SimdUint: Copy + Sealed {
7480
}
7581

7682
macro_rules! impl_trait {
77-
{ $($ty:ty),* } => {
83+
{ $($ty:ident ($signed:ident)),* } => {
7884
$(
7985
impl<const LANES: usize> Sealed for Simd<$ty, LANES>
8086
where
@@ -95,6 +101,12 @@ macro_rules! impl_trait {
95101
unsafe { intrinsics::simd_as(self) }
96102
}
97103

104+
#[inline]
105+
fn wrapping_neg(self) -> Self {
106+
use crate::simd::SimdInt;
107+
(-self.cast::<$signed>()).cast()
108+
}
109+
98110
#[inline]
99111
fn saturating_add(self, second: Self) -> Self {
100112
// Safety: `self` is a vector
@@ -153,4 +165,4 @@ macro_rules! impl_trait {
153165
}
154166
}
155167

156-
impl_trait! { u8, u16, u32, u64, usize }
168+
impl_trait! { u8 (i8), u16 (i16), u32 (i32), u64 (i64), usize (isize) }

crates/core_simd/tests/ops_macros.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,16 @@ macro_rules! impl_unsigned_tests {
361361
}
362362
}
363363

364+
test_helpers::test_lanes! {
365+
fn wrapping_neg<const LANES: usize>() {
366+
test_helpers::test_unary_elementwise(
367+
&Vector::<LANES>::wrapping_neg,
368+
&Scalar::wrapping_neg,
369+
&|_| true,
370+
);
371+
}
372+
}
373+
364374
impl_binary_op_test!(Scalar, Add::add, AddAssign::add_assign, Scalar::wrapping_add);
365375
impl_binary_op_test!(Scalar, Sub::sub, SubAssign::sub_assign, Scalar::wrapping_sub);
366376
impl_binary_op_test!(Scalar, Mul::mul, MulAssign::mul_assign, Scalar::wrapping_mul);

0 commit comments

Comments
 (0)