Skip to content

Commit fb65716

Browse files
authored
Unrolled build for #142328
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: #142326 This PR adds methods to the primitive unsigned integer types that return the minimum number of bits required to represent an unsigned integer.
2 parents f77bb1b + 199b808 commit fb65716

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

library/core/src/num/uint_macros.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,30 @@ 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!(0b111_", stringify!($SelfT), ".bit_width(), 3);")]
229+
#[doc = concat!("assert_eq!(0b1110_", stringify!($SelfT), ".bit_width(), 4);")]
230+
#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.bit_width(), ", stringify!($BITS), ");")]
231+
/// ```
232+
#[unstable(feature = "uint_bit_width", issue = "142326")]
233+
#[must_use = "this returns the result of the operation, \
234+
without modifying the original"]
235+
#[inline(always)]
236+
pub const fn bit_width(self) -> u32 {
237+
Self::BITS - self.leading_zeros()
238+
}
239+
216240
/// Returns `self` with only the most significant bit set, or `0` if
217241
/// the input is `0`.
218242
///

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)