Skip to content

Commit

Permalink
Implement feature integer_sign_cast
Browse files Browse the repository at this point in the history
  • Loading branch information
Rua committed Jun 2, 2024
1 parent a83cf56 commit 37af787
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
22 changes: 22 additions & 0 deletions library/core/src/num/int_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,28 @@ macro_rules! int_impl {
(self as $UnsignedT).trailing_ones()
}

/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This is a bit safer than `as` because it wouldn't silently change the size if the code
/// is refactored.
///
/// # Examples
///
/// Basic usage:
///
/// ```
#[doc = concat!("let n = -1", stringify!($SelfT), ";")]
///
#[doc = concat!("assert_eq!(n.cast_unsigned(), ", stringify!($UnsignedT), "::MAX);")]
/// ```
#[unstable(feature = "integer_sign_cast", issue = "125882")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> $UnsignedT {
self as $UnsignedT
}

/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
Expand Down
22 changes: 22 additions & 0 deletions library/core/src/num/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,28 @@ macro_rules! uint_impl {
(!self).trailing_zeros()
}

/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This is a bit safer than `as` because it wouldn't silently change the size if the code
/// is refactored.
///
/// # Examples
///
/// Basic usage:
///
/// ```
#[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
///
#[doc = concat!("assert_eq!(n.cast_signed(), -1", stringify!($SignedT), ");")]
/// ```
#[unstable(feature = "integer_sign_cast", issue = "125882")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> $SignedT {
self as $SignedT
}

/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
Expand Down

0 comments on commit 37af787

Please sign in to comment.