Skip to content

Commit a79b9ba

Browse files
joshtriplettgitbot
authored and
gitbot
committed
Add cast_signed and cast_unsigned methods for NonZero types
1 parent fc5034d commit a79b9ba

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

core/src/num/nonzero.rs

+47
Original file line numberDiff line numberDiff line change
@@ -1626,6 +1626,29 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
16261626
// results will be sqrt(1), which is 1, so a result can't be zero.
16271627
unsafe { Self::new_unchecked(result) }
16281628
}
1629+
1630+
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
1631+
///
1632+
/// # Examples
1633+
///
1634+
/// Basic usage:
1635+
///
1636+
/// ```
1637+
/// #![feature(integer_sign_cast)]
1638+
/// # use std::num::NonZero;
1639+
///
1640+
#[doc = concat!("let n = NonZero::<", stringify!($Int), ">::MAX;")]
1641+
///
1642+
#[doc = concat!("assert_eq!(n.cast_signed(), NonZero::new(-1", stringify!($Sint), ").unwrap());")]
1643+
/// ```
1644+
#[unstable(feature = "integer_sign_cast", issue = "125882")]
1645+
#[must_use = "this returns the result of the operation, \
1646+
without modifying the original"]
1647+
#[inline(always)]
1648+
pub const fn cast_signed(self) -> NonZero<$Sint> {
1649+
// SAFETY: `self.get()` can't be zero
1650+
unsafe { NonZero::new_unchecked(self.get().cast_signed()) }
1651+
}
16291652
};
16301653

16311654
// Associated items for signed nonzero types only.
@@ -2042,6 +2065,30 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
20422065
// SAFETY: negation of nonzero cannot yield zero values.
20432066
unsafe { Self::new_unchecked(result) }
20442067
}
2068+
2069+
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
2070+
///
2071+
/// # Examples
2072+
///
2073+
/// Basic usage:
2074+
///
2075+
/// ```
2076+
/// #![feature(integer_sign_cast)]
2077+
/// # use std::num::NonZero;
2078+
///
2079+
#[doc = concat!("let n = NonZero::new(-1", stringify!($Int), ").unwrap();")]
2080+
///
2081+
#[doc = concat!("assert_eq!(n.cast_unsigned(), NonZero::<", stringify!($Uint), ">::MAX);")]
2082+
/// ```
2083+
#[unstable(feature = "integer_sign_cast", issue = "125882")]
2084+
#[must_use = "this returns the result of the operation, \
2085+
without modifying the original"]
2086+
#[inline(always)]
2087+
pub const fn cast_unsigned(self) -> NonZero<$Uint> {
2088+
// SAFETY: `self.get()` can't be zero
2089+
unsafe { NonZero::new_unchecked(self.get().cast_unsigned()) }
2090+
}
2091+
20452092
};
20462093
}
20472094

0 commit comments

Comments
 (0)