Re: [PATCH v7 7/7] rust: enable `clippy::ref_as_ptr` lint
From: Tamir Duberstein
Date: Wed Mar 26 2025 - 15:07:22 EST
On Wed, Mar 26, 2025 at 1:36 PM Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
>
> On Wed Mar 26, 2025 at 5:57 PM CET, Tamir Duberstein wrote:
> >
> >
> > In the current code you're looking at, yes. But in the code I have
> > locally I'm transmuting `[u8]` to `BStr`. See my earlier reply where I
> > said "Hmm, looking at this again we can just transmute ref-to-ref and
> > avoid pointers entirely. We're already doing that in
> > `CStr::from_bytes_with_nul_unchecked`".
>
> `CStr::from_bytes_with_nul_unchecked` does the transmute with
> references. That is a usage that the docs of `transmute` explicitly
> recommend to change to an `as` cast [1].
RIght. That guidance was written in 2016
(https://github.com/rust-lang/rust/pull/34609) and doesn't present any
rationale for `as` casts being preferred to transmute. I posted a
comment in the most relevant issue I could find:
https://github.com/rust-lang/rust/issues/34249#issuecomment-2755316610.
> No idea about provenance still.
Well that's not surprising, nobody was thinking about provenance in
2016. But I really don't think we should blindly follow the advice in
this case. It doesn't make an iota of sense to me - does it make sense
to you?
>
> [1]: https://doc.rust-lang.org/std/mem/fn.transmute.html#alternatives
>
> >> I tried to find some existing issues about the topic and found that
> >> there exists a clippy lint `transmute_ptr_to_ptr`. There is an issue
> >> asking for a better justification [1] and it seems like nobody provided
> >> one there. Maybe we should ask the opsem team what happens to provenance
> >> when transmuting?
> >
> > Yeah, we should do this - but again: not relevant in this discussion.
>
> I think it's pretty relevant.
It's not relevant because we're no longer talking about transmuting
pointer to pointer. The two options are:
1. transmute reference to reference.
2. coerce reference to pointer, `as` cast pointer to pointer (triggers
`ptr_as_ptr`), reborrow pointer to reference.
If anyone can help me understand why (2) is better than (1), I'd
certainly appreciate it.