Rollup merge of #142328 - sorairolake:feature/uint-bit-width, r=tgross35

feat: Add `bit_width` for unsigned integer types

- Accepted ACP: rust-lang/libs-team#598
- Tracking issue: rust-lang/rust#142326

This PR adds methods to the primitive unsigned integer types that return the minimum number of bits required to represent an unsigned integer.
This commit is contained in:
Matthias Krüger 2025-06-11 13:48:13 +02:00 committed by GitHub
commit 583a6e2de7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 33 additions and 0 deletions

View file

@ -213,6 +213,30 @@ macro_rules! uint_impl {
(!self).trailing_zeros()
}
/// Returns the minimum number of bits required to represent `self`.
///
/// This method returns zero if `self` is zero.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(uint_bit_width)]
///
#[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".bit_width(), 0);")]
#[doc = concat!("assert_eq!(0b111_", stringify!($SelfT), ".bit_width(), 3);")]
#[doc = concat!("assert_eq!(0b1110_", stringify!($SelfT), ".bit_width(), 4);")]
#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.bit_width(), ", stringify!($BITS), ");")]
/// ```
#[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()
}
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///

View file

@ -94,6 +94,7 @@
#![feature(try_blocks)]
#![feature(try_find)]
#![feature(try_trait_v2)]
#![feature(uint_bit_width)]
#![feature(unsize)]
#![feature(unwrap_infallible)]
// tidy-alphabetical-end

View file

@ -72,6 +72,14 @@ macro_rules! uint_module {
assert_eq_const_safe!(u32: X.trailing_ones(), 0);
}
fn test_bit_width() {
assert_eq_const_safe!(u32: A.bit_width(), 6);
assert_eq_const_safe!(u32: B.bit_width(), 6);
assert_eq_const_safe!(u32: C.bit_width(), 7);
assert_eq_const_safe!(u32: _0.bit_width(), 0);
assert_eq_const_safe!(u32: _1.bit_width(), $T::BITS);
}
fn test_rotate() {
assert_eq_const_safe!($T: A.rotate_left(6).rotate_right(2).rotate_right(4), A);
assert_eq_const_safe!($T: B.rotate_left(3).rotate_left(2).rotate_right(5), B);