rust-lang / rust-lang/rust-clippy
Warn on transmutes that could use pre-defined methods instead
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
I've been rather exhaustively adding methods to the standard library that allow "safe" transmutes that we know work, like between [u8] and str (see: rust-lang/rust#41119 and rust-lang/rust#40380). It'd be nice if we had a framework to detect transmutes specifically between these types and suggest other methods instead.
For example, &str -> &u8 is str::as_bytes, and the reverse is str::from_utf8_unchecked. If someone does a raw transmute here, they should be redirected to the standard library functions that do these conversions.
I've been slowly adding methods to do less common conversions, like &mut [u8] -> &mut str. In general it makes sense to have some sort of framework to recognise transmutes and suggest to replace them with more explicit functions, especially as these other methods get stabilised.
If we want to go all-out, we could detect functions that do these conversions and suggest them instead of transmutes.
Current list:
transmute::<&str, &[u8]>=>str::as_bytestransmute::<&mut str, &mut [u8]>=>str::as_mut_bytestransmute::<&[u8], &str>=>std::str::from_utf8_uncheckedtransmute::<&mut [u8], &mut str>=>std::str::from_utf8_unchecked_muttransmute::<&CStr, &[u8]>=>CStr::to_bytes_with_nultransmute::<&[u8], &CStr>=>CStr::from_bytes_with_nul_uncheckedtransmute::<f32, u32>=>f32::to_bitstransmute::<f64, u64>=>f64::to_bitstransmute::<u32, f32>=>f32::from_bitstransmute::<u64, f64>=>f64::from_bits
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the listed transmute pairs and the corresponding standard-library methods, including the str, CStr, f32, and f64 conversions. Define the lint framework and decide whether the initial scope covers only these pairs or broader conversion detection. Done means Clippy warns on applicable transmutes and suggests the appropriate explicit method.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100