Skip to content

cast_possible_truncation false positive: const defined in the same crate #9613

@dtolnay

Description

@dtolnay

Summary

I believe cast_possible_truncation should not trigger when using as to cast a constant defined in the same crate, and clippy can tell for sure that the cast will not truncate. It's a false positive to indicate that the cast may truncate.

If the programmer later changes the value of the const such that truncation does occur (this would be an extremely unusual scenario) then the developer will be alerted about the old code at that point by clippy, so there is no risk.

Lint Name

cast_possible_truncation

Reproducer

const CHUNK: usize = 64;

fn main() {
    // CHUNK is almost always used as usize
    let _empty_chunk = [0u8; CHUNK];

    // In a few places it is used as u32
    for i in 0..(u32::from(char::MAX) + 1) / CHUNK as u32 {
        for j in 0..CHUNK as u32 {
            let _ch = i * CHUNK as u32 + j;
            // ...
        }
    }
}
$ cargo clippy -- -Dclippy::cast_possible_truncation
error: casting `usize` to `u32` may truncate the value on targets with 64-bit wide pointers
 --> src/main.rs:8:46
  |
8 |     for i in 0..(u32::from(char::MAX) + 1) / CHUNK as u32 {
  |                                              ^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation
  = note: requested on the command line with `-D clippy::cast-possible-truncation`

error: casting `usize` to `u32` may truncate the value on targets with 64-bit wide pointers
 --> src/main.rs:9:21
  |
9 |         for j in 0..CHUNK as u32 {
  |                     ^^^^^^^^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation

error: casting `usize` to `u32` may truncate the value on targets with 64-bit wide pointers
  --> src/main.rs:10:27
   |
10 |             let _ch = i * CHUNK as u32 + j;
   |                           ^^^^^^^^^^^^
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation

Version

rustc 1.66.0-nightly (8b0c05d9a 2022-10-07)
binary: rustc
commit-hash: 8b0c05d9ad7121cdb97600f261bcd5f04c8db20d
commit-date: 2022-10-07
host: x86_64-unknown-linux-gnu
release: 1.66.0-nightly
LLVM version: 15.0.2

Additional Labels

No response

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