Skip to content

Implement BITS constant for non-zero integers #93292

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

Merged
merged 2 commits into from
Mar 13, 2022
Merged
Changes from all commits
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
40 changes: 39 additions & 1 deletion library/core/src/num/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ macro_rules! nonzero_unsigned_operations {
without modifying the original"]
#[inline]
pub const fn log2(self) -> u32 {
<$Int>::BITS - 1 - self.leading_zeros()
Self::BITS - 1 - self.leading_zeros()
}

/// Returns the base 10 logarithm of the number, rounded down.
Expand Down Expand Up @@ -1090,3 +1090,41 @@ nonzero_min_max_signed! {
NonZeroI128(i128);
NonZeroIsize(isize);
}

macro_rules! nonzero_bits {
( $( $Ty: ident($Int: ty); )+ ) => {
$(
impl $Ty {
/// The size of this non-zero integer type in bits.
///
#[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
///
/// # Examples
///
/// ```
/// #![feature(nonzero_bits)]
#[doc = concat!("# use std::num::", stringify!($Ty), ";")]
///
#[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
/// ```
#[unstable(feature = "nonzero_bits", issue = "94881")]
pub const BITS: u32 = <$Int>::BITS;
}
)+
}
}

nonzero_bits! {
NonZeroU8(u8);
NonZeroI8(i8);
NonZeroU16(u16);
NonZeroI16(i16);
NonZeroU32(u32);
NonZeroI32(i32);
NonZeroU64(u64);
NonZeroI64(i64);
NonZeroU128(u128);
NonZeroI128(i128);
NonZeroUsize(usize);
NonZeroIsize(isize);
}