Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions library/core/src/num/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 18 additions & 0 deletions library/coretests/tests/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Loading