Skip to content

Commit fb91bf0

Browse files
authored
Rollup merge of rust-lang#93292 - nvzqz:nonzero-bits, r=dtolnay
Implement `BITS` constant for non-zero integers This adds the associated [`BITS`](https://doc.rust-lang.org/stable/std/primitive.usize.html#associatedconstant.BITS) constant to `NonZero{U,I}{8,16,32,64,128,size}`. This is useful when a type alias refers to either a regular or non-zero integer.
2 parents 454ef16 + 522a73e commit fb91bf0

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

core/src/num/nonzero.rs

+39-1
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,7 @@ macro_rules! nonzero_unsigned_operations {
465465
without modifying the original"]
466466
#[inline]
467467
pub const fn log2(self) -> u32 {
468-
<$Int>::BITS - 1 - self.leading_zeros()
468+
Self::BITS - 1 - self.leading_zeros()
469469
}
470470

471471
/// Returns the base 10 logarithm of the number, rounded down.
@@ -1090,3 +1090,41 @@ nonzero_min_max_signed! {
10901090
NonZeroI128(i128);
10911091
NonZeroIsize(isize);
10921092
}
1093+
1094+
macro_rules! nonzero_bits {
1095+
( $( $Ty: ident($Int: ty); )+ ) => {
1096+
$(
1097+
impl $Ty {
1098+
/// The size of this non-zero integer type in bits.
1099+
///
1100+
#[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
1101+
///
1102+
/// # Examples
1103+
///
1104+
/// ```
1105+
/// #![feature(nonzero_bits)]
1106+
#[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1107+
///
1108+
#[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
1109+
/// ```
1110+
#[unstable(feature = "nonzero_bits", issue = "94881")]
1111+
pub const BITS: u32 = <$Int>::BITS;
1112+
}
1113+
)+
1114+
}
1115+
}
1116+
1117+
nonzero_bits! {
1118+
NonZeroU8(u8);
1119+
NonZeroI8(i8);
1120+
NonZeroU16(u16);
1121+
NonZeroI16(i16);
1122+
NonZeroU32(u32);
1123+
NonZeroI32(i32);
1124+
NonZeroU64(u64);
1125+
NonZeroI64(i64);
1126+
NonZeroU128(u128);
1127+
NonZeroI128(i128);
1128+
NonZeroUsize(usize);
1129+
NonZeroIsize(isize);
1130+
}

0 commit comments

Comments
 (0)