feat: Change return type of `NonZero::bit_width`
Return `NonZero<u32>` instead of `u32`.
diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs
index baabf1d..30c3fb8 100644
--- a/library/core/src/num/nonzero.rs
+++ b/library/core/src/num/nonzero.rs
@@ -1789,8 +1789,9 @@ pub const fn cast_signed(self) -> NonZero<$Sint> {
/// #
/// # 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);")]
+ #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.bit_width(), NonZero::new(1)?);")]
+ #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b111)?.bit_width(), NonZero::new(3)?);")]
+ #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b1110)?.bit_width(), NonZero::new(4)?);")]
/// # Some(())
/// # }
/// ```
@@ -1798,8 +1799,10 @@ pub const fn cast_signed(self) -> NonZero<$Sint> {
#[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()
+ pub const fn bit_width(self) -> NonZero<u32> {
+ // SAFETY: Since `self.leading_zeros()` is always less than
+ // `Self::BITS`, this subtraction can never be zero.
+ unsafe { NonZero::new_unchecked(Self::BITS - self.leading_zeros()) }
}
};
diff --git a/library/coretests/tests/nonzero.rs b/library/coretests/tests/nonzero.rs
index 4bcc61d..c368a26 100644
--- a/library/coretests/tests/nonzero.rs
+++ b/library/coretests/tests/nonzero.rs
@@ -577,10 +577,10 @@ 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);
+ assert_eq!(NonZero::<$T>::new(0b010_1100).unwrap().bit_width(), NonZero::new(6).unwrap());
+ assert_eq!(NonZero::<$T>::new(0b111_1001).unwrap().bit_width(), NonZero::new(7).unwrap());
+ assert_eq!(NonZero::<$T>::MIN.bit_width(), NonZero::new(1).unwrap());
+ assert_eq!(NonZero::<$T>::MAX.bit_width(), NonZero::new(<$T>::BITS).unwrap());
}
)+
};