rust-lang / rust-lang/rust-clippy

`transmute_ptr_to_ptr` doesn’t justify its existence

Open
#6,372 9 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-documentation C-enhancement
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

The transmute_ptr_to_ptr lint fires on transmute<T, U> when
both T and U are reference types. The docs say:

Why this is bad

Transmutes are dangerous, and these can instead be written as casts.

But this doesn’t explain anything. These casts are just as unsafe as the
transmute. In fact, transmute can be written in terms of such
casts:

pub unsafe fn transmute<T, U>(t: T) -> U {
    std::ptr::read(&t as *const T as *const U)
}

…so clearly they don’t bring any safety benefit.

I am aware that the docs for transmute itself also mention that you
can use as-casts in place of transmute
. But those docs also
offer no explanation. They were added in rust-lang/rust#34609, where
@sfackler voiced the same concern but received no response.
(@sfackler also points out that transmute::<&T, &U> at least checks
statically that &T and &U have the same size, which pointer casts do
not. See size-checking example.)

Some veteran programmers on my team have suggested using transmute in
these cases for clarity, and I have to agree that it’s clearer:

unsafe { std::mem::transmute::<&str, &Tag>(s.as_ref()) }
// versus
unsafe { &*(s.as_ref() as *const str as *const Tag) }

The former says what it’s doing right on the tin. In the latter, you
have to make sure that your &s and *s are all matching, and it’s
less self-documenting.

Does this lint exist for a reason other than safety theater or cargo
culting? If so, could you please add an explanation to the docs?

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.

Research direction

Start with the transmute_ptr_to_ptr lint documentation and the referenced std::mem::transmute alternatives, then review the linked discussion and examples. Done means the lint docs clearly explain whether the lint has a reason beyond safety concerns and how the pointer casts differ from transmute.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.