rust-lang/rust-clippy

Have a lint against usize-to-u64 casts (or, against *all* integer casts)

Open

#9.231 geöffnet am 23. Juli 2022

Auf GitHub ansehen
 (23 Kommentare) (2 Reaktionen) (0 zugewiesene Personen)Rust (1.391 Forks)batch import
A-lintgood first issue

Repository-Metriken

Stars
 (10.406 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 19T 22h) (113 gemergte PRs in 30 T)

Beschreibung

What it does

I would like clippy to lint against all integer casts. So I have set:

#![warn(
    clippy::cast_possible_wrap, // unsigned -> signed
    clippy::cast_sign_loss, // signed -> unsigned
    clippy::cast_lossless,
    clippy::cast_possible_truncation,
)]

However, I just by accident noticed that this does not lint against usize-to-u64 casts. I guess cast_possible_truncation says "this cannot truncate because we don't have more than 64bit pointer size", and "cast_lossless" says "ah this might be lossy on platforms with pointers larger than 64bit", and then neither of them does anything.

I would be happy to either have one of these lints also trigger on usize-to-u64 casts, or to have a new lint against all integer casts.

Lint Name

cast_integer

Category

pedantic

Advantage

Integer casts are subtle and should be done via From/TryFrom, never via as, so I want to rule out all of them in my codebase.

Drawbacks

No response

Example

pub fn foo(x: usize) -> u64 { x as u64 }

Could be written as:

pub fn foo(x: usize) -> u64 { u64::try_from(x).unwrap() }

Contributor Guide