Suggest `{to,from}_ne_bytes` when people use transmute between arrays and integers
Open
@bend-n is already working on this.
Since Jan 26, 2025.
A-diagnostics
T-compiler
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
fn bytes_at_home_1(a: [u8; 4]) -> u32 {
unsafe { std::mem::transmute(a) }
}
fn bytes_at_home_2(x: u32) -> [u8; 4] {
unsafe { std::mem::transmute(x) }
}
Current output
(no warnings)
Desired output
Warning: use the safe alternative instead
|
| unsafe { std::mem::transmute(a) }
| ^^^^^^^^^^^^^^^^^^^ This can be done with `u32::from_ne_bytes(a)` instead
|
hint: there's also `from_le_bytes` and `from_ne_bytes` if you expect a particular byte order
Warning: use the safe alternative instead
|
| unsafe { std::mem::transmute(x) }
| ^^^^^^^^^^^^^^^^^^^ This can be done with `x.to_ne_bytes()` instead
|
hint: there's also `to_le_bytes` and `to_ne_bytes` if you expect a particular byte order
Rationale and extra context
I see people doing this a bunch, like it just came up in Discord.
It would be nice to point them to the safe alternative when possible.
Other cases
Rust Version
Playground nightly ⬇
Anything else?
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.
Assessment
This issue has not been assessed yet.