Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit fef3324

Browse files
authored
Rollup merge of rust-lang#76492 - fusion-engineering-forks:int-bits, r=dtolnay
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`.
2 parents 1720fd9 + 1bfe5ef commit fef3324

File tree

18 files changed

+72
-64
lines changed

18 files changed

+72
-64
lines changed

compiler/rustc_data_structures/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#![feature(generators)]
1515
#![feature(generator_trait)]
1616
#![feature(fn_traits)]
17+
#![feature(int_bits_const)]
1718
#![feature(min_specialization)]
1819
#![feature(optin_builtin_traits)]
1920
#![feature(nll)]

compiler/rustc_data_structures/src/tagged_ptr/copy.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ where
4848
P: Pointer,
4949
T: Tag,
5050
{
51-
const TAG_BIT_SHIFT: usize = (8 * std::mem::size_of::<usize>()) - T::BITS;
51+
const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS;
5252
const ASSERTION: () = {
5353
assert!(T::BITS <= P::BITS);
5454
// Used for the transmute_copy's below

library/alloc/src/collections/binary_heap.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@
146146

147147
use core::fmt;
148148
use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen};
149-
use core::mem::{self, size_of, swap, ManuallyDrop};
149+
use core::mem::{self, swap, ManuallyDrop};
150150
use core::ops::{Deref, DerefMut};
151151
use core::ptr;
152152

@@ -617,7 +617,7 @@ impl<T: Ord> BinaryHeap<T> {
617617

618618
#[inline(always)]
619619
fn log2_fast(x: usize) -> usize {
620-
8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
620+
(usize::BITS - x.leading_zeros() - 1) as usize
621621
}
622622

623623
// `rebuild` takes O(len1 + len2) operations

library/alloc/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@
101101
#![feature(fn_traits)]
102102
#![feature(fundamental)]
103103
#![feature(inplace_iteration)]
104+
#![feature(int_bits_const)]
104105
#![feature(lang_items)]
105106
#![feature(layout_for_ptr)]
106107
#![feature(libc)]

library/alloc/src/raw_vec.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,7 @@ unsafe impl<#[may_dangle] T, A: AllocRef> Drop for RawVec<T, A> {
528528

529529
#[inline]
530530
fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
531-
if mem::size_of::<usize>() < 8 && alloc_size > isize::MAX as usize {
531+
if usize::BITS < 64 && alloc_size > isize::MAX as usize {
532532
Err(CapacityOverflow)
533533
} else {
534534
Ok(())

library/alloc/tests/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#![feature(deque_range)]
1919
#![feature(inplace_iteration)]
2020
#![feature(iter_map_while)]
21+
#![feature(int_bits_const)]
2122

2223
use std::collections::hash_map::DefaultHasher;
2324
use std::hash::{Hash, Hasher};

library/alloc/tests/string.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::borrow::Cow;
22
use std::collections::TryReserveError::*;
3-
use std::mem::size_of;
43
use std::ops::Bound::*;
54

65
pub trait IntoCow<'a, B: ?Sized>
@@ -605,7 +604,7 @@ fn test_try_reserve() {
605604
// on 64-bit, we assume the OS will give an OOM for such a ridiculous size.
606605
// Any platform that succeeds for these requests is technically broken with
607606
// ptr::offset because LLVM is the worst.
608-
let guards_against_isize = size_of::<usize>() < 8;
607+
let guards_against_isize = usize::BITS < 64;
609608

610609
{
611610
// Note: basic stuff is checked by test_reserve
@@ -686,7 +685,7 @@ fn test_try_reserve_exact() {
686685
const MAX_CAP: usize = isize::MAX as usize;
687686
const MAX_USIZE: usize = usize::MAX;
688687

689-
let guards_against_isize = size_of::<usize>() < 8;
688+
let guards_against_isize = usize::BITS < 64;
690689

691690
{
692691
let mut empty_string: String = String::new();

library/alloc/tests/vec.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1341,7 +1341,7 @@ fn test_try_reserve() {
13411341
// on 64-bit, we assume the OS will give an OOM for such a ridiculous size.
13421342
// Any platform that succeeds for these requests is technically broken with
13431343
// ptr::offset because LLVM is the worst.
1344-
let guards_against_isize = size_of::<usize>() < 8;
1344+
let guards_against_isize = usize::BITS < 64;
13451345

13461346
{
13471347
// Note: basic stuff is checked by test_reserve

library/core/src/fmt/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2086,7 +2086,7 @@ impl<T: ?Sized> Pointer for *const T {
20862086
f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
20872087

20882088
if f.width.is_none() {
2089-
f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
2089+
f.width = Some((usize::BITS / 4) as usize + 2);
20902090
}
20912091
}
20922092
f.flags |= 1 << (FlagV1::Alternate as u32);

library/core/src/num/bignum.rs

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
#![macro_use]
2121

2222
use crate::intrinsics;
23-
use crate::mem;
2423

2524
/// Arithmetic operations required by bignums.
2625
pub trait FullOps: Sized {
@@ -58,25 +57,22 @@ macro_rules! impl_full_ops {
5857
// This cannot overflow;
5958
// the output is between `0` and `2^nbits * (2^nbits - 1)`.
6059
// FIXME: will LLVM optimize this into ADC or similar?
61-
let nbits = mem::size_of::<$ty>() * 8;
6260
let v = (self as $bigty) * (other as $bigty) + (carry as $bigty);
63-
((v >> nbits) as $ty, v as $ty)
61+
((v >> <$ty>::BITS) as $ty, v as $ty)
6462
}
6563

6664
fn full_mul_add(self, other: $ty, other2: $ty, carry: $ty) -> ($ty, $ty) {
6765
// This cannot overflow;
6866
// the output is between `0` and `2^nbits * (2^nbits - 1)`.
69-
let nbits = mem::size_of::<$ty>() * 8;
7067
let v = (self as $bigty) * (other as $bigty) + (other2 as $bigty) +
7168
(carry as $bigty);
72-
((v >> nbits) as $ty, v as $ty)
69+
((v >> <$ty>::BITS) as $ty, v as $ty)
7370
}
7471

7572
fn full_div_rem(self, other: $ty, borrow: $ty) -> ($ty, $ty) {
7673
debug_assert!(borrow < other);
7774
// This cannot overflow; the output is between `0` and `other * (2^nbits - 1)`.
78-
let nbits = mem::size_of::<$ty>() * 8;
79-
let lhs = ((borrow as $bigty) << nbits) | (self as $bigty);
75+
let lhs = ((borrow as $bigty) << <$ty>::BITS) | (self as $bigty);
8076
let rhs = other as $bigty;
8177
((lhs / rhs) as $ty, (lhs % rhs) as $ty)
8278
}
@@ -128,13 +124,11 @@ macro_rules! define_bignum {
128124

129125
/// Makes a bignum from `u64` value.
130126
pub fn from_u64(mut v: u64) -> $name {
131-
use crate::mem;
132-
133127
let mut base = [0; $n];
134128
let mut sz = 0;
135129
while v > 0 {
136130
base[sz] = v as $ty;
137-
v >>= mem::size_of::<$ty>() * 8;
131+
v >>= <$ty>::BITS;
138132
sz += 1;
139133
}
140134
$name { size: sz, base: base }
@@ -150,9 +144,7 @@ macro_rules! define_bignum {
150144
/// Returns the `i`-th bit where bit 0 is the least significant one.
151145
/// In other words, the bit with weight `2^i`.
152146
pub fn get_bit(&self, i: usize) -> u8 {
153-
use crate::mem;
154-
155-
let digitbits = mem::size_of::<$ty>() * 8;
147+
let digitbits = <$ty>::BITS as usize;
156148
let d = i / digitbits;
157149
let b = i % digitbits;
158150
((self.base[d] >> b) & 1) as u8
@@ -166,8 +158,6 @@ macro_rules! define_bignum {
166158
/// Returns the number of bits necessary to represent this value. Note that zero
167159
/// is considered to need 0 bits.
168160
pub fn bit_length(&self) -> usize {
169-
use crate::mem;
170-
171161
// Skip over the most significant digits which are zero.
172162
let digits = self.digits();
173163
let zeros = digits.iter().rev().take_while(|&&x| x == 0).count();
@@ -180,7 +170,7 @@ macro_rules! define_bignum {
180170
}
181171
// This could be optimized with leading_zeros() and bit shifts, but that's
182172
// probably not worth the hassle.
183-
let digitbits = mem::size_of::<$ty>() * 8;
173+
let digitbits = <$ty>::BITS as usize;
184174
let mut i = nonzero.len() * digitbits - 1;
185175
while self.get_bit(i) == 0 {
186176
i -= 1;
@@ -265,9 +255,7 @@ macro_rules! define_bignum {
265255

266256
/// Multiplies itself by `2^bits` and returns its own mutable reference.
267257
pub fn mul_pow2(&mut self, bits: usize) -> &mut $name {
268-
use crate::mem;
269-
270-
let digitbits = mem::size_of::<$ty>() * 8;
258+
let digitbits = <$ty>::BITS as usize;
271259
let digits = bits / digitbits;
272260
let bits = bits % digitbits;
273261

@@ -393,13 +381,11 @@ macro_rules! define_bignum {
393381
/// Divide self by another bignum, overwriting `q` with the quotient and `r` with the
394382
/// remainder.
395383
pub fn div_rem(&self, d: &$name, q: &mut $name, r: &mut $name) {
396-
use crate::mem;
397-
398384
// Stupid slow base-2 long division taken from
399385
// https://en.wikipedia.org/wiki/Division_algorithm
400386
// FIXME use a greater base ($ty) for the long division.
401387
assert!(!d.is_zero());
402-
let digitbits = mem::size_of::<$ty>() * 8;
388+
let digitbits = <$ty>::BITS as usize;
403389
for digit in &mut q.base[..] {
404390
*digit = 0;
405391
}
@@ -462,10 +448,8 @@ macro_rules! define_bignum {
462448

463449
impl crate::fmt::Debug for $name {
464450
fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result {
465-
use crate::mem;
466-
467451
let sz = if self.size < 1 { 1 } else { self.size };
468-
let digitlen = mem::size_of::<$ty>() * 2;
452+
let digitlen = <$ty>::BITS as usize / 4;
469453

470454
write!(f, "{:#x}", self.base[sz - 1])?;
471455
for &v in self.base[..sz - 1].iter().rev() {

0 commit comments

Comments
 (0)