Aligned vs non-aligned write

Been reading Simd-json code for a while and I can't seem to wrap my head around some stuff.

  1. When writing to Vec unsafely using std::mem::write, can it make a difference if you write u32 versus i32?
        let mut base = Vec::new<u32>();
        let v: [i32; 4] = [
            static_cast_i32!(idx_minus_64), // macro for transmute<u32, i32>
            static_cast_i32!(idx_minus_64),
            static_cast_i32!(idx_minus_64),
            static_cast_i32!(idx_minus_64),
        ];
        //skip
        write(base.as_mut_ptr().add(len).cast::<[i32; 4]>(), v);
  1. Does the size of vector impacts alignment?
let is_unaligned = base.len() % 4 != 0;
let write_fn = if is_unaligned {
    std::ptr::write_unaligned
} else {
    std::ptr::write
};

No, the only difference it can make is getting a compile time type error. But at runtime they are the same.

I'm not sure why simd-json is doing those transmutes, but my guess is that this code was somehow translated from C++ due to the use of the name "static cast".

No.

Again, this code may be translated from C++, where allocations are guaranteed to be 16 bytes aligned and so since they start writing at the index vec.len() they will be aligned to 16 bytes if the length is a multiple of 4. This still doesn't clear this up for me though, since they are writing a [i32; 4], whose alignment is still 4 and hence std::ptr::write would have been enough.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.