Skip to content

Commit b3404d2

Browse files
committed
feat: Add bit_width for unsigned integer types
1 parent 1677d46 commit b3404d2

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

library/core/src/num/uint_macros.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,29 @@ macro_rules! uint_impl {
213213
(!self).trailing_zeros()
214214
}
215215

216+
/// Returns the minimum number of bits required to represent `self`.
217+
///
218+
/// This method returns zero if `self` is zero.
219+
///
220+
/// # Examples
221+
///
222+
/// Basic usage:
223+
///
224+
/// ```
225+
/// #![feature(uint_bit_width)]
226+
///
227+
#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".bit_width(), 0);")]
228+
#[doc = concat!("assert_eq!(7", stringify!($SelfT), ".bit_width(), 3);")]
229+
#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.bit_width(), ", stringify!($BITS), ");")]
230+
/// ```
231+
#[unstable(feature = "uint_bit_width", issue = "142326")]
232+
#[must_use = "this returns the result of the operation, \
233+
without modifying the original"]
234+
#[inline(always)]
235+
pub const fn bit_width(self) -> u32 {
236+
Self::BITS - self.leading_zeros()
237+
}
238+
216239
/// Returns `self` with only the most significant bit set, or `0` if
217240
/// the input is `0`.
218241
///

library/coretests/tests/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@
9494
#![feature(try_blocks)]
9595
#![feature(try_find)]
9696
#![feature(try_trait_v2)]
97+
#![feature(uint_bit_width)]
9798
#![feature(unsize)]
9899
#![feature(unwrap_infallible)]
99100
// tidy-alphabetical-end

library/coretests/tests/num/uint_macros.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,14 @@ macro_rules! uint_module {
7272
assert_eq_const_safe!(u32: X.trailing_ones(), 0);
7373
}
7474

75+
fn test_bit_width() {
76+
assert_eq_const_safe!(u32: A.bit_width(), 6);
77+
assert_eq_const_safe!(u32: B.bit_width(), 6);
78+
assert_eq_const_safe!(u32: C.bit_width(), 7);
79+
assert_eq_const_safe!(u32: _0.bit_width(), 0);
80+
assert_eq_const_safe!(u32: _1.bit_width(), $T::BITS);
81+
}
82+
7583
fn test_rotate() {
7684
assert_eq_const_safe!($T: A.rotate_left(6).rotate_right(2).rotate_right(4), A);
7785
assert_eq_const_safe!($T: B.rotate_left(3).rotate_left(2).rotate_right(5), B);

0 commit comments

Comments
 (0)