How do I create a Vec<u8> with variable alignment in Rust?

Viewed 70

I need to create a Vector of u8 whose memory address is sector size aligned. I saw another post which talks about same problem, but when I tried to implement it (playground link), it was not working.

use std::mem;

#[repr(C, align(64))]
struct AlignToSixtyFour([u8; 64]);

unsafe fn aligned_vec(n_bytes: usize) -> Vec<u8> {
    // Lazy math to ensure we always have enough.
    let n_units = (n_bytes / mem::size_of::<AlignToSixtyFour>()) + 1;

    let mut aligned: Vec<AlignToSixtyFour> = Vec::with_capacity(n_units);
    let ptr = aligned.as_mut_ptr();
    let len_units = aligned.len();
    let cap_units = aligned.capacity();

    mem::forget(aligned);

    let av = Vec::from_raw_parts(
        ptr as *mut u8,
        len_units * mem::size_of::<AlignToSixtyFour>(),
        cap_units * mem::size_of::<AlignToSixtyFour>(),
    );
    av
}

fn main() {
    println!("Hello, world!");
    unsafe {
        let mut kp = aligned_vec(1024);
        kp.resize(1024 as usize, 0);
        println!("align_of_val {:?}", mem::align_of_val(&kp));    // should be 64
        println!("align_of_val {:?}", mem::align_of_val(&kp[0])); // should be 64
    }
}

The output:

Hello, world!
align_of_val 8
align_of_val 1

Also the number to which vector should be aligned is variable, not known at compile time.

0 Answers
Related