Skip to content

size_of_in_element_count false-positive when dividing byte-size by element size #6511

Closed
@MarijnS95

Description

@MarijnS95

Lint name: size_of_in_element_count

I tried this code:

fn main() {
    let bytes = [0u8, 1u8, 2u8, 3u8];
    let shorts: &[u16] = unsafe {
        std::slice::from_raw_parts(
            bytes.as_ptr() as *const _,
            bytes.len() / std::mem::size_of::<u16>(),
        )
    };
    dbg!(shorts);
}

I expected to see this happen:

No size_of_in_element_count lint warning/error when dividing by size_of.

Instead, this happened:

    Checking playground v0.0.1 (/playground)
error: found a count of bytes instead of a count of elements of `T`
 --> src/main.rs:6:13
  |
6 |             bytes.len() / std::mem::size_of::<u16>(),
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = 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

#6394 recently introduced the size_of_in_element_count to catch cases where byte sizes instead of element sizes are passed into from_raw_parts and related functions. However, size_of is used in the example above to convert away from byte sizes by dividing instead of multiplying. After all the linter error states:

use a count of elements instead of a count of bytes, it already gets multiplied by the size of the type

When no count of bytes nor multiplication is used here at all.

CC @nico-abram

Meta

  • cargo +nightly clippy -V: clippy 0.0.212 (257becb 2020-12-27)
  • rustc +nightly -Vv:
    rustc 1.51.0-nightly (257becbfe 2020-12-27)
    binary: rustc
    commit-hash: 257becbfe4987d1f7b12af5a8dd5ed96697cd2e8
    commit-date: 2020-12-27
    host: x86_64-unknown-linux-gnu
    release: 1.51.0-nightly
    

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions