Transmuting `Box`es of `#[repr(transparent)]` slice-like DSTs

⚓ rust    📅 2025-06-12    👤 surdeus    👁️ 1      

surdeus

Assumming that bytemuck::TransparentWrapper<Self> is a #[repr(transparent)] wrapper of Self, is this function sound?

use std::mem;

#[repr(C)]
pub struct DstArray<H, D> {
    pub header: H,
    pub data: [D],
}

impl<H, D> DstArray<H, D> {
    pub fn wrap<W>(self: Box<Self>) -> Box<W>
    where
        W: bytemuck::TransparentWrapper<Self> +?Sized,
    {
        let self_box = mem::MaybeUninit::new(self);

        // - `W` is transparent wrapper of `Self`
        // - Ptr metadata of `&Self` is length, so the metadata of `&W` must be the same length.
        //
        // Does this imply that we can transmute 
        // `MaybeUninit<Box<Self>>` to `MaybeUninit<Box<W>>`?
        let w_box: mem::MaybeUninit<Box<W>> = unsafe { mem::transmute_copy(&self_box) };
        unsafe { w_box.assume_init() }
    }
}

1 post - 1 participant

Read full topic

🏷️ rust_feed