Skip to content

Commit 37af787

Browse files
committed
Implement feature integer_sign_cast
1 parent a83cf56 commit 37af787

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

library/core/src/num/int_macros.rs

+22
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,28 @@ macro_rules! int_impl {
183183
(self as $UnsignedT).trailing_ones()
184184
}
185185

186+
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
187+
///
188+
/// This is a bit safer than `as` because it wouldn't silently change the size if the code
189+
/// is refactored.
190+
///
191+
/// # Examples
192+
///
193+
/// Basic usage:
194+
///
195+
/// ```
196+
#[doc = concat!("let n = -1", stringify!($SelfT), ";")]
197+
///
198+
#[doc = concat!("assert_eq!(n.cast_unsigned(), ", stringify!($UnsignedT), "::MAX);")]
199+
/// ```
200+
#[unstable(feature = "integer_sign_cast", issue = "125882")]
201+
#[must_use = "this returns the result of the operation, \
202+
without modifying the original"]
203+
#[inline(always)]
204+
pub const fn cast_unsigned(self) -> $UnsignedT {
205+
self as $UnsignedT
206+
}
207+
186208
/// Shifts the bits to the left by a specified amount, `n`,
187209
/// wrapping the truncated bits to the end of the resulting integer.
188210
///

library/core/src/num/uint_macros.rs

+22
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,28 @@ macro_rules! uint_impl {
184184
(!self).trailing_zeros()
185185
}
186186

187+
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
188+
///
189+
/// This is a bit safer than `as` because it wouldn't silently change the size if the code
190+
/// is refactored.
191+
///
192+
/// # Examples
193+
///
194+
/// Basic usage:
195+
///
196+
/// ```
197+
#[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
198+
///
199+
#[doc = concat!("assert_eq!(n.cast_signed(), -1", stringify!($SignedT), ");")]
200+
/// ```
201+
#[unstable(feature = "integer_sign_cast", issue = "125882")]
202+
#[must_use = "this returns the result of the operation, \
203+
without modifying the original"]
204+
#[inline(always)]
205+
pub const fn cast_signed(self) -> $SignedT {
206+
self as $SignedT
207+
}
208+
187209
/// Shifts the bits to the left by a specified amount, `n`,
188210
/// wrapping the truncated bits to the end of the resulting integer.
189211
///

0 commit comments

Comments
 (0)