rust-lang / rust-lang/rust-clippy

`cast_possible_truncation` triggers when the value is guranteed to not be truncated

Open
#7,486 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Lint name: cast_possible_truncation

I tried this code:

#![deny(clippy::cast_possible_truncation)]

fn modulo(number: u64, other: u32) -> u32 {
    // a u64 with guranteed value to be less than or equal to u32::max_value()
    let other_u64 = other as u64;
    // modulo gurantees that the following invariant holds:
    // result < other_u64
    // which implies that result < u32::max_value()
    let result = number % other_u64;
    result as u32
}

fn main() {
    assert_eq!(modulo(11_u64, 5_u32), 1_u32);
}

I expected to see this happen: the lint should not trigger

Instead, this happened: the lint about a possible truncation has been emitted

Meta
  • cargo clippy -V: clippy 0.1.55 (02718709 2021-07-22)
  • rustc -Vv:
rustc 1.55.0-nightly (027187094 2021-07-22)
binary: rustc
commit-hash: 027187094ee05011d6602f5742f550851ccc7fd6
commit-date: 2021-07-22
host: x86_64-pc-windows-msvc
release: 1.55.0-nightly
LLVM version: 12.0.1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the provided Rust reproducer and the cast_possible_truncation lint implementation and tests. Determine whether the modulo invariant can be recognized safely by the lint. Done means the example no longer emits the lint while genuine potentially truncating casts remain covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.