rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.32k stars 1.53k forks source link

`cast_possible_wrap` for convertion from `u8` to `isize` #9337

Closed quarthex closed 1 year ago

quarthex commented 2 years ago

Summary

The lint cast_possible_wrap is triggered by a conversion from u8 to isize.

The displayed message is:

casting `u8` to `isize` may wrap around the value on targets with 32-bit wide pointers

On 16/32/64-bits platforms, the message is wrong. An 8-bit unsigned value fits in a 16/32/64-bits signed register.

Reproducer

#![warn(clippy::cast_possible_wrap)]
const A: u8 = 0;
const B: isize = A as isize;

Version

rustc 1.63.0 (4b91a6ea7 2022-08-08)
binary: rustc
commit-hash: 4b91a6ea7258a947e59c6522cd5898e7c0a6a88f
commit-date: 2022-08-08
host: x86_64-unknown-linux-gnu
release: 1.63.0
LLVM version: 14.0.5

Additional Labels

@rustbot label +I-false-positive +L-pedantic

quarthex commented 2 years ago

The lint applies on 8-bits platforms, though.

asquared31415 commented 1 year ago

Rust will never support platforms where u/isize is smaller than 16 bits and this lint is always incorrect. In fact isize::from(u8) exists, which means it definitely is a lossless conversion.

quarthex commented 1 year ago

@asquared31415 If it want to be considered as a language targeted for embedded development, Rust should be able to produce code for such platforms. In my company, we are trying to deal with shortages of microcontrollers such as STM32 (mainly reserved by the car industry) and we will use TinyAVR micrcontrollers instead. So, saying that Rust will never support 8-bit platforms is a little dramatic from my point of view.

asquared31415 commented 1 year ago

Unfortunately Rust has already made guarantees that are incompatible with that. It's well documented that usize is at least 16 bits large in The Reference and changing that would also require breaking changes to the standard library, namely the removal of the isize::from(u8) impl.