Skip to content

feat: Add bit_width for unsigned integer types #142328

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 11, 2025
Merged
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/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
///
Expand Down
1 change: 1 addition & 0 deletions library/coretests/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions library/coretests/tests/num/uint_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading