Skip to content

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

Open
@scottmcm

Description

@scottmcm

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

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions