Skip to content

Commit fef3324

Browse files
authored
Rollup merge of #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

+1
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

+1-1
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

+2-2
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

+1
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

+1-1
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

+1
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

+2-3
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

+1-1
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

+1-1
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

+9-25
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() {

library/core/src/num/mod.rs

+28
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,20 @@ $EndFeature, "
348348
pub const MAX: Self = !Self::MIN;
349349
}
350350

351+
doc_comment! {
352+
concat!("The size of this integer type in bits.
353+
354+
# Examples
355+
356+
```
357+
", $Feature, "#![feature(int_bits_const)]
358+
assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
359+
$EndFeature, "
360+
```"),
361+
#[unstable(feature = "int_bits_const", issue = "76904")]
362+
pub const BITS: u32 = $BITS;
363+
}
364+
351365
doc_comment! {
352366
concat!("Converts a string slice in a given base to an integer.
353367
@@ -2601,6 +2615,20 @@ $EndFeature, "
26012615
pub const MAX: Self = !0;
26022616
}
26032617

2618+
doc_comment! {
2619+
concat!("The size of this integer type in bits.
2620+
2621+
# Examples
2622+
2623+
```
2624+
", $Feature, "#![feature(int_bits_const)]
2625+
assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
2626+
$EndFeature, "
2627+
```"),
2628+
#[unstable(feature = "int_bits_const", issue = "76904")]
2629+
pub const BITS: u32 = $BITS;
2630+
}
2631+
26042632
doc_comment! {
26052633
concat!("Converts a string slice in a given base to an integer.
26062634

library/core/src/slice/sort.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -565,7 +565,7 @@ fn break_patterns<T>(v: &mut [T]) {
565565
random
566566
};
567567
let mut gen_usize = || {
568-
if mem::size_of::<usize>() <= 4 {
568+
if usize::BITS <= 32 {
569569
gen_u32() as usize
570570
} else {
571571
(((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
@@ -667,7 +667,7 @@ where
667667
///
668668
/// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
669669
/// this function will immediately switch to heapsort.
670-
fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: usize)
670+
fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32)
671671
where
672672
F: FnMut(&T, &T) -> bool,
673673
{
@@ -763,7 +763,7 @@ where
763763
}
764764

765765
// Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
766-
let limit = mem::size_of::<usize>() * 8 - v.len().leading_zeros() as usize;
766+
let limit = usize::BITS - v.len().leading_zeros();
767767

768768
recurse(v, &mut is_less, None, limit);
769769
}

library/core/tests/iter.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ fn test_iterator_step_by_nth_overflow() {
474474
}
475475

476476
let mut it = Test(0);
477-
let root = usize::MAX >> (::std::mem::size_of::<usize>() * 8 / 2);
477+
let root = usize::MAX >> (usize::BITS / 2);
478478
let n = root + 20;
479479
(&mut it).step_by(n).nth(n);
480480
assert_eq!(it.0, n as Bigger * n as Bigger);

library/core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
#![feature(partition_point)]
5353
#![feature(once_cell)]
5454
#![feature(unsafe_block_in_unsafe_fn)]
55+
#![feature(int_bits_const)]
5556
#![deny(unsafe_op_in_unsafe_fn)]
5657

5758
extern crate test;

library/core/tests/num/int_macros.rs

+8-12
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ macro_rules! int_module {
22
($T:ident, $T_i:ident) => {
33
#[cfg(test)]
44
mod tests {
5-
use core::mem;
65
use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr};
76
use core::$T_i::*;
87

@@ -82,30 +81,27 @@ macro_rules! int_module {
8281

8382
#[test]
8483
fn test_count_zeros() {
85-
let bits = mem::size_of::<$T>() * 8;
86-
assert_eq!(A.count_zeros(), bits as u32 - 3);
87-
assert_eq!(B.count_zeros(), bits as u32 - 2);
88-
assert_eq!(C.count_zeros(), bits as u32 - 5);
84+
assert_eq!(A.count_zeros(), $T::BITS - 3);
85+
assert_eq!(B.count_zeros(), $T::BITS - 2);
86+
assert_eq!(C.count_zeros(), $T::BITS - 5);
8987
}
9088

9189
#[test]
9290
fn test_leading_trailing_ones() {
93-
let bits = (mem::size_of::<$T>() * 8) as u32;
94-
9591
let a: $T = 0b0101_1111;
9692
assert_eq!(a.trailing_ones(), 5);
97-
assert_eq!((!a).leading_ones(), bits - 7);
93+
assert_eq!((!a).leading_ones(), $T::BITS - 7);
9894

9995
assert_eq!(a.reverse_bits().leading_ones(), 5);
10096

101-
assert_eq!(_1.leading_ones(), bits);
102-
assert_eq!(_1.trailing_ones(), bits);
97+
assert_eq!(_1.leading_ones(), $T::BITS);
98+
assert_eq!(_1.trailing_ones(), $T::BITS);
10399

104100
assert_eq!((_1 << 1).trailing_ones(), 0);
105101
assert_eq!(MAX.leading_ones(), 0);
106102

107-
assert_eq!((_1 << 1).leading_ones(), bits - 1);
108-
assert_eq!(MAX.trailing_ones(), bits - 1);
103+
assert_eq!((_1 << 1).leading_ones(), $T::BITS - 1);
104+
assert_eq!(MAX.trailing_ones(), $T::BITS - 1);
109105

110106
assert_eq!(_0.leading_ones(), 0);
111107
assert_eq!(_0.trailing_ones(), 0);

0 commit comments

Comments
 (0)