Skip to content

cast_possible_truncation suggestion problem #13814

@leonardo-m

Description

@leonardo-m

Summary

Clippy cast_possible_truncation nusery lint gives an wrong suggestion.

Lint Name

cast_possible_truncation

Reproducer

I tried this code:

#![allow(dead_code)]
#![warn(clippy::all)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]

const X1: u16 = 1251_u16.ilog(3) as u16;
const X2: u16 = 1251_u16.ilog(3) as _;

fn main() {}

I saw this happen:

warning: casting `u32` to `u16` may truncate the value
 --> src/main.rs:6:17
  |
6 | const X1: u16 = 1251_u16.ilog(3) as u16;
  |                 ^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ...
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation
note: the lint level is defined here
 --> src/main.rs:4:9
  |
4 | #![warn(clippy::pedantic)]
  |         ^^^^^^^^^^^^^^^^
  = note: `#[warn(clippy::cast_possible_truncation)]` implied by `#[warn(clippy::pedantic)]`
help: ... or use `try_from` and handle the error accordingly
  |
6 | const X1: u16 = u16::try_from(1251_u16.ilog(3));
  |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

warning: casting `u32` to `u16` may truncate the value
 --> src/main.rs:7:17
  |
7 | const X2: u16 = 1251_u16.ilog(3) as _;
  |                 ^^^^^^^^^^^^^^^^^^^^^
  |
  = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ...
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation
help: ... or use `try_from` and handle the error accordingly
  |
7 | const X2: u16 = 1251_u16.ilog(3).try_into();
  |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~

The suggested code can't compile, even if you add unwrap(), because it's a const context.

Version

v.1.85 Nightly

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