rust-lang / rust-lang/rust

Suggest `{to,from}_ne_bytes` when people use transmute between arrays and integers

Open
#136,067 6 comments 0 reactions 1 assignee View on GitHub

@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?

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=a89dfdaa49736b9d106b2099ca48ddd7

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.