diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 8cd8b0850e947..baabf1d90b88a 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -1777,6 +1777,30 @@ macro_rules! nonzero_integer_signedness_dependent_methods { // SAFETY: `self.get()` can't be zero unsafe { NonZero::new_unchecked(self.get().cast_signed()) } } + + /// Returns the minimum number of bits required to represent `self`. + /// + /// # Examples + /// + /// ``` + /// #![feature(uint_bit_width)] + /// + /// # use core::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b111)?.bit_width(), 3);")] + #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b1110)?.bit_width(), 4);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "uint_bit_width", issue = "142326")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn bit_width(self) -> u32 { + Self::BITS - self.leading_zeros() + } }; // Associated items for signed nonzero types only. diff --git a/library/coretests/tests/nonzero.rs b/library/coretests/tests/nonzero.rs index 69e4ed9c36b3a..4bcc61de8dcad 100644 --- a/library/coretests/tests/nonzero.rs +++ b/library/coretests/tests/nonzero.rs @@ -570,3 +570,21 @@ fn test_nonzero_lowest_one() { nonzero_int_impl!(i8, i16, i32, i64, i128, isize); nonzero_uint_impl!(u8, u16, u32, u64, u128, usize); } + +#[test] +fn test_nonzero_bit_width() { + macro_rules! nonzero_uint_impl { + ($($T:ty),+) => { + $( + { + assert_eq!(NonZero::<$T>::new(0b010_1100).unwrap().bit_width(), 6); + assert_eq!(NonZero::<$T>::new(0b111_1001).unwrap().bit_width(), 7); + assert_eq!(NonZero::<$T>::MIN.bit_width(), 1); + assert_eq!(NonZero::<$T>::MAX.bit_width(), <$T>::BITS); + } + )+ + }; + } + + nonzero_uint_impl!(u8, u16, u32, u64, u128, usize); +}