]> git.lizzy.rs Git - rust.git/commitdiff
Rollup merge of #76492 - fusion-engineering-forks:int-bits, r=dtolnay
authorRalf Jung <post@ralfj.de>
Sat, 19 Sep 2020 09:47:45 +0000 (11:47 +0200)
committerGitHub <noreply@github.com>
Sat, 19 Sep 2020 09:47:45 +0000 (11:47 +0200)
Add associated constant `BITS` to all integer types

Recently I've regularly come across this snippet (in a few different crates, including `core` and `std`):
```rust
std::mem::size_of<usize>() * 8
```

I think it's time for a `usize::BITS`.

18 files changed:
compiler/rustc_data_structures/src/lib.rs
compiler/rustc_data_structures/src/tagged_ptr/copy.rs
library/alloc/src/collections/binary_heap.rs
library/alloc/src/lib.rs
library/alloc/src/raw_vec.rs
library/alloc/tests/lib.rs
library/alloc/tests/string.rs
library/alloc/tests/vec.rs
library/core/src/fmt/mod.rs
library/core/src/num/bignum.rs
library/core/src/num/mod.rs
library/core/src/slice/sort.rs
library/core/tests/iter.rs
library/core/tests/lib.rs
library/core/tests/num/int_macros.rs
library/core/tests/num/uint_macros.rs
library/panic_unwind/src/dwarf/mod.rs
library/panic_unwind/src/lib.rs

index 88c160e93b66a618eed378141e8314f18aaa7ee7..06718cc9803127f2e9e50a4011963c2eaf0db16a 100644 (file)
@@ -14,6 +14,7 @@
 #![feature(generators)]
 #![feature(generator_trait)]
 #![feature(fn_traits)]
+#![feature(int_bits_const)]
 #![feature(min_specialization)]
 #![feature(optin_builtin_traits)]
 #![feature(nll)]
index d39d146db318f230f11e8ff1ae909c14e2e47175..d63bcdb3c2b0425d4993010dccc6fb0aee679cab 100644 (file)
@@ -48,7 +48,7 @@ impl<P, T, const COMPARE_PACKED: bool> CopyTaggedPtr<P, T, COMPARE_PACKED>
     P: Pointer,
     T: Tag,
 {
-    const TAG_BIT_SHIFT: usize = (8 * std::mem::size_of::<usize>()) - T::BITS;
+    const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS;
     const ASSERTION: () = {
         assert!(T::BITS <= P::BITS);
         // Used for the transmute_copy's below
index 24d17fdd880ba8bc9585f93ce7c4e08dbaf7b59e..8a7dd9d4249a8b66a802cdb2e30db6abee59213e 100644 (file)
 
 use core::fmt;
 use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen};
-use core::mem::{self, size_of, swap, ManuallyDrop};
+use core::mem::{self, swap, ManuallyDrop};
 use core::ops::{Deref, DerefMut};
 use core::ptr;
 
@@ -617,7 +617,7 @@ pub fn append(&mut self, other: &mut Self) {
 
         #[inline(always)]
         fn log2_fast(x: usize) -> usize {
-            8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
+            (usize::BITS - x.leading_zeros() - 1) as usize
         }
 
         // `rebuild` takes O(len1 + len2) operations
index 7881c101f9f60f496f1b6f62b525c7cb330a2a2b..f3c1eee47c7216ac1d1036e8b4d858326738e2e8 100644 (file)
 #![feature(fn_traits)]
 #![feature(fundamental)]
 #![feature(inplace_iteration)]
+#![feature(int_bits_const)]
 #![feature(lang_items)]
 #![feature(layout_for_ptr)]
 #![feature(libc)]
index 05382d0b5594edfece3d193fb5d1698b8fdcdab0..62675665f037f39da3c680db2e7338f6fdc83071 100644 (file)
@@ -528,7 +528,7 @@ fn drop(&mut self) {
 
 #[inline]
 fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
-    if mem::size_of::<usize>() < 8 && alloc_size > isize::MAX as usize {
+    if usize::BITS < 64 && alloc_size > isize::MAX as usize {
         Err(CapacityOverflow)
     } else {
         Ok(())
index 03737e1ef1f4dcd4d8be3439edffbd365ea8741f..3ee0cfbe74759862a6da591141abb1b85a931808 100644 (file)
@@ -18,6 +18,7 @@
 #![feature(deque_range)]
 #![feature(inplace_iteration)]
 #![feature(iter_map_while)]
+#![feature(int_bits_const)]
 
 use std::collections::hash_map::DefaultHasher;
 use std::hash::{Hash, Hasher};
index 4e6043541226f77310e96628c9b23a7a5026354e..a6e41b21b618c8d841d510c73fcba95e24028993 100644 (file)
@@ -1,6 +1,5 @@
 use std::borrow::Cow;
 use std::collections::TryReserveError::*;
-use std::mem::size_of;
 use std::ops::Bound::*;
 
 pub trait IntoCow<'a, B: ?Sized>
@@ -605,7 +604,7 @@ fn test_try_reserve() {
     // on 64-bit, we assume the OS will give an OOM for such a ridiculous size.
     // Any platform that succeeds for these requests is technically broken with
     // ptr::offset because LLVM is the worst.
-    let guards_against_isize = size_of::<usize>() < 8;
+    let guards_against_isize = usize::BITS < 64;
 
     {
         // Note: basic stuff is checked by test_reserve
@@ -686,7 +685,7 @@ fn test_try_reserve_exact() {
     const MAX_CAP: usize = isize::MAX as usize;
     const MAX_USIZE: usize = usize::MAX;
 
-    let guards_against_isize = size_of::<usize>() < 8;
+    let guards_against_isize = usize::BITS < 64;
 
     {
         let mut empty_string: String = String::new();
index 368ca4c543219a50d0d8e8a601185eeea7d4c5da..a49ca7c256a75697ff19c6c7aad7738e730a7cfa 100644 (file)
@@ -1341,7 +1341,7 @@ fn test_try_reserve() {
     // on 64-bit, we assume the OS will give an OOM for such a ridiculous size.
     // Any platform that succeeds for these requests is technically broken with
     // ptr::offset because LLVM is the worst.
-    let guards_against_isize = size_of::<usize>() < 8;
+    let guards_against_isize = usize::BITS < 64;
 
     {
         // Note: basic stuff is checked by test_reserve
index 48b7f2739eeb29b9ac47958bdb14d13bf3acf06d..8558cb5a5e8a32ebadc1f8c3becb89f78f73f3c5 100644 (file)
@@ -2086,7 +2086,7 @@ fn fmt(&self, f: &mut Formatter<'_>) -> Result {
             f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
 
             if f.width.is_none() {
-                f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
+                f.width = Some((usize::BITS / 4) as usize + 2);
             }
         }
         f.flags |= 1 << (FlagV1::Alternate as u32);
index 6f16b93d0488aa6278a24591f6a5c952e828f86d..6a1a1e1976160077f340cf17664a8a8f4434cf85 100644 (file)
@@ -20,7 +20,6 @@
 #![macro_use]
 
 use crate::intrinsics;
-use crate::mem;
 
 /// Arithmetic operations required by bignums.
 pub trait FullOps: Sized {
@@ -58,25 +57,22 @@ fn full_mul(self, other: $ty, carry: $ty) -> ($ty, $ty) {
                     // This cannot overflow;
                     // the output is between `0` and `2^nbits * (2^nbits - 1)`.
                     // FIXME: will LLVM optimize this into ADC or similar?
-                    let nbits = mem::size_of::<$ty>() * 8;
                     let v = (self as $bigty) * (other as $bigty) + (carry as $bigty);
-                    ((v >> nbits) as $ty, v as $ty)
+                    ((v >> <$ty>::BITS) as $ty, v as $ty)
                 }
 
                 fn full_mul_add(self, other: $ty, other2: $ty, carry: $ty) -> ($ty, $ty) {
                     // This cannot overflow;
                     // the output is between `0` and `2^nbits * (2^nbits - 1)`.
-                    let nbits = mem::size_of::<$ty>() * 8;
                     let v = (self as $bigty) * (other as $bigty) + (other2 as $bigty) +
                             (carry as $bigty);
-                    ((v >> nbits) as $ty, v as $ty)
+                    ((v >> <$ty>::BITS) as $ty, v as $ty)
                 }
 
                 fn full_div_rem(self, other: $ty, borrow: $ty) -> ($ty, $ty) {
                     debug_assert!(borrow < other);
                     // This cannot overflow; the output is between `0` and `other * (2^nbits - 1)`.
-                    let nbits = mem::size_of::<$ty>() * 8;
-                    let lhs = ((borrow as $bigty) << nbits) | (self as $bigty);
+                    let lhs = ((borrow as $bigty) << <$ty>::BITS) | (self as $bigty);
                     let rhs = other as $bigty;
                     ((lhs / rhs) as $ty, (lhs % rhs) as $ty)
                 }
@@ -128,13 +124,11 @@ pub fn from_small(v: $ty) -> $name {
 
             /// Makes a bignum from `u64` value.
             pub fn from_u64(mut v: u64) -> $name {
-                use crate::mem;
-
                 let mut base = [0; $n];
                 let mut sz = 0;
                 while v > 0 {
                     base[sz] = v as $ty;
-                    v >>= mem::size_of::<$ty>() * 8;
+                    v >>= <$ty>::BITS;
                     sz += 1;
                 }
                 $name { size: sz, base: base }
@@ -150,9 +144,7 @@ pub fn digits(&self) -> &[$ty] {
             /// Returns the `i`-th bit where bit 0 is the least significant one.
             /// In other words, the bit with weight `2^i`.
             pub fn get_bit(&self, i: usize) -> u8 {
-                use crate::mem;
-
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 let d = i / digitbits;
                 let b = i % digitbits;
                 ((self.base[d] >> b) & 1) as u8
@@ -166,8 +158,6 @@ pub fn is_zero(&self) -> bool {
             /// Returns the number of bits necessary to represent this value. Note that zero
             /// is considered to need 0 bits.
             pub fn bit_length(&self) -> usize {
-                use crate::mem;
-
                 // Skip over the most significant digits which are zero.
                 let digits = self.digits();
                 let zeros = digits.iter().rev().take_while(|&&x| x == 0).count();
@@ -180,7 +170,7 @@ pub fn bit_length(&self) -> usize {
                 }
                 // This could be optimized with leading_zeros() and bit shifts, but that's
                 // probably not worth the hassle.
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 let mut i = nonzero.len() * digitbits - 1;
                 while self.get_bit(i) == 0 {
                     i -= 1;
@@ -265,9 +255,7 @@ pub fn mul_small(&mut self, other: $ty) -> &mut $name {
 
             /// Multiplies itself by `2^bits` and returns its own mutable reference.
             pub fn mul_pow2(&mut self, bits: usize) -> &mut $name {
-                use crate::mem;
-
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 let digits = bits / digitbits;
                 let bits = bits % digitbits;
 
@@ -393,13 +381,11 @@ pub fn div_rem_small(&mut self, other: $ty) -> (&mut $name, $ty) {
             /// Divide self by another bignum, overwriting `q` with the quotient and `r` with the
             /// remainder.
             pub fn div_rem(&self, d: &$name, q: &mut $name, r: &mut $name) {
-                use crate::mem;
-
                 // Stupid slow base-2 long division taken from
                 // https://en.wikipedia.org/wiki/Division_algorithm
                 // FIXME use a greater base ($ty) for the long division.
                 assert!(!d.is_zero());
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 for digit in &mut q.base[..] {
                     *digit = 0;
                 }
@@ -462,10 +448,8 @@ fn clone(&self) -> Self {
 
         impl crate::fmt::Debug for $name {
             fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result {
-                use crate::mem;
-
                 let sz = if self.size < 1 { 1 } else { self.size };
-                let digitlen = mem::size_of::<$ty>() * 2;
+                let digitlen = <$ty>::BITS as usize / 4;
 
                 write!(f, "{:#x}", self.base[sz - 1])?;
                 for &v in self.base[..sz - 1].iter().rev() {
index 050c187e55576b5009becf286bd3c3576b780322..eec149cc3e8014276661f328046d3b9c1e6b1bf7 100644 (file)
@@ -348,6 +348,20 @@ macro_rules! int_impl {
             pub const MAX: Self = !Self::MIN;
         }
 
+        doc_comment! {
+            concat!("The size of this integer type in bits.
+
+# Examples
+
+```
+", $Feature, "#![feature(int_bits_const)]
+assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
+$EndFeature, "
+```"),
+            #[unstable(feature = "int_bits_const", issue = "76904")]
+            pub const BITS: u32 = $BITS;
+        }
+
         doc_comment! {
             concat!("Converts a string slice in a given base to an integer.
 
@@ -2601,6 +2615,20 @@ macro_rules! uint_impl {
             pub const MAX: Self = !0;
         }
 
+        doc_comment! {
+            concat!("The size of this integer type in bits.
+
+# Examples
+
+```
+", $Feature, "#![feature(int_bits_const)]
+assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
+$EndFeature, "
+```"),
+            #[unstable(feature = "int_bits_const", issue = "76904")]
+            pub const BITS: u32 = $BITS;
+        }
+
         doc_comment! {
             concat!("Converts a string slice in a given base to an integer.
 
index 8c14651bd826cd4881f545a8d16d9446bf234037..71d2c2c9b2f4c2f3be43c3f9754ceec87f56c8dc 100644 (file)
@@ -565,7 +565,7 @@ fn break_patterns<T>(v: &mut [T]) {
             random
         };
         let mut gen_usize = || {
-            if mem::size_of::<usize>() <= 4 {
+            if usize::BITS <= 32 {
                 gen_u32() as usize
             } else {
                 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
@@ -667,7 +667,7 @@ fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
 ///
 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
 /// this function will immediately switch to heapsort.
-fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: usize)
+fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32)
 where
     F: FnMut(&T, &T) -> bool,
 {
@@ -763,7 +763,7 @@ pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
     }
 
     // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
-    let limit = mem::size_of::<usize>() * 8 - v.len().leading_zeros() as usize;
+    let limit = usize::BITS - v.len().leading_zeros();
 
     recurse(v, &mut is_less, None, limit);
 }
index 00e3972c42f9d41fe0e14eb356615e2c851f5fca..0eb9af3f454e986adb2eb73e2161a447eab939f8 100644 (file)
@@ -474,7 +474,7 @@ fn nth(&mut self, n: usize) -> Option<Self::Item> {
     }
 
     let mut it = Test(0);
-    let root = usize::MAX >> (::std::mem::size_of::<usize>() * 8 / 2);
+    let root = usize::MAX >> (usize::BITS / 2);
     let n = root + 20;
     (&mut it).step_by(n).nth(n);
     assert_eq!(it.0, n as Bigger * n as Bigger);
index a5b1b51e06c64ebea26e19a3d3b54a486d7579ac..4db391f3e567eb69c962c40b7c53264320c5057e 100644 (file)
@@ -52,6 +52,7 @@
 #![feature(partition_point)]
 #![feature(once_cell)]
 #![feature(unsafe_block_in_unsafe_fn)]
+#![feature(int_bits_const)]
 #![deny(unsafe_op_in_unsafe_fn)]
 
 extern crate test;
index 58a585669122ca3b7859cf19b9bef7525354d705..27e6760e7cbb9175e667dc50941b4828dec8ec0f 100644 (file)
@@ -2,7 +2,6 @@ macro_rules! int_module {
     ($T:ident, $T_i:ident) => {
         #[cfg(test)]
         mod tests {
-            use core::mem;
             use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr};
             use core::$T_i::*;
 
@@ -82,30 +81,27 @@ fn test_count_ones() {
 
             #[test]
             fn test_count_zeros() {
-                let bits = mem::size_of::<$T>() * 8;
-                assert_eq!(A.count_zeros(), bits as u32 - 3);
-                assert_eq!(B.count_zeros(), bits as u32 - 2);
-                assert_eq!(C.count_zeros(), bits as u32 - 5);
+                assert_eq!(A.count_zeros(), $T::BITS - 3);
+                assert_eq!(B.count_zeros(), $T::BITS - 2);
+                assert_eq!(C.count_zeros(), $T::BITS - 5);
             }
 
             #[test]
             fn test_leading_trailing_ones() {
-                let bits = (mem::size_of::<$T>() * 8) as u32;
-
                 let a: $T = 0b0101_1111;
                 assert_eq!(a.trailing_ones(), 5);
-                assert_eq!((!a).leading_ones(), bits - 7);
+                assert_eq!((!a).leading_ones(), $T::BITS - 7);
 
                 assert_eq!(a.reverse_bits().leading_ones(), 5);
 
-                assert_eq!(_1.leading_ones(), bits);
-                assert_eq!(_1.trailing_ones(), bits);
+                assert_eq!(_1.leading_ones(), $T::BITS);
+                assert_eq!(_1.trailing_ones(), $T::BITS);
 
                 assert_eq!((_1 << 1).trailing_ones(), 0);
                 assert_eq!(MAX.leading_ones(), 0);
 
-                assert_eq!((_1 << 1).leading_ones(), bits - 1);
-                assert_eq!(MAX.trailing_ones(), bits - 1);
+                assert_eq!((_1 << 1).leading_ones(), $T::BITS - 1);
+                assert_eq!(MAX.trailing_ones(), $T::BITS - 1);
 
                 assert_eq!(_0.leading_ones(), 0);
                 assert_eq!(_0.trailing_ones(), 0);
index b84a8a7d9f88ba3aee84214cc61ac21f764e9a56..952ec188dc1385f9911e4665c237db2935feb2f4 100644 (file)
@@ -4,7 +4,6 @@ macro_rules! uint_module {
         mod tests {
             use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr};
             use core::$T_i::*;
-            use std::mem;
             use std::str::FromStr;
 
             use crate::num;
@@ -47,30 +46,27 @@ fn test_count_ones() {
 
             #[test]
             fn test_count_zeros() {
-                let bits = mem::size_of::<$T>() * 8;
-                assert!(A.count_zeros() == bits as u32 - 3);
-                assert!(B.count_zeros() == bits as u32 - 2);
-                assert!(C.count_zeros() == bits as u32 - 5);
+                assert!(A.count_zeros() == $T::BITS - 3);
+                assert!(B.count_zeros() == $T::BITS - 2);
+                assert!(C.count_zeros() == $T::BITS - 5);
             }
 
             #[test]
             fn test_leading_trailing_ones() {
-                let bits = (mem::size_of::<$T>() * 8) as u32;
-
                 let a: $T = 0b0101_1111;
                 assert_eq!(a.trailing_ones(), 5);
-                assert_eq!((!a).leading_ones(), bits - 7);
+                assert_eq!((!a).leading_ones(), $T::BITS - 7);
 
                 assert_eq!(a.reverse_bits().leading_ones(), 5);
 
-                assert_eq!(_1.leading_ones(), bits);
-                assert_eq!(_1.trailing_ones(), bits);
+                assert_eq!(_1.leading_ones(), $T::BITS);
+                assert_eq!(_1.trailing_ones(), $T::BITS);
 
                 assert_eq!((_1 << 1).trailing_ones(), 0);
                 assert_eq!((_1 >> 1).leading_ones(), 0);
 
-                assert_eq!((_1 << 1).leading_ones(), bits - 1);
-                assert_eq!((_1 >> 1).trailing_ones(), bits - 1);
+                assert_eq!((_1 << 1).leading_ones(), $T::BITS - 1);
+                assert_eq!((_1 >> 1).trailing_ones(), $T::BITS - 1);
 
                 assert_eq!(_0.leading_ones(), 0);
                 assert_eq!(_0.trailing_ones(), 0);
index 649bbce52a364ccc6a329816c2a2ca462562cb0c..652fbe95a14d195f39281a727d056b5f78aede60 100644 (file)
@@ -53,7 +53,7 @@ pub unsafe fn read_uleb128(&mut self) -> u64 {
     }
 
     pub unsafe fn read_sleb128(&mut self) -> i64 {
-        let mut shift: usize = 0;
+        let mut shift: u32 = 0;
         let mut result: u64 = 0;
         let mut byte: u8;
         loop {
@@ -65,7 +65,7 @@ pub unsafe fn read_sleb128(&mut self) -> i64 {
             }
         }
         // sign-extend
-        if shift < 8 * mem::size_of::<u64>() && (byte & 0x40) != 0 {
+        if shift < u64::BITS && (byte & 0x40) != 0 {
             result |= (!0 as u64) << shift;
         }
         result as i64
index 6f31e6dcae70d7b40f406b2c863034ffbd77a8a2..162f0386b6692c757e845c91f55e70babad28995 100644 (file)
@@ -18,6 +18,7 @@
     issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/"
 )]
 #![feature(core_intrinsics)]
+#![feature(int_bits_const)]
 #![feature(lang_items)]
 #![feature(libc)]
 #![feature(nll)]