Skip to content

Commit f4efc37

Browse files
committed
feat: Add bit_width for unsigned NonZero<T>
1 parent a7b3715 commit f4efc37

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

library/core/src/num/nonzero.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1777,6 +1777,30 @@ macro_rules! nonzero_integer_signedness_dependent_methods {
17771777
// SAFETY: `self.get()` can't be zero
17781778
unsafe { NonZero::new_unchecked(self.get().cast_signed()) }
17791779
}
1780+
1781+
/// Returns the minimum number of bits required to represent `self`.
1782+
///
1783+
/// # Examples
1784+
///
1785+
/// ```
1786+
/// #![feature(uint_bit_width)]
1787+
///
1788+
/// # use core::num::NonZero;
1789+
/// #
1790+
/// # fn main() { test().unwrap(); }
1791+
/// # 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);")]
1794+
/// # Some(())
1795+
/// # }
1796+
/// ```
1797+
#[unstable(feature = "uint_bit_width", issue = "142326")]
1798+
#[must_use = "this returns the result of the operation, \
1799+
without modifying the original"]
1800+
#[inline(always)]
1801+
pub const fn bit_width(self) -> u32 {
1802+
Self::BITS - self.leading_zeros()
1803+
}
17801804
};
17811805

17821806
// Associated items for signed nonzero types only.

library/coretests/tests/nonzero.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,3 +570,21 @@ fn test_nonzero_lowest_one() {
570570
nonzero_int_impl!(i8, i16, i32, i64, i128, isize);
571571
nonzero_uint_impl!(u8, u16, u32, u64, u128, usize);
572572
}
573+
574+
#[test]
575+
fn test_nonzero_bit_width() {
576+
macro_rules! nonzero_uint_impl {
577+
($($T:ty),+) => {
578+
$(
579+
{
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);
584+
}
585+
)+
586+
};
587+
}
588+
589+
nonzero_uint_impl!(u8, u16, u32, u64, u128, usize);
590+
}

0 commit comments

Comments
 (0)