atomic-rs icon indicating copy to clipboard operation
atomic-rs copied to clipboard

Why compare `align_of`?

Open rise0chen opened this issue 2 years ago • 4 comments

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Test {
    a: u8,
    b: u8,
    c: u8,
    d: u8,
}
fn main() {
    println!("align: {}", core::mem::align_of::<Test>());
    println!("size: {}", core::mem::size_of::<Test>());
}

Size of the struct is 4, align of the struct is 1. The condition is not met. image

rise0chen avatar Jan 17 '22 06:01 rise0chen

I think Atomic<Test > can be converted to AtomicU32

rise0chen avatar Jan 17 '22 06:01 rise0chen

You can use #[repr(align(4))] on your struct to ensure the alignment is sufficient. This is required since this crate will unsafely access your struct as an AtomicU32.

Amanieu avatar Jan 17 '22 07:01 Amanieu

image transmute don't require alignment, how about replace transmute_copy by transmute?

rise0chen avatar Jan 17 '22 09:01 rise0chen

This crate isn't actually transmuting though, it's casting a pointer to your type to a pointer to AtomicU32 and accessing it as an AtomicU32 in-place. This requires that your type be suitably aligned for an AtomicU32.

Amanieu avatar Jan 17 '22 21:01 Amanieu