-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Closed
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveIssue: The lint was triggered on code it shouldn't have
Description
Lint name: size_of_in_element_count
I tried this code:
fn u8_as_bytes(x: &u8) -> &[u8] {
unsafe {
let ptr: *const u8 = x;
std::slice::from_raw_parts(ptr.cast::<u8>(), std::mem::size_of::<u8>())
}
}I expected to see this happen: Clippy should not give a size_of_in_element_count error.
Instead, this happened for rustup run nightly cargo clippy:
error: found a count of bytes instead of a count of elements of `T`
--> src/main.rs:4:54
|
4 | std::slice::from_raw_parts(ptr.cast::<u8>(), std::mem::size_of::<u8>())
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[deny(clippy::size_of_in_element_count)]` on by default
= help: use a count of elements instead of a count of bytes, it already gets multiplied by the size of the type
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#size_of_in_element_count
In contrast, clippy (correctly) does not give an error for this code:
fn u32_as_bytes(x: &u32) -> &[u8] {
unsafe {
let ptr: *const u32 = x;
std::slice::from_raw_parts(ptr.cast::<u8>(), std::mem::size_of::<u32>())
}
}In other words, I've seen the false positive only for the u8 case.
The false positive also occurs for the following similar code, but again, only for the u8 case:
fn u8_slice_as_bytes(slice: &[u8]) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
slice.as_ptr().cast::<u8>(),
slice.len() * std::mem::size_of::<u8>(),
)
}
}You might wonder why anyone would write a functions like u8_as_bytes or u8_slice_as_bytes. This came up for me because they're in a macro that implements a trait, and the macro is used for all the numeric primitives, including u8. (Here's the CI failure for my crate due to the clippy lint.)
Meta
rustup run nightly cargo clippy -V: clippy 0.1.51 (a62a760 2021-01-13)rustup run nightly rustc -Vv:rustc 1.51.0-nightly (a62a76047 2021-01-13) binary: rustc commit-hash: a62a76047ea24aad7639f14eb3ce0e620b77bdb7 commit-date: 2021-01-13 host: x86_64-unknown-linux-gnu release: 1.51.0-nightly
Metadata
Metadata
Assignees
Labels
C-bugCategory: Clippy is not doing the correct thingCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveIssue: The lint was triggered on code it shouldn't have