rust-lang/rust-clippy

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

Open

#9 231 ouverte le 23 juil. 2022

Voir sur GitHub
 (23 commentaires) (2 réactions) (0 assignés)Rust (1 391 forks)batch import
A-lintgood first issue

Métriques du dépôt

Stars
 (10 406 stars)
Métriques de merge PR
 (Merge moyen 19j 22h) (113 PRs mergées en 30 j)

Description

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() }

Guide contributeur