Skip to content

Commit a25950d

Browse files
committed
feat: Change return type of NonZero::bit_width
Return `NonZero<u32>` instead of `u32`.
1 parent f4efc37 commit a25950d

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

library/core/src/num/nonzero.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,17 +1789,20 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
17891789
/// #
17901790
/// # fn main() { test().unwrap(); }
17911791
/// # fn test() -> Option<()> {
1792-
#[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b111)?.bit_width(), 3);")]
1793-
#[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b1110)?.bit_width(), 4);")]
1792+
#[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.bit_width(), NonZero::new(1)?);")]
1793+
#[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b111)?.bit_width(), NonZero::new(3)?);")]
1794+
#[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0b1110)?.bit_width(), NonZero::new(4)?);")]
17941795
/// # Some(())
17951796
/// # }
17961797
/// ```
17971798
#[unstable(feature = "uint_bit_width", issue = "142326")]
17981799
#[must_use = "this returns the result of the operation, \
17991800
without modifying the original"]
18001801
#[inline(always)]
1801-
pub const fn bit_width(self) -> u32 {
1802-
Self::BITS - self.leading_zeros()
1802+
pub const fn bit_width(self) -> NonZero<u32> {
1803+
// SAFETY: Since `self.leading_zeros()` is always less than
1804+
// `Self::BITS`, this subtraction can never be zero.
1805+
unsafe { NonZero::new_unchecked(Self::BITS - self.leading_zeros()) }
18031806
}
18041807
};
18051808

library/coretests/tests/nonzero.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -577,10 +577,10 @@ fn test_nonzero_bit_width() {
577577
($($T:ty),+) => {
578578
$(
579579
{
580-
assert_eq!(NonZero::<$T>::new(0b010_1100).unwrap().bit_width(), 6);
581-
assert_eq!(NonZero::<$T>::new(0b111_1001).unwrap().bit_width(), 7);
582-
assert_eq!(NonZero::<$T>::MIN.bit_width(), 1);
583-
assert_eq!(NonZero::<$T>::MAX.bit_width(), <$T>::BITS);
580+
assert_eq!(NonZero::<$T>::new(0b010_1100).unwrap().bit_width(), NonZero::new(6).unwrap());
581+
assert_eq!(NonZero::<$T>::new(0b111_1001).unwrap().bit_width(), NonZero::new(7).unwrap());
582+
assert_eq!(NonZero::<$T>::MIN.bit_width(), NonZero::new(1).unwrap());
583+
assert_eq!(NonZero::<$T>::MAX.bit_width(), NonZero::new(<$T>::BITS).unwrap());
584584
}
585585
)+
586586
};

0 commit comments

Comments
 (0)