Thread (27 messages) 27 messages, 3 authors, 2025-03-27

Re: [PATCH v7 7/7] rust: enable `clippy::ref_as_ptr` lint

From: Benno Lossin <hidden>
Date: 2025-03-26 10:31:06
Also in: dri-devel, linux-block, linux-devicetree, linux-kbuild, linux-kselftest, linux-pci, lkml, rust-for-linux

On Wed Mar 26, 2025 at 12:54 AM CET, Tamir Duberstein wrote:
On Tue, Mar 25, 2025 at 6:40 PM Benno Lossin [off-list ref] wrote:
quoted
On Tue Mar 25, 2025 at 11:33 PM CET, Tamir Duberstein wrote:
quoted
On Tue, Mar 25, 2025 at 6:11 PM Benno Lossin [off-list ref] wrote:
quoted
On Tue Mar 25, 2025 at 9:07 PM CET, Tamir Duberstein wrote:
quoted
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 40034f77fc2f..6233af50bab7 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -29,7 +29,7 @@ pub const fn is_empty(&self) -> bool {
     #[inline]
     pub const fn from_bytes(bytes: &[u8]) -> &Self {
         // SAFETY: `BStr` is transparent to `[u8]`.
-        unsafe { &*(bytes as *const [u8] as *const BStr) }
+        unsafe { &*(core::mem::transmute::<*const [u8], *const Self>(bytes)) }
Hmm I'm not sure about using `transmute` here. Yes the types are
transparent, but I don't think that we should use it here.
What's your suggestion? I initially tried

let bytes: *const [u8] = bytes;
unsafe { &*bytes.cast() }

but that doesn't compile because of the implicit Sized bound on pointer::cast.
This is AFAIK one of the only places where we cannot get rid of the `as`
cast. So:

    let bytes: *const [u8] = bytes;
    // CAST: `BStr` transparently wraps `[u8]`.
    let bytes = bytes as *const BStr;
    // SAFETY: `bytes` is derived from a reference.
    unsafe { &*bytes }

IMO a `transmute` is worse than an `as` cast :)
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`

Why is transmute worse than an `as` cast?
It's right in the docs: "`transmute` should be the absolute last
resort." [1]. IIRC, Gary was a bit more lenient in its use, but I think
we should avoid it as much as possible such that people copying code or
taking inspiration also don't use it.

So for both cases I'd prefer an `as` cast.

[1]: https://doc.rust-lang.org/std/mem/fn.transmute.html

---
Cheers,
Benno
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help