Skip to content
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

Suggest size_of_val(a) for a.len() * size_of::<T>() #10518

Closed
scottmcm opened this issue Mar 18, 2023 · 4 comments · Fixed by #10601
Closed

Suggest size_of_val(a) for a.len() * size_of::<T>() #10518

scottmcm opened this issue Mar 18, 2023 · 4 comments · Fixed by #10601
Assignees
Labels
A-lint Area: New lints good-first-issue These issues are a good way to get started with Clippy

Comments

@scottmcm
Copy link
Member

scottmcm commented Mar 18, 2023

What it does

When a is &[T], detect a.len() * size_of::<T>() and suggest size_of_val(a) instead.

Lint Name

manual_slice_size_calculation

Category

complexity, perf

Advantage

  • Shorter to write
  • Removes the need for the human and the compiler to worry about overflow in the multiplication
  • Potentially faster at runtime as rust emits special no-wrapping flags when it calculates the byte length
  • Less turbofishing

Drawbacks

No response

Example

https://github.com/rust-lang/rust/blob/13afbdaa0655dda23d7129e59ac48f1ec88b2084/library/core/src/hash/mod.rs#L837

let newlen = data.len() * mem::size_of::<$ty>();

Could be written as:

let newlen = mem::size_of_val(data);
@scottmcm scottmcm added the A-lint Area: New lints label Mar 18, 2023
@Alexendoo Alexendoo added the good-first-issue These issues are a good way to get started with Clippy label Mar 18, 2023
@schubart
Copy link
Contributor

@rustbot claim

@asquared31415
Copy link
Contributor

slice.len(), usize multiplication, and size_of::<T> are all const, but size_of_val is only unstably const. Code may be using this pattern out of necessity.

@blyxyas
Copy link
Member

blyxyas commented Apr 2, 2023

size_of_val is only unstably const.

Then maybe only linting for nightly builds? It can be quickly checked from cx.sess().is_nightly_build(). As far as I'm aware, there are no unstable Clippy lints.

@Alexendoo
Copy link
Member

It can still lint on stable, but only outside of const contexts which can be checked using in_constant

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints good-first-issue These issues are a good way to get started with Clippy
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants