feat: Add bit_width for unsigned NonZero<T>
This commit is contained in:
parent
a7b3715826
commit
f4efc370e6
2 changed files with 42 additions and 0 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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…
Add table
Add a link
Reference in a new issue