Skip to content

library: Use size_of from the prelude instead of imported #138034

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions library/alloc/benches/slice.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{mem, ptr};
use std::ptr;

use rand::Rng;
use rand::distr::{Alphanumeric, SampleString, StandardUniform};
Expand Down Expand Up @@ -234,7 +234,7 @@ macro_rules! sort {
fn $name(b: &mut Bencher) {
let v = $gen($len);
b.iter(|| v.clone().$f());
b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64;
b.bytes = $len * size_of_val(&$gen(1)[0]) as u64;
}
};
}
Expand All @@ -246,7 +246,7 @@ macro_rules! sort_strings {
let v = $gen($len);
let v = v.iter().map(|s| &**s).collect::<Vec<&str>>();
b.iter(|| v.clone().$f());
b.bytes = $len * mem::size_of::<&str>() as u64;
b.bytes = $len * size_of::<&str>() as u64;
}
};
}
Expand All @@ -268,7 +268,7 @@ macro_rules! sort_expensive {
});
black_box(count);
});
b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64;
b.bytes = $len * size_of_val(&$gen(1)[0]) as u64;
}
};
}
Expand All @@ -279,7 +279,7 @@ macro_rules! sort_lexicographic {
fn $name(b: &mut Bencher) {
let v = $gen($len);
b.iter(|| v.clone().$f(|x| x.to_string()));
b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64;
b.bytes = $len * size_of_val(&$gen(1)[0]) as u64;
}
};
}
Expand Down Expand Up @@ -322,7 +322,7 @@ macro_rules! reverse {
fn $name(b: &mut Bencher) {
// odd length and offset by 1 to be as unaligned as possible
let n = 0xFFFFF;
let mut v: Vec<_> = (0..1 + (n / mem::size_of::<$ty>() as u64)).map($f).collect();
let mut v: Vec<_> = (0..1 + (n / size_of::<$ty>() as u64)).map($f).collect();
b.iter(|| black_box(&mut v[1..]).reverse());
b.bytes = n;
}
Expand All @@ -346,7 +346,7 @@ macro_rules! rotate {
($name:ident, $gen:expr, $len:expr, $mid:expr) => {
#[bench]
fn $name(b: &mut Bencher) {
let size = mem::size_of_val(&$gen(1)[0]);
let size = size_of_val(&$gen(1)[0]);
let mut v = $gen($len * 8 / size);
b.iter(|| black_box(&mut v).rotate_left(($mid * 8 + size - 1) / size));
b.bytes = (v.len() * size) as u64;
Expand Down
8 changes: 4 additions & 4 deletions library/alloc/benches/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ fn random_sorted_fill(mut seed: u32, buf: &mut [u32]) {
// This algorithm was used for Vecs prior to Rust 1.52.
fn bench_dedup_slice_truncate(b: &mut Bencher, sz: usize) {
let mut template = vec![0u32; sz];
b.bytes = std::mem::size_of_val(template.as_slice()) as u64;
b.bytes = size_of_val(template.as_slice()) as u64;
random_sorted_fill(0x43, &mut template);

let mut vec = template.clone();
Expand All @@ -691,7 +691,7 @@ fn bench_dedup_slice_truncate(b: &mut Bencher, sz: usize) {
// Measures performance of Vec::dedup on random data.
fn bench_vec_dedup_random(b: &mut Bencher, sz: usize) {
let mut template = vec![0u32; sz];
b.bytes = std::mem::size_of_val(template.as_slice()) as u64;
b.bytes = size_of_val(template.as_slice()) as u64;
random_sorted_fill(0x43, &mut template);

let mut vec = template.clone();
Expand All @@ -708,7 +708,7 @@ fn bench_vec_dedup_random(b: &mut Bencher, sz: usize) {
// Measures performance of Vec::dedup when there is no items removed
fn bench_vec_dedup_none(b: &mut Bencher, sz: usize) {
let mut template = vec![0u32; sz];
b.bytes = std::mem::size_of_val(template.as_slice()) as u64;
b.bytes = size_of_val(template.as_slice()) as u64;
template.chunks_exact_mut(2).for_each(|w| {
w[0] = black_box(0);
w[1] = black_box(5);
Expand All @@ -729,7 +729,7 @@ fn bench_vec_dedup_none(b: &mut Bencher, sz: usize) {
// Measures performance of Vec::dedup when there is all items removed
fn bench_vec_dedup_all(b: &mut Bencher, sz: usize) {
let mut template = vec![0u32; sz];
b.bytes = std::mem::size_of_val(template.as_slice()) as u64;
b.bytes = size_of_val(template.as_slice()) as u64;
template.iter_mut().for_each(|w| {
*w = black_box(0);
});
Expand Down
28 changes: 10 additions & 18 deletions library/alloc/src/boxed/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,6 @@ impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
/// ```
/// use std::error::Error;
/// use std::fmt;
/// use std::mem;
///
/// #[derive(Debug)]
/// struct AnError;
Expand All @@ -543,9 +542,9 @@ impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
/// impl Error for AnError {}
///
/// let an_error = AnError;
/// assert!(0 == mem::size_of_val(&an_error));
/// assert!(0 == size_of_val(&an_error));
/// let a_boxed_error = Box::<dyn Error>::from(an_error);
/// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
/// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
/// ```
fn from(err: E) -> Box<dyn Error + 'a> {
Box::new(err)
Expand All @@ -563,7 +562,6 @@ impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync +
/// ```
/// use std::error::Error;
/// use std::fmt;
/// use std::mem;
///
/// #[derive(Debug)]
/// struct AnError;
Expand All @@ -581,10 +579,10 @@ impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync +
/// unsafe impl Sync for AnError {}
///
/// let an_error = AnError;
/// assert!(0 == mem::size_of_val(&an_error));
/// assert!(0 == size_of_val(&an_error));
/// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
/// assert!(
/// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
/// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
/// ```
fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
Box::new(err)
Expand All @@ -600,12 +598,11 @@ impl<'a> From<String> for Box<dyn Error + Send + Sync + 'a> {
///
/// ```
/// use std::error::Error;
/// use std::mem;
///
/// let a_string_error = "a string error".to_string();
/// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
/// assert!(
/// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
/// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
/// ```
#[inline]
fn from(err: String) -> Box<dyn Error + Send + Sync + 'a> {
Expand Down Expand Up @@ -644,11 +641,10 @@ impl<'a> From<String> for Box<dyn Error + 'a> {
///
/// ```
/// use std::error::Error;
/// use std::mem;
///
/// let a_string_error = "a string error".to_string();
/// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
/// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
/// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
/// ```
fn from(str_err: String) -> Box<dyn Error + 'a> {
let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
Expand All @@ -668,12 +664,11 @@ impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
///
/// ```
/// use std::error::Error;
/// use std::mem;
///
/// let a_str_error = "a str error";
/// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
/// assert!(
/// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
/// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
/// ```
#[inline]
fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
Expand All @@ -692,11 +687,10 @@ impl<'a> From<&str> for Box<dyn Error + 'a> {
///
/// ```
/// use std::error::Error;
/// use std::mem;
///
/// let a_str_error = "a str error";
/// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
/// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
/// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
/// ```
fn from(err: &str) -> Box<dyn Error + 'a> {
From::from(String::from(err))
Expand All @@ -712,13 +706,12 @@ impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
///
/// ```
/// use std::error::Error;
/// use std::mem;
/// use std::borrow::Cow;
///
/// let a_cow_str_error = Cow::from("a str error");
/// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
/// assert!(
/// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
/// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
/// ```
fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
From::from(String::from(err))
Expand All @@ -734,12 +727,11 @@ impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + 'a> {
///
/// ```
/// use std::error::Error;
/// use std::mem;
/// use std::borrow::Cow;
///
/// let a_cow_str_error = Cow::from("a str error");
/// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
/// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
/// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
/// ```
fn from(err: Cow<'b, str>) -> Box<dyn Error + 'a> {
From::from(String::from(err))
Expand Down
22 changes: 8 additions & 14 deletions library/alloc/src/boxed/thin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ use core::intrinsics::const_allocate;
use core::marker::PhantomData;
#[cfg(not(no_global_oom_handling))]
use core::marker::Unsize;
use core::mem;
#[cfg(not(no_global_oom_handling))]
use core::mem::SizedTypeProperties;
use core::mem::{self, SizedTypeProperties};
use core::ops::{Deref, DerefMut};
use core::ptr::{self, NonNull, Pointee};

Expand All @@ -30,7 +29,6 @@ use crate::alloc::{self, Layout, LayoutError};
/// let five = ThinBox::new(5);
/// let thin_slice = ThinBox::<[i32]>::new_unsize([1, 2, 3, 4]);
///
/// use std::mem::{size_of, size_of_val};
/// let size_of_ptr = size_of::<*const ()>();
/// assert_eq!(size_of_ptr, size_of_val(&five));
/// assert_eq!(size_of_ptr, size_of_val(&thin_slice));
Expand Down Expand Up @@ -114,7 +112,7 @@ impl<Dyn: ?Sized> ThinBox<Dyn> {
where
T: Unsize<Dyn>,
{
if mem::size_of::<T>() == 0 {
if size_of::<T>() == 0 {
let ptr = WithOpaqueHeader::new_unsize_zst::<Dyn, T>(value);
ThinBox { ptr, _marker: PhantomData }
} else {
Expand Down Expand Up @@ -283,9 +281,7 @@ impl<H> WithHeader<H> {
let ptr = if layout.size() == 0 {
// Some paranoia checking, mostly so that the ThinBox tests are
// more able to catch issues.
debug_assert!(
value_offset == 0 && mem::size_of::<T>() == 0 && mem::size_of::<H>() == 0
);
debug_assert!(value_offset == 0 && size_of::<T>() == 0 && size_of::<H>() == 0);
layout.dangling()
} else {
let ptr = alloc::alloc(layout);
Expand Down Expand Up @@ -315,7 +311,7 @@ impl<H> WithHeader<H> {
Dyn: Pointee<Metadata = H> + ?Sized,
T: Unsize<Dyn>,
{
assert!(mem::size_of::<T>() == 0);
assert!(size_of::<T>() == 0);

const fn max(a: usize, b: usize) -> usize {
if a > b { a } else { b }
Expand All @@ -329,18 +325,16 @@ impl<H> WithHeader<H> {
// FIXME: just call `WithHeader::alloc_layout` with size reset to 0.
// Currently that's blocked on `Layout::extend` not being `const fn`.

let alloc_align =
max(mem::align_of::<T>(), mem::align_of::<<Dyn as Pointee>::Metadata>());
let alloc_align = max(align_of::<T>(), align_of::<<Dyn as Pointee>::Metadata>());

let alloc_size =
max(mem::align_of::<T>(), mem::size_of::<<Dyn as Pointee>::Metadata>());
let alloc_size = max(align_of::<T>(), size_of::<<Dyn as Pointee>::Metadata>());

unsafe {
// SAFETY: align is power of two because it is the maximum of two alignments.
let alloc: *mut u8 = const_allocate(alloc_size, alloc_align);

let metadata_offset =
alloc_size.checked_sub(mem::size_of::<<Dyn as Pointee>::Metadata>()).unwrap();
alloc_size.checked_sub(size_of::<<Dyn as Pointee>::Metadata>()).unwrap();
// SAFETY: adding offset within the allocation.
let metadata_ptr: *mut <Dyn as Pointee>::Metadata =
alloc.add(metadata_offset).cast();
Expand Down Expand Up @@ -421,7 +415,7 @@ impl<H> WithHeader<H> {
}

const fn header_size() -> usize {
mem::size_of::<H>()
size_of::<H>()
}

fn alloc_layout(value_layout: Layout) -> Result<(Layout, usize), LayoutError> {
Expand Down
8 changes: 4 additions & 4 deletions library/alloc/src/collections/btree/node/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ fn test_partial_eq() {
#[cfg(target_arch = "x86_64")]
#[cfg_attr(any(miri, randomized_layouts), ignore)] // We'd like to run Miri with layout randomization
fn test_sizes() {
assert_eq!(core::mem::size_of::<LeafNode<(), ()>>(), 16);
assert_eq!(core::mem::size_of::<LeafNode<i64, i64>>(), 16 + CAPACITY * 2 * 8);
assert_eq!(core::mem::size_of::<InternalNode<(), ()>>(), 16 + (CAPACITY + 1) * 8);
assert_eq!(core::mem::size_of::<InternalNode<i64, i64>>(), 16 + (CAPACITY * 3 + 1) * 8);
assert_eq!(size_of::<LeafNode<(), ()>>(), 16);
assert_eq!(size_of::<LeafNode<i64, i64>>(), 16 + CAPACITY * 2 * 8);
assert_eq!(size_of::<InternalNode<(), ()>>(), 16 + (CAPACITY + 1) * 8);
assert_eq!(size_of::<InternalNode<i64, i64>>(), 16 + (CAPACITY * 3 + 1) * 8);
}
4 changes: 2 additions & 2 deletions library/alloc/src/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ impl<A: Allocator> RawVecInner<A> {

// Allocators currently return a `NonNull<[u8]>` whose length
// matches the size requested. If that ever changes, the capacity
// here should change to `ptr.len() / mem::size_of::<T>()`.
// here should change to `ptr.len() / size_of::<T>()`.
Ok(Self {
ptr: Unique::from(ptr.cast()),
cap: unsafe { Cap::new_unchecked(capacity) },
Expand Down Expand Up @@ -627,7 +627,7 @@ impl<A: Allocator> RawVecInner<A> {
unsafe fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) {
// Allocators currently return a `NonNull<[u8]>` whose length matches
// the size requested. If that ever changes, the capacity here should
// change to `ptr.len() / mem::size_of::<T>()`.
// change to `ptr.len() / size_of::<T>()`.
self.ptr = Unique::from(ptr.cast());
self.cap = unsafe { Cap::new_unchecked(cap) };
}
Expand Down
3 changes: 1 addition & 2 deletions library/alloc/src/raw_vec/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use core::mem::size_of;
use std::cell::Cell;

use super::*;
Expand Down Expand Up @@ -93,7 +92,7 @@ fn zst_sanity<T>(v: &RawVec<T>) {
fn zst() {
let cap_err = Err(crate::collections::TryReserveErrorKind::CapacityOverflow.into());

assert_eq!(std::mem::size_of::<ZST>(), 0);
assert_eq!(size_of::<ZST>(), 0);

// All these different ways of creating the RawVec produce the same thing.

Expand Down
4 changes: 2 additions & 2 deletions library/alloc/src/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use core::borrow::{Borrow, BorrowMut};
#[cfg(not(no_global_oom_handling))]
use core::cmp::Ordering::{self, Less};
#[cfg(not(no_global_oom_handling))]
use core::mem::{self, MaybeUninit};
use core::mem::MaybeUninit;
#[cfg(not(no_global_oom_handling))]
use core::ptr;
#[unstable(feature = "array_chunks", issue = "74985")]
Expand Down Expand Up @@ -446,7 +446,7 @@ impl<T> [T] {
// Avoids binary-size usage in cases where the alignment doesn't work out to make this
// beneficial or on 32-bit platforms.
let is_using_u32_as_idx_type_helpful =
const { mem::size_of::<(K, u32)>() < mem::size_of::<(K, usize)>() };
const { size_of::<(K, u32)>() < size_of::<(K, usize)>() };

// It's possible to instantiate this for u8 and u16 but, doing so is very wasteful in terms
// of compile-times and binary-size, the peak saved heap memory for u16 is (u8 + u16) -> 4
Expand Down
6 changes: 2 additions & 4 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,16 +119,14 @@ use crate::vec::{self, Vec};
/// the same `char`s:
///
/// ```
/// use std::mem;
///
/// // `s` is ASCII which represents each `char` as one byte
/// let s = "hello";
/// assert_eq!(s.len(), 5);
///
/// // A `char` array with the same contents would be longer because
/// // every `char` is four bytes
/// let s = ['h', 'e', 'l', 'l', 'o'];
/// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
/// let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
/// assert_eq!(size, 20);
///
/// // However, for non-ASCII strings, the difference will be smaller
Expand All @@ -137,7 +135,7 @@ use crate::vec::{self, Vec};
/// assert_eq!(s.len(), 20);
///
/// let s = ['💖', '💖', '💖', '💖', '💖'];
/// let size: usize = s.into_iter().map(|c| mem::size_of_val(&c)).sum();
/// let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
/// assert_eq!(size, 20);
/// ```
///
Expand Down
Loading
Loading