Is it safe to cast `&[u8]` to `&AlignedBuf([u8])`?

⚓ rust    📅 2025-05-12    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 49 days ago. The information described in this article may have changed.

In my code I want to work with buffers which have a guaranteed alignment, so I created the following helper type:

#[repr(align(8))]
pub struct AlignedBuf(pub [u8]);

impl AlignedBuf {
    /// # Safety
    /// `p` MUST have alignment equal to 8.
    pub unsafe fn from_raw_parts<'a>(p: *const u8, len: usize) -> &'a Self {
        debug_assert_eq!(p as usize % 8, 0);
        debug_assert_eq!(len % 8, 0);
        unsafe {
            let s: &[u8] = core::slice::from_raw_parts(p, len);
            &*(s as *const [u8] as *const Self)
        }
    }
}

I think this code should be sound (assuming the methods are used with correct p and len) and it passes Miri without issues. But on the other hand the Nomicon states:

Currently the only properly supported way to create a custom DST is by making your type generic and performing an unsizing coercion

Should I read it as that the casts are not currently allowed?

2 posts - 2 participants

Read full topic

🏷️ rust_feed