about summary refs log tree commit diff
path: root/library/core/src/num
diff options
context:
space:
mode:
authorShun Sakai <sorairolake@protonmail.ch>2025-06-07 22:38:30 +0900
committerShun Sakai <sorairolake@protonmail.ch>2025-06-11 11:15:37 +0900
commit199b80887043acdc029558f3739c094bdfd72b6a (patch)
tree06288d63ce5aa44fb1053ede88346d2c8ee03c40 /library/core/src/num
parent1677d46cb128cc8f285dbd32b0dc4d7a46437050 (diff)
feat: Add `bit_width` for unsigned integer types
Diffstat (limited to 'library/core/src/num')
-rw-r--r--library/core/src/num/uint_macros.rs24
1 files changed, 24 insertions, 0 deletions
diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs
index 5f82e6af86b..4ee0e7326b3 100644
--- a/library/core/src/num/uint_macros.rs
+++ b/library/core/src/num/uint_macros.rs
@@ -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`.
         ///