Rollup merge of #125884 - Rua:integer_sign_cast, r=Mark-Simulacrum
Implement feature `integer_sign_cast` Tracking issue: https://github.com/rust-lang/rust/issues/125882 Since this is my first time making a library addition I wasn't sure where to place the new code relative to existing code. I decided to place it near the top where there are already some other basic bitwise manipulation functions. If there is an official guideline for the ordering of functions, please let me know.
This commit is contained in:
commit
890770d7bc
@ -183,6 +183,30 @@ pub const fn trailing_ones(self) -> u32 {
|
||||
(self as $UnsignedT).trailing_ones()
|
||||
}
|
||||
|
||||
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
|
||||
///
|
||||
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
|
||||
/// the same.
|
||||
///
|
||||
/// # 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.
|
||||
///
|
||||
|
@ -184,6 +184,30 @@ pub const fn trailing_ones(self) -> u32 {
|
||||
(!self).trailing_zeros()
|
||||
}
|
||||
|
||||
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
|
||||
///
|
||||
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
|
||||
/// the same.
|
||||
///
|
||||
/// # 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.
|
||||
///
|
||||
|
Loading…
Reference in New Issue
Block a user