Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement feature integer_sign_cast #125884

Merged
merged 2 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 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,30 @@ 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
Rua marked this conversation as resolved.
Show resolved Hide resolved
/// is refactored.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(integer_sign_cast)]
///
#[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
24 changes: 24 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,30 @@ 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:
///
/// ```
/// #![feature(integer_sign_cast)]
///
#[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
Loading