From 1d13de686706f48f9da30b5640dd16b357df2806 Mon Sep 17 00:00:00 2001 From: Nikolai Vazquez Date: Sat, 12 Mar 2022 08:00:45 -0500 Subject: [PATCH 1/2] Implement `BITS` constant for non-zero integers --- library/core/src/num/nonzero.rs | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 5bdd78aa2dea4..05e53175873d4 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -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); +} From 6b5acf0d4063fc726f68fcd444140ffd576b7304 Mon Sep 17 00:00:00 2001 From: Nikolai Vazquez Date: Sat, 12 Mar 2022 08:01:35 -0500 Subject: [PATCH 2/2] Use `Self::BITS` in `log2` implementation --- library/core/src/num/nonzero.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 05e53175873d4..c36529314784e 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -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.