Soundness of mutable access to union containing an atomic

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

surdeus

Is the following code sound?

#[repr(C)]
union Ptr {
    raw: *mut (),
    atomic: ManuallyDrop<AtomicPtr<()>>,
}

impl Ptr {
    /// Retrieve the pointer stored, no matter if it was stored with `raw` or `atomic`
    fn get_mut(&mut self) -> &mut *mut () {
        // SAFETY: both union members have exactly the same layout, and 
        // accessing an atomic pointer from a mutable reference does not
        // require any synchronization.
        unsafe { &mut self.raw }
    }
}

miri doesn't seem to see any issue with it, and I would say it's sound, but I'd rather ask to be sure on this topic.

10 posts - 4 participants

Read full topic

🏷️ rust_feed